0
|
1 //
|
|
2 // MessagePack for Java
|
|
3 //
|
|
4 // Copyright (C) 2009 - 2013 FURUHASHI Sadayuki
|
|
5 //
|
|
6 // Licensed under the Apache License, Version 2.0 (the "License");
|
|
7 // you may not use this file except in compliance with the License.
|
|
8 // You may obtain a copy of the License at
|
|
9 //
|
|
10 // http://www.apache.org/licenses/LICENSE-2.0
|
|
11 //
|
|
12 // Unless required by applicable law or agreed to in writing, software
|
|
13 // distributed under the License is distributed on an "AS IS" BASIS,
|
|
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15 // See the License for the specific language governing permissions and
|
|
16 // limitations under the License.
|
|
17 //
|
|
18 package org.msgpack.template;
|
|
19
|
|
20 import java.io.IOException;
|
|
21 import java.util.Collection;
|
|
22 import java.util.LinkedList;
|
|
23 import org.msgpack.packer.Packer;
|
|
24 import org.msgpack.unpacker.Unpacker;
|
|
25 import org.msgpack.MessageTypeException;
|
|
26
|
|
27 public class CollectionTemplate<E> extends AbstractTemplate<Collection<E>> {
|
|
28 private Template<E> elementTemplate;
|
|
29
|
|
30 public CollectionTemplate(Template<E> elementTemplate) {
|
|
31 this.elementTemplate = elementTemplate;
|
|
32 }
|
|
33
|
|
34 public void write(Packer pk, Collection<E> target, boolean required)
|
|
35 throws IOException {
|
|
36 if (target == null) {
|
|
37 if (required) {
|
|
38 throw new MessageTypeException("Attempted to write null");
|
|
39 }
|
|
40 pk.writeNil();
|
|
41 return;
|
|
42 }
|
|
43 Collection<E> col = target;
|
|
44 pk.writeArrayBegin(col.size());
|
|
45 for (E e : col) {
|
|
46 elementTemplate.write(pk, e);
|
|
47 }
|
|
48 pk.writeArrayEnd();
|
|
49 }
|
|
50
|
|
51 public Collection<E> read(Unpacker u, Collection<E> to, boolean required)
|
|
52 throws IOException {
|
|
53 if (!required && u.trySkipNil()) {
|
|
54 return null;
|
|
55 }
|
|
56 int n = u.readArrayBegin();
|
|
57 if (to == null) {
|
|
58 to = new LinkedList<E>();
|
|
59 } else {
|
|
60 to.clear();
|
|
61 }
|
|
62 for (int i = 0; i < n; i++) {
|
|
63 E e = elementTemplate.read(u, null);
|
|
64 to.add(e);
|
|
65 }
|
|
66 u.readArrayEnd();
|
|
67 return to;
|
|
68 }
|
|
69 }
|