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.Map;
|
|
22 import java.util.HashMap;
|
|
23 import org.msgpack.packer.Packer;
|
|
24 import org.msgpack.unpacker.Unpacker;
|
|
25 import org.msgpack.MessageTypeException;
|
|
26
|
|
27 public class MapTemplate<K, V> extends AbstractTemplate<Map<K, V>> {
|
|
28 private Template<K> keyTemplate;
|
|
29 private Template<V> valueTemplate;
|
|
30
|
|
31 public MapTemplate(Template<K> keyTemplate, Template<V> valueTemplate) {
|
|
32 this.keyTemplate = keyTemplate;
|
|
33 this.valueTemplate = valueTemplate;
|
|
34 }
|
|
35
|
|
36 public void write(Packer pk, Map<K, V> target, boolean required)
|
|
37 throws IOException {
|
|
38 if (!(target instanceof Map)) {
|
|
39 if (target == null) {
|
|
40 if (required) {
|
|
41 throw new MessageTypeException("Attempted to write null");
|
|
42 }
|
|
43 pk.writeNil();
|
|
44 return;
|
|
45 }
|
|
46 throw new MessageTypeException("Target is not a Map but " + target.getClass());
|
|
47 }
|
|
48 Map<K, V> map = (Map<K, V>) target;
|
|
49 pk.writeMapBegin(map.size());
|
|
50 for (Map.Entry<K, V> pair : map.entrySet()) {
|
|
51 keyTemplate.write(pk, pair.getKey());
|
|
52 valueTemplate.write(pk, pair.getValue());
|
|
53 }
|
|
54 pk.writeMapEnd();
|
|
55 }
|
|
56
|
|
57 public Map<K, V> read(Unpacker u, Map<K, V> to, boolean required)
|
|
58 throws IOException {
|
|
59 if (!required && u.trySkipNil()) {
|
|
60 return null;
|
|
61 }
|
|
62 int n = u.readMapBegin();
|
|
63 Map<K, V> map;
|
|
64 if (to != null) {
|
|
65 map = (Map<K, V>) to;
|
|
66 map.clear();
|
|
67 } else {
|
|
68 map = new HashMap<K, V>(n);
|
|
69 }
|
|
70 for (int i = 0; i < n; i++) {
|
|
71 K key = keyTemplate.read(u, null);
|
|
72 V value = valueTemplate.read(u, null);
|
|
73 map.put(key, value);
|
|
74 }
|
|
75 u.readMapEnd();
|
|
76 return map;
|
|
77 }
|
|
78 }
|