package org.djutils.serialization.serializers; import org.djunits.unit.Unit; import org.djutils.serialization.DisplayType; import org.djutils.serialization.EndianUtil; import org.djutils.serialization.SerializationUnits; /** * Abstract class to (de)serializes a DJUNITS value. *

* Copyright (c) 2019-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
* BSD-style license. See DJUNITS License. *

* @author Alexander Verbraeck * @param the unit type * @param the object type */ public abstract class ObjectWithUnitSerializer, T> extends ObjectSerializer { /** * Construct a new ObjectWithUnitSerializer. * @param type byte; the field type (returned by the fieldType method) * @param dataClassName String; returned by the dataClassName method */ public ObjectWithUnitSerializer(final byte type, final String dataClassName) { super(type, dataClassName); } /** * Code a unit, including MoneyUnits. * @param unit the unit to code in the byte array * @param message the byte array * @param pointer the start pointer in the byte array * @param endianUtil EndianUtil; encoder to use for multi-byte values */ protected void encodeUnit(final U unit, final byte[] message, final Pointer pointer, final EndianUtil endianUtil) { SerializationUnits unitType = SerializationUnits.getUnitType(unit); message[pointer.getAndIncrement(1)] = unitType.getCode(); DisplayType displayType = DisplayType.getDisplayType(unit); message[pointer.getAndIncrement(1)] = displayType.getByteCode(); } /** * Retrieve and decode a DJUNITS unit. * @param buffer byte[]; the encoded data * @param pointer Pointer; position in the encoded data where the unit is to be decoded from * @param endianUtil EndianUtil; decoder for multi-byte values * @return Unit */ @SuppressWarnings("unchecked") protected U getUnit(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil) { SerializationUnits unitType = SerializationUnits.getUnitType(buffer[pointer.getAndIncrement(1)]); DisplayType displayType = DisplayType.getDisplayType(unitType, 0 + buffer[pointer.getAndIncrement(1)]); return (U) displayType.getDjunitsType(); } }