View Javadoc
1   package org.djutils.serialization.serializers;
2   
3   import org.djutils.serialization.EndianUtil;
4   import org.djutils.serialization.SerializationException;
5   
6   /**
7    * Serializer for primitive data array classes. *
8    * <p>
9    * Copyright (c) 2019-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
10   * BSD-style license. See <a href="https://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
11   * <p>
12   * @version $Revision$, $LastChangedDate$, by $Author$, <br>
13   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
14   * @author <a href="https://www.tudelft.nl/staff/p.knoppers/">Peter Knoppers</a>
15   * @author <a href="https://www.transport.citg.tudelft.nl">Wouter Schakel</a>
16   * @param <T> array type, e.g. int[]
17   */
18  public abstract class BasicPrimitiveArrayOrMatrixSerializer<T extends Object> extends BasicSerializer<T>
19  {
20      /** Size of one element of the encoded data. */
21      private final int elementSize;
22  
23      /** Number of dimensions of the data. */
24      private final int numberOfDimensions;
25  
26      /**
27       * Construct a new BasicPrimitiveArrayOrMatrixSerializer.
28       * @param type byte; the field type (returned by the <code>fieldType</code> method)
29       * @param elementSize int; the number of bytes needed to encode one additional array element
30       * @param dataClassName String; returned by the dataClassName method
31       * @param numberOfDimensions int; number of dimensions (1 for array, 2 for matrix)
32       */
33      public BasicPrimitiveArrayOrMatrixSerializer(final byte type, final int elementSize, final String dataClassName,
34              final int numberOfDimensions)
35      {
36          super(type, dataClassName);
37          this.elementSize = elementSize;
38          this.numberOfDimensions = numberOfDimensions;
39      }
40  
41      @Override
42      public final int sizeWithPrefix(final T object) throws SerializationException
43      {
44          return 1 + size(object);
45      }
46  
47      @Override
48      public final void serializeWithPrefix(final T object, final byte[] buffer, final Pointer pointer,
49              final EndianUtil endianUtil) throws SerializationException
50      {
51          buffer[pointer.getAndIncrement(1)] = fieldType();
52          serialize(object, buffer, pointer, endianUtil);
53      }
54  
55      /**
56       * Retrieve the number of bytes needed to encode one additional array element.
57       * @return int; the number of bytes needed to encode one additional array element
58       */
59      public final int getElementSize()
60      {
61          return this.elementSize;
62      }
63  
64      @Override
65      public final int getNumberOfDimensions()
66      {
67          return this.numberOfDimensions;
68      }
69  
70  }