1 package org.djutils.serialization.serializers;
2
3 import org.djunits.unit.Unit;
4 import org.djunits.unit.scale.IdentityScale;
5 import org.djunits.value.ValueRuntimeException;
6 import org.djunits.value.storage.StorageType;
7 import org.djunits.value.vdouble.matrix.base.DoubleMatrix;
8 import org.djunits.value.vdouble.matrix.base.DoubleMatrixInterface;
9 import org.djunits.value.vdouble.matrix.data.DoubleMatrixData;
10 import org.djunits.value.vdouble.scalar.base.DoubleScalarInterface;
11 import org.djunits.value.vdouble.vector.base.DoubleVectorInterface;
12 import org.djutils.serialization.EndianUtil;
13 import org.djutils.serialization.FieldTypes;
14 import org.djutils.serialization.SerializationException;
15
16
17
18
19
20
21
22
23
24
25
26
27
28 public class DoubleMatrixSerializer<U extends Unit<U>, S extends DoubleScalarInterface<U, S>,
29 V extends DoubleVectorInterface<U, S, V>, M extends DoubleMatrixInterface<U, S, V, M>>
30 extends ArrayOrMatrixWithUnitSerializer<U, M>
31 {
32
33 public DoubleMatrixSerializer()
34 {
35 super(FieldTypes.DOUBLE_64_UNIT_MATRIX, "Djunits_DoubleMatrix", 2);
36 }
37
38
39 @Override
40 public int size(final M adm) throws SerializationException
41 {
42 try
43 {
44 return 4 + 4 + 2 + 8 * adm.rows() * adm.cols();
45 }
46 catch (ValueRuntimeException e)
47 {
48 throw new SerializationException(e);
49 }
50 }
51
52
53 @Override
54 public void serialize(final M adm, final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
55 throws SerializationException
56 {
57 try
58 {
59 endianUtil.encodeInt(adm.rows(), buffer, pointer.getAndIncrement(4));
60 endianUtil.encodeInt(adm.cols(), buffer, pointer.getAndIncrement(4));
61 encodeUnit(adm.getDisplayUnit(), buffer, pointer, endianUtil);
62 for (int i = 0; i < adm.rows(); i++)
63 {
64 for (int j = 0; j < adm.cols(); j++)
65 {
66 endianUtil.encodeDouble(adm.get(i, j).getSI(), buffer, pointer.getAndIncrement(8));
67 }
68 }
69 }
70 catch (ValueRuntimeException e)
71 {
72 throw new SerializationException(e);
73 }
74 }
75
76
77 @Override
78 public M deSerialize(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil) throws SerializationException
79 {
80 try
81 {
82 int height = endianUtil.decodeInt(buffer, pointer.getAndIncrement(4));
83 int width = endianUtil.decodeInt(buffer, pointer.getAndIncrement(4));
84 Unit<? extends Unit<?>> unit = getUnit(buffer, pointer, endianUtil);
85 double[][] array = new double[height][width];
86 for (int i = 0; i < height; i++)
87 {
88 for (int j = 0; j < width; j++)
89 {
90 array[i][j] = endianUtil.decodeDouble(buffer, pointer.getAndIncrement(8));
91 }
92 }
93 DoubleMatrixData fvd = DoubleMatrixData.instantiate(array, IdentityScale.SCALE, StorageType.DENSE);
94 return DoubleMatrix.instantiateAnonymous(fvd, unit);
95 }
96 catch (ValueRuntimeException exception)
97 {
98 throw new SerializationException(exception);
99 }
100 }
101
102 }