forked from msgpack/msgpack-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectArrayTemplate.java
More file actions
60 lines (50 loc) · 1.59 KB
/
ObjectArrayTemplate.java
File metadata and controls
60 lines (50 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package org.msgpack.template;
import java.io.IOException;
import java.lang.reflect.Array;
import org.msgpack.MessageTypeException;
import org.msgpack.packer.Packer;
import org.msgpack.unpacker.Unpacker;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ObjectArrayTemplate extends AbstractTemplate {
protected Class componentClass;
protected Template componentTemplate;
public ObjectArrayTemplate(Class componentClass, Template componentTemplate) {
this.componentClass = componentClass;
this.componentTemplate = componentTemplate;
}
@Override
public void write(Packer packer, Object v, boolean required)
throws IOException {
if (v == null) {
if (required) {
throw new MessageTypeException("Attempted to write null");
}
packer.writeNil();
return;
}
if (!(v instanceof Object[]) || !componentClass.isAssignableFrom(v.getClass().getComponentType())) {
throw new MessageTypeException();
}
Object[] array = (Object[]) v;
int length = array.length;
packer.writeArrayBegin(length);
for (int i = 0; i < length; i++) {
componentTemplate.write(packer, array[i], required);
}
packer.writeArrayEnd();
}
@Override
public Object read(Unpacker unpacker, Object to, boolean required)
throws IOException {
if (!required && unpacker.trySkipNil()) {
return null;
}
int length = unpacker.readArrayBegin();
Object[] array = (Object[]) Array.newInstance(componentClass, length);
for (int i = 0; i < length; i++) {
array[i] = componentTemplate.read(unpacker, null, required);
}
unpacker.readArrayEnd();
return array;
}
}