technocreatives / dbc-codegen

Generate Rust structs for messages from a dbc (CAN bus definition) file.
Apache License 2.0
43 stars 22 forks source link

Use generated enums in `new` and setters. #39

Open marcelbuesing opened 3 years ago

marcelbuesing commented 3 years ago

I think it would be great to make more use of the generated enums as I think it makes the api more compile-time safe and convenient to use. Right now it mostly saves you from putting .into() everywhere but furthermore I think a proper type makes it easier to use the api correctly. My proposal would be to rename the setters, analogue to the getters, to include a raw suffix and add a fn that uses the enum parameter. Same for new.

/// Construct new Bar from values
    pub fn new(one: u8, two: f32, three: BarThree, four: u8, xtype: BarType) -> Result<Self, CanError> {
        let mut res = Self { raw: [0u8; 8] };
        res.set_one(one)?;
        res.set_two(two)?;
        res.set_three(three)?;
        res.set_four(four)?;
        res.set_xtype(xtype)?;
        Ok(res)
    }

    /// Construct new Bar from values
    pub fn new_raw(one: u8, two: f32, three: u8, four: u8, xtype: bool) -> Result<Self, CanError> {
        let mut res = Self { raw: [0u8; 8] };
        res.set_one(one)?;
        res.set_two(two)?;
        res.set_three(three)?;
        res.set_four(four)?;
        res.set_xtype(xtype)?;
        Ok(res)
  }

    /// Three
    ///
    /// - Min: 0
    /// - Max: 7
    /// - Unit: ""
    /// - Receivers: Dolor
    #[inline(always)]
    pub fn three(&self) -> BarThree {
        self.three_raw().into()
    }

    /// Get raw value of Three
    ///
    /// - Start bit: 13
    /// - Signal size: 3 bits
    /// - Factor: 1
    /// - Offset: 0
    /// - Byte order: BigEndian
    /// - Value type: Unsigned
    #[inline(always)]
    pub fn three_raw(&self) -> u8 {
        let signal = self.raw.view_bits::<Msb0>()[10..13].load_be::<u8>();

        signal
    }

    /// Set value of Three
    #[inline(always)]
    pub fn set_three_raw(&mut self, value: u8) -> Result<&mut Self, CanError> {
        #[cfg(feature = "range_checked")]
        if value < 0_u8 || 7_u8 < value {
            return Err(CanError::ParameterOutOfRange { message_id: 512 });
        }
        self.raw.view_bits_mut::<Msb0>()[10..13].store_be(value);
        Ok(self)
    }

    /// Set value of Three
    #[inline(always)]
    pub fn set_three(&mut self, value: BarThree) -> Result<&mut Self, CanError> {
        self.set_three_raw(value.into())
    }