chisel_decoders/
common.rs

1//! Common types used throughout the rest of the crate
2use std::borrow::Cow;
3use std::fmt::{Debug, Display, Formatter};
4
5/// General result type used by a decoder instance
6pub type DecoderResult<T> = Result<T, DecoderError>;
7
8/// Enumeration of different decoder errors
9#[derive(Debug, Copy, Clone, PartialEq)]
10pub enum DecoderErrorCode {
11    /// Something went pear-shaped in the underlying stream
12    StreamFailure,
13    /// Detected an invalid byte sequence
14    InvalidByteSequence,
15    /// Out of range error
16    OutOfRange,
17    /// The end of the input has been reached
18    EndOfInput,
19}
20
21/// Structure for encoding errors
22#[derive(Debug, Clone)]
23pub struct DecoderError {
24    /// The error code
25    pub code: DecoderErrorCode,
26
27    /// Associated error message
28    pub message: Cow<'static, str>,
29}
30
31impl Display for DecoderError {
32    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
33        write!(f, "Code: {:?}, Message: {}", self.code, self.message)
34    }
35}
36
37/// Helper macro for generating errors
38#[macro_export]
39macro_rules! decoder_error {
40    ($code : expr, $msg : expr) => {
41        DecoderError {
42            code: $code,
43            message: $msg.into(),
44        }
45    };
46}
47
48#[macro_export]
49macro_rules! end_of_input {
50    () => {
51        Err(DecoderError {
52            code: DecoderErrorCode::EndOfInput,
53            message: "end of input reached".into(),
54        })
55    };
56}
57
58#[macro_export]
59macro_rules! invalid_byte_sequence {
60    () => {
61        Err(DecoderError {
62            code: DecoderErrorCode::InvalidByteSequence,
63            message: "invalid byte sequence".into(),
64        })
65    };
66}