Mercurial > hg > Members > sugi > MessagePack-java
comparison src/main/java/org/msgpack/template/OrdinalEnumTemplate.java @ 0:cb825acd883a
first commit
author | sugi |
---|---|
date | Sat, 18 Oct 2014 15:06:15 +0900 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:cb825acd883a |
---|---|
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.HashMap; | |
22 | |
23 import org.msgpack.MessageTypeException; | |
24 import org.msgpack.annotation.OrdinalEnum; | |
25 import org.msgpack.packer.Packer; | |
26 import org.msgpack.unpacker.Unpacker; | |
27 | |
28 public class OrdinalEnumTemplate<T> extends AbstractTemplate<T> { | |
29 protected T[] entries; | |
30 protected HashMap<T, Integer> reverse; | |
31 protected boolean strict; | |
32 | |
33 public OrdinalEnumTemplate(Class<T> targetClass) { | |
34 entries = targetClass.getEnumConstants(); | |
35 reverse = new HashMap<T, Integer>(); | |
36 for (int i = 0; i < entries.length; i++) { | |
37 reverse.put(entries[i], i); | |
38 } | |
39 strict = !targetClass.isAnnotationPresent(OrdinalEnum.class) | |
40 || targetClass.getAnnotation(OrdinalEnum.class).strict(); | |
41 } | |
42 | |
43 @Override | |
44 public void write(Packer pk, T target, boolean required) throws IOException { | |
45 if (target == null) { | |
46 if (required) { | |
47 throw new MessageTypeException("Attempted to write null"); | |
48 } | |
49 pk.writeNil(); | |
50 return; | |
51 } | |
52 Integer ordinal = reverse.get(target); | |
53 if (ordinal == null) { | |
54 throw new MessageTypeException( | |
55 new IllegalArgumentException("ordinal: " + ordinal)); | |
56 } | |
57 pk.write((int) ordinal); | |
58 } | |
59 | |
60 @Override | |
61 public T read(Unpacker pac, T to, boolean required) throws IOException, | |
62 MessageTypeException { | |
63 if (!required && pac.trySkipNil()) { | |
64 return null; | |
65 } | |
66 | |
67 int ordinal = pac.readInt(); | |
68 | |
69 if (ordinal < entries.length) { | |
70 return entries[ordinal]; | |
71 } | |
72 | |
73 if (!strict) { | |
74 return null; | |
75 } | |
76 | |
77 throw new MessageTypeException(new IllegalArgumentException("ordinal: " | |
78 + ordinal)); | |
79 | |
80 } | |
81 } |