1 package com.github.davidmoten.rx2.buffertofile;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.DataInputStream;
6 import java.io.DataOutputStream;
7 import java.io.IOException;
8 import java.io.Serializable;
9 import java.nio.charset.Charset;
10
11 import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerBytes;
12 import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerJavaIO;
13
14 public final class Serializers {
15
16 private static final Charset UTF_8 = Charset.forName("UTF-8");
17
18 private Serializers() {
19
20 }
21
22 public static <T extends Serializable> Serializer<T> javaIO() {
23
24 return new SerializerJavaIO<T>();
25 }
26
27 public static Serializer<byte[]> bytes() {
28
29 return new SerializerBytes();
30 }
31
32 public static Serializer<String> utf8() {
33
34 return string(UTF_8);
35 }
36
37 public static Serializer<String> string(Charset charset) {
38 return new SerializerString(charset);
39 }
40
41 public static <T> Serializer<T> from(DataSerializer<T> ds) {
42 return new WrappedDataSerializer<T>(ds);
43 }
44
45 private static final class WrappedDataSerializer<T> implements Serializer<T> {
46
47 private final DataSerializer<T> ds;
48
49 WrappedDataSerializer(DataSerializer<T> ds) {
50 this.ds = ds;
51 }
52
53 @Override
54 public byte[] serialize(T t) throws IOException {
55 ByteArrayOutputStream bytes;
56 int cap = ds.sizeHint();
57 if (cap > 0)
58 bytes = new ByteArrayOutputStream(ds.sizeHint());
59 else
60 bytes = new ByteArrayOutputStream();
61 DataOutputStream out = new DataOutputStream(bytes);
62 ds.serialize(t, out);
63 out.close();
64 return bytes.toByteArray();
65 }
66
67 @Override
68 public T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
69 ByteArrayInputStream is = new ByteArrayInputStream(bytes);
70 DataInputStream in = new DataInputStream(is);
71 T t = ds.deserialize(in);
72 in.close();
73 return t;
74 }
75
76 }
77
78 }