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-2020 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  
34   * @param message byte[]; the byte array
35  
36   * @param pointer Pointer; the start pointer in the byte array
37  
38       * @param endianUtil EndianUtil; encoder to use for multi-byte values
39       */
40      protected void encodeUnit(final U unit, final byte[] message, final Pointer pointer, final EndianUtil endianUtil)
41      {
42          SerializationUnits unitType = SerializationUnits.getUnitType(unit);
43          message[pointer.getAndIncrement(1)] = unitType.getCode();
44          DisplayType displayType = DisplayType.getDisplayType(unit);
45          message[pointer.getAndIncrement(1)] = displayType.getByteCode();
46      }
47  
48      /**
49       * Retrieve and decode a DJUNITS unit.
50       * @param buffer byte[]; the encoded data
51       * @param pointer Pointer; position in the encoded data where the unit is to be decoded from
52       * @param endianUtil EndianUtil; decoder for multi-byte values
53       * @return Unit
54       */
55      @SuppressWarnings("unchecked")
56      protected U getUnit(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
57      {
58          SerializationUnits unitType = SerializationUnits.getUnitType(buffer[pointer.getAndIncrement(1)]);
59          DisplayType displayType = DisplayType.getDisplayType(unitType, 0 + buffer[pointer.getAndIncrement(1)]);
60          return (U) displayType.getDjunitsType();
61      }
62  
63  }