001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.math.struct;
006
007import edu.wpi.first.math.Nat;
008import edu.wpi.first.math.Num;
009import edu.wpi.first.math.Vector;
010import edu.wpi.first.util.struct.Struct;
011import java.nio.ByteBuffer;
012import org.ejml.simple.SimpleMatrix;
013
014public final class VectorStruct<R extends Num> implements Struct<Vector<R>> {
015  private final int m_rows;
016
017  /**
018   * Constructs the {@link Struct} implementation.
019   *
020   * @param rows The number of rows of the vectors this serializer processes.
021   */
022  public VectorStruct(Nat<R> rows) {
023    m_rows = rows.getNum();
024  }
025
026  @Override
027  public Class<Vector<R>> getTypeClass() {
028    @SuppressWarnings("unchecked")
029    var clazz = (Class<Vector<R>>) (Class<?>) Vector.class;
030    return clazz;
031  }
032
033  @Override
034  public String getTypeName() {
035    return "Vector__" + m_rows;
036  }
037
038  @Override
039  public int getSize() {
040    return kSizeDouble * m_rows;
041  }
042
043  @Override
044  public String getSchema() {
045    return "double data[" + m_rows + "]";
046  }
047
048  @Override
049  public Vector<R> unpack(ByteBuffer bb) {
050    var storage = new SimpleMatrix(Struct.unpackDoubleArray(bb, m_rows));
051    return new Vector<R>(storage);
052  }
053
054  @Override
055  public void pack(ByteBuffer bb, Vector<R> value) {
056    Struct.packArray(bb, value.getData());
057  }
058}