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