cantools/
encode.rs

1//! Module providing utility traits for encoding CAN-bus data.
2//!
3//! The module provides two traits: [TryEncode], and [Encode]. [try_encode](TryEncode::try_encode)
4//! models the possibility that the encoding fails whereas [encode](Encode::encode) models the not
5//! failable encoding. If [encode](Encode::encode) fails internally, it panics.
6//!
7//! # Example
8//! ```
9//! use cantools::data::CANRead;
10//! use cantools::signals::Bit;
11//! use cantools::encode::{TryEncode, Encode};
12//!
13//! let bit = Bit::new(20);
14//! let mut data = [0u8, 0u8, 0u8, 0u8];
15//!
16//! let result = bit.try_encode(&mut data, true);
17//! bit.encode(&mut data, false);
18//! ```
19
20use crate::data::CANWrite;
21
22/// Type representing possible encoding errors.
23#[derive(Debug, PartialEq)]
24pub enum EncodeError {
25    /// There is not enough byte data available to encode a value.
26    NotEnoughData,
27    /// The value to encode is smaller than the minimum value encodable.
28    MinError,
29    /// The value to encode is greater than the maximum value encodable.
30    MaxError,
31}
32
33/// A trait modeling the failable encoding of data.
34pub trait TryEncode<T> {
35    /// A type modelling the different possible failures of the encoding.
36    type Error;
37
38    /// Tries to encode `value` into `data`.
39    fn try_encode<D: CANWrite>(&self, data: &mut D, value: T) -> Result<(), Self::Error>;
40}
41
42/// A trait modeling the not failable encoding of data.
43///
44/// [Encode] is sub-trait of [TryEncode]. [encode](Encode::encode) is implemented using
45/// [try_encode](TryEncode::try_encode). If [try_encode](TryEncode::try_encode) succeeds,
46/// [encode](Encode::encode) returns. Otherwise, [encode](Encode::encode) panics.
47pub trait Encode<T>: TryEncode<T> {
48    /// Encodes `value` into the CAN-bus data `data`.
49    ///
50    /// # Panics
51    /// [encode](Encode::encode) panics if the call to [try_encode](TryEncode::try_encode) in the
52    /// implementation returns the error variant.
53    fn encode<D: CANWrite>(&self, data: &mut D, value: T) {
54        match self.try_encode(data, value) {
55            Ok(_) => (),
56            Err(_) => panic!("cannot encode data"),
57        }
58    }
59}