View Javadoc
1   package org.djutils.serialization.serializers;
2   
3   import org.djunits.unit.Unit;
4   import org.djutils.serialization.DisplayType;
5   import org.djutils.serialization.EndianUtil;
6   import org.djutils.serialization.SerializationUnits;
7   
8   /**
9    * Abstract class to (de)serializes a DJUNITS value.
10   * <p>
11   * Copyright (c) 2019-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>.
13   * </p>
14   * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a>
15   * @param <U> the unit type
16   * @param <T> the object type
17   */
18  public abstract class ObjectWithUnitSerializer<U extends Unit<U>, T> extends ObjectSerializer<T>
19  {
20      /**
21       * Construct a new ObjectWithUnitSerializer.
22       * @param type byte; the field type (returned by the <code>fieldType</code> method)
23       * @param dataClassName String; returned by the dataClassName method
24       */
25      public ObjectWithUnitSerializer(final byte type, final String dataClassName)
26      {
27          super(type, dataClassName);
28      }
29  
30      /**
31       * Code a unit, including MoneyUnits.
32       * @param unit U; the unit to code in the byte array
33       * @param message byte[]; the byte array
34       * @param pointer Pointer; the start pointer in the byte array
35       * @param endianUtil EndianUtil; encoder to use for multi-byte values
36       */
37      protected void encodeUnit(final U unit, final byte[] message, final Pointer pointer, final EndianUtil endianUtil)
38      {
39          SerializationUnits unitType = SerializationUnits.getUnitType(unit);
40          message[pointer.getAndIncrement(1)] = unitType.getCode();
41          DisplayType displayType = DisplayType.getDisplayType(unit);
42          message[pointer.getAndIncrement(1)] = displayType.getByteCode();
43      }
44  
45      /**
46       * Retrieve and decode a DJUNITS unit.
47       * @param buffer byte[]; the encoded data
48       * @param pointer Pointer; position in the encoded data where the unit is to be decoded from
49       * @param endianUtil EndianUtil; decoder for multi-byte values
50       * @return Unit
51       */
52      @SuppressWarnings("unchecked")
53      protected U getUnit(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
54      {
55          SerializationUnits unitType = SerializationUnits.getUnitType(buffer[pointer.getAndIncrement(1)]);
56          DisplayType displayType = DisplayType.getDisplayType(unitType, 0 + buffer[pointer.getAndIncrement(1)]);
57          return (U) displayType.getDjunitsType();
58      }
59  
60  }