View Javadoc
1   package org.djutils.serialization.serializers;
2   
3   import org.djunits.unit.Unit;
4   import org.djunits.value.vfloat.scalar.base.FloatScalar;
5   import org.djutils.serialization.EndianUtil;
6   import org.djutils.serialization.FieldTypes;
7   import org.djutils.serialization.SerializationException;
8   
9   /**
10   * (De)serializes a DJUNITS FloatScalar.
11   * <p>
12   * Copyright (c) 2019-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
13   * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>.
14   * <p>
15   * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a>
16   * @param <U> the unit type
17   * @param <S> the scalar type
18   */
19  public class FloatScalarSerializer<U extends Unit<U>, S extends FloatScalar<U, S>>
20          extends ObjectWithUnitSerializer<U, S>
21  {
22      /** */
23      public FloatScalarSerializer()
24      {
25          super(FieldTypes.FLOAT_32_UNIT, "Djunits_FloatScalar");
26      }
27  
28      /** {@inheritDoc} */
29      @Override
30      public int size(final S afs) throws SerializationException
31      {
32          return 2 + 4;
33      }
34  
35      /** {@inheritDoc} */
36      @Override
37      public void serialize(final S afs, final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
38              throws SerializationException
39      {
40          encodeUnit(afs.getDisplayUnit(), buffer, pointer, endianUtil);
41          float v = afs.getSI();
42          endianUtil.encodeFloat(v, buffer, pointer.getAndIncrement(4));
43      }
44  
45      /** {@inheritDoc} */
46      @Override
47      public S deSerialize(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil) throws SerializationException
48      {
49          U unit = getUnit(buffer, pointer, endianUtil);
50          S afs = FloatScalar.instantiateAnonymous(endianUtil.decodeFloat(buffer, pointer.getAndIncrement(4)),
51                  unit.getStandardUnit());
52          afs.setDisplayUnit(unit);
53          return afs;
54      }
55  
56  }