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