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.djutils.serialization.EndianUtil;
6   import org.djutils.serialization.FieldTypes;
7   import org.djutils.serialization.SerializationException;
8   
9   /**
10   * (De)serializes a DJUNITS DoubleScalar.
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 DoubleScalarSerializer<U extends Unit<U>, S extends DoubleScalar<U, S>>
20          extends ObjectWithUnitSerializer<U, S>
21  {
22      /** */
23      public DoubleScalarSerializer()
24      {
25          super(FieldTypes.DOUBLE_64_UNIT, "Djunits_DoubleScalar");
26      }
27  
28      @Override
29      public int size(final S ads) throws SerializationException
30      {
31          return 2 + 8;
32      }
33  
34      @Override
35      public void serialize(final S ads, final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
36              throws SerializationException
37      {
38          encodeUnit(ads.getDisplayUnit(), buffer, pointer, endianUtil);
39          double v = ads.getSI();
40          endianUtil.encodeDouble(v, buffer, pointer.getAndIncrement(8));
41      }
42  
43      @Override
44      public S deSerialize(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil) throws SerializationException
45      {
46          U unit = getUnit(buffer, pointer, endianUtil);
47          S afd = DoubleScalar.instantiateAnonymous(endianUtil.decodeDouble(buffer, pointer.getAndIncrement(8)),
48                  unit.getStandardUnit());
49          afd.setDisplayUnit(unit);
50          return afd;
51      }
52  }