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.MatBuilder;
008import edu.wpi.first.math.Matrix;
009import edu.wpi.first.math.Nat;
010import edu.wpi.first.math.Num;
011import edu.wpi.first.math.proto.Wpimath.ProtobufMatrix;
012import edu.wpi.first.util.protobuf.Protobuf;
013import us.hebi.quickbuf.Descriptors.Descriptor;
014
015public class MatrixProto<R extends Num, C extends Num>
016    implements Protobuf<Matrix<R, C>, ProtobufMatrix> {
017  private final Nat<R> m_rows;
018  private final Nat<C> m_cols;
019
020  /**
021   * Constructs the {@link Protobuf} implementation.
022   *
023   * @param rows The number of rows of the matrices this serializer processes.
024   * @param cols The number of cols of the matrices this serializer processes.
025   */
026  public MatrixProto(Nat<R> rows, Nat<C> cols) {
027    m_rows = rows;
028    m_cols = cols;
029  }
030
031  @Override
032  public Class<Matrix<R, C>> getTypeClass() {
033    @SuppressWarnings("unchecked")
034    var clazz = (Class<Matrix<R, C>>) (Class<?>) Matrix.class;
035    return clazz;
036  }
037
038  @Override
039  public Descriptor getDescriptor() {
040    return ProtobufMatrix.getDescriptor();
041  }
042
043  @Override
044  public ProtobufMatrix createMessage() {
045    return ProtobufMatrix.newInstance();
046  }
047
048  @Override
049  public Matrix<R, C> unpack(ProtobufMatrix msg) {
050    if (msg.getNumRows() != m_rows.getNum() || msg.getNumCols() != m_cols.getNum()) {
051      throw new IllegalArgumentException(
052          "Tried to unpack msg "
053              + msg
054              + " with "
055              + msg.getNumRows()
056              + " rows and "
057              + msg.getNumCols()
058              + " columns into Matrix with "
059              + m_rows.getNum()
060              + " rows and "
061              + m_cols.getNum()
062              + " columns");
063    }
064    return MatBuilder.fill(m_rows, m_cols, Protobuf.unpackArray(msg.getData()));
065  }
066
067  @Override
068  public void pack(ProtobufMatrix msg, Matrix<R, C> value) {
069    msg.setNumRows(value.getNumRows());
070    msg.setNumCols(value.getNumCols());
071    Protobuf.packArray(msg.getMutableData(), value.getData());
072  }
073}