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