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.vfloat.matrix.base.FloatMatrix;
8 import org.djunits.value.vfloat.matrix.base.FloatMatrixInterface;
9 import org.djunits.value.vfloat.matrix.data.FloatMatrixData;
10 import org.djunits.value.vfloat.scalar.base.FloatScalarInterface;
11 import org.djunits.value.vfloat.vector.base.FloatVectorInterface;
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 FloatMatrixSerializer<U extends Unit<U>, S extends FloatScalarInterface<U, S>,
29 V extends FloatVectorInterface<U, S, V>, M extends FloatMatrixInterface<U, S, V, M>>
30 extends ArrayOrMatrixWithUnitSerializer<U, M>
31 {
32
33 public FloatMatrixSerializer()
34 {
35 super(FieldTypes.FLOAT_32_UNIT_MATRIX, "Djunits_FloatMatrix", 2);
36 }
37
38
39 @Override
40 public int size(final M afm) throws SerializationException
41 {
42 try
43 {
44 return 4 + 4 + 2 + 4 * afm.rows() * afm.cols();
45 }
46 catch (ValueRuntimeException e)
47 {
48 throw new SerializationException(e);
49 }
50 }
51
52
53 @Override
54 public void serialize(final M afm, final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
55 throws SerializationException
56 {
57 try
58 {
59 endianUtil.encodeInt(afm.rows(), buffer, pointer.getAndIncrement(4));
60 endianUtil.encodeInt(afm.cols(), buffer, pointer.getAndIncrement(4));
61 encodeUnit(afm.getDisplayUnit(), buffer, pointer, endianUtil);
62 for (int i = 0; i < afm.rows(); i++)
63 {
64 for (int j = 0; j < afm.cols(); j++)
65 {
66 endianUtil.encodeFloat(afm.get(i, j).getSI(), buffer, pointer.getAndIncrement(4));
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 int height = endianUtil.decodeInt(buffer, pointer.getAndIncrement(4));
81 int width = endianUtil.decodeInt(buffer, pointer.getAndIncrement(4));
82 Unit<? extends Unit<?>> unit = getUnit(buffer, pointer, endianUtil);
83 float[][] array = new float[height][width];
84 for (int i = 0; i < height; i++)
85 {
86 for (int j = 0; j < width; j++)
87 {
88 array[i][j] = endianUtil.decodeFloat(buffer, pointer.getAndIncrement(4));
89 }
90 }
91 try
92 {
93 FloatMatrixData fvd = FloatMatrixData.instantiate(array, IdentityScale.SCALE, StorageType.DENSE);
94 return FloatMatrix.instantiateAnonymous(fvd, unit);
95 }
96 catch (ValueRuntimeException exception)
97 {
98 throw new SerializationException(exception);
99 }
100 }
101
102 }