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.proto;
006
007import edu.wpi.first.math.Nat;
008import edu.wpi.first.math.Num;
009import edu.wpi.first.math.Vector;
010import edu.wpi.first.math.proto.Wpimath.ProtobufVector;
011import edu.wpi.first.util.protobuf.Protobuf;
012import org.ejml.simple.SimpleMatrix;
013import us.hebi.quickbuf.Descriptors.Descriptor;
014
015public final class VectorProto<R extends Num> implements Protobuf<Vector<R>, ProtobufVector> {
016  private final Nat<R> m_rows;
017
018  /**
019   * Constructs the {@link Protobuf} implementation.
020   *
021   * @param rows The number of rows of the vectors this serializer processes.
022   */
023  public VectorProto(Nat<R> rows) {
024    m_rows = rows;
025  }
026
027  @Override
028  public Class<Vector<R>> getTypeClass() {
029    @SuppressWarnings("unchecked")
030    var clazz = (Class<Vector<R>>) (Class<?>) Vector.class;
031    return clazz;
032  }
033
034  @Override
035  public Descriptor getDescriptor() {
036    return ProtobufVector.getDescriptor();
037  }
038
039  @Override
040  public ProtobufVector createMessage() {
041    return ProtobufVector.newInstance();
042  }
043
044  @Override
045  public Vector<R> unpack(ProtobufVector msg) {
046    if (msg.getRows().length() != m_rows.getNum()) {
047      throw new IllegalArgumentException(
048          "Tried to unpack msg "
049              + msg
050              + " with "
051              + msg.getRows().length()
052              + " rows into Vector with "
053              + m_rows.getNum()
054              + " rows");
055    }
056    var storage = new SimpleMatrix(Protobuf.unpackArray(msg.getRows()));
057    return new Vector<R>(storage);
058  }
059
060  @Override
061  public void pack(ProtobufVector msg, Vector<R> value) {
062    Protobuf.packArray(msg.getMutableRows(), value.getData());
063  }
064}