-
Notifications
You must be signed in to change notification settings - Fork 236
/
Codec.java
121 lines (95 loc) · 3.27 KB
/
Codec.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package org.fxmisc.richtext.model;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javafx.scene.paint.Color;
public interface Codec<T> {
String getName();
void encode(DataOutputStream os, T t) throws IOException;
T decode(DataInputStream is) throws IOException;
static final Codec<String> STRING_CODEC = new Codec<String>() {
@Override
public String getName() {
return "string";
}
@Override
public void encode(DataOutputStream os, String s) throws IOException {
os.writeUTF(s);
}
@Override
public String decode(DataInputStream is) throws IOException {
return is.readUTF();
}
};
static final Codec<Color> COLOR_CODEC = new Codec<Color>() {
@Override
public String getName() {
return "color";
}
@Override
public void encode(DataOutputStream os, Color c)
throws IOException {
os.writeDouble(c.getRed());
os.writeDouble(c.getGreen());
os.writeDouble(c.getBlue());
os.writeDouble(c.getOpacity());
}
@Override
public Color decode(DataInputStream is) throws IOException {
return Color.color(
is.readDouble(),
is.readDouble(),
is.readDouble(),
is.readDouble());
}
};
static <T> Codec<List<T>> listCodec(Codec<T> elemCodec) {
return SuperCodec.collectionListCodec(elemCodec);
}
static <T> Codec<Collection<T>> collectionCodec(Codec<T> elemCodec) {
return SuperCodec.upCast(SuperCodec.collectionListCodec(elemCodec));
}
static <T> Codec<Optional<T>> optionalCodec(Codec<T> elemCodec) {
return new Codec<Optional<T>>() {
@Override
public String getName() {
return "optional<" + elemCodec.getName() + ">";
}
@Override
public void encode(DataOutputStream os, Optional<T> ot) throws IOException {
if(ot.isPresent()) {
os.writeBoolean(true);
elemCodec.encode(os, ot.get());
} else {
os.writeBoolean(false);
}
}
@Override
public Optional<T> decode(DataInputStream is) throws IOException {
return is.readBoolean()
? Optional.of(elemCodec.decode(is))
: Optional.empty();
}
};
}
static <E extends Enum<E>> Codec<E> enumCodec(Class<E> enumType) {
return new Codec<E>() {
@Override
public String getName() {
return enumType.getSimpleName();
}
@Override
public void encode(DataOutputStream os, E e) throws IOException {
os.writeInt(e.ordinal());
}
@Override
public E decode(DataInputStream is) throws IOException {
int ord = is.readInt();
return enumType.getEnumConstants()[ord];
}
};
}
}