justcode_core/
error.rs

1//! Error types for justcode encoding/decoding.
2
3use thiserror::Error;
4
5#[cfg(feature = "std")]
6use std::string::String;
7
8#[cfg(not(feature = "std"))]
9extern crate alloc;
10#[cfg(not(feature = "std"))]
11use alloc::string::String;
12
13/// Result type for justcode operations.
14pub type Result<T> = core::result::Result<T, JustcodeError>;
15
16/// Errors that can occur during encoding or decoding.
17#[derive(Error, Debug, Clone, PartialEq, Eq)]
18pub enum JustcodeError {
19    /// Not enough bytes to decode the value.
20    #[error("unexpected end of input: expected {expected} bytes, got {got}")]
21    UnexpectedEndOfInput { expected: usize, got: usize },
22
23    /// Size limit exceeded during decoding.
24    #[error("size limit exceeded: limit is {limit}, but {requested} bytes were requested")]
25    SizeLimitExceeded { limit: usize, requested: usize },
26
27    /// Invalid varint encoding.
28    #[error("invalid varint encoding")]
29    InvalidVarint,
30
31    /// Custom error message.
32    #[error("{0}")]
33    Custom(String),
34}
35
36impl JustcodeError {
37    /// Create a custom error with a message.
38    pub fn custom(msg: impl Into<String>) -> Self {
39        Self::Custom(msg.into())
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn test_error_display() {
49        let err = JustcodeError::UnexpectedEndOfInput {
50            expected: 10,
51            got: 5,
52        };
53        assert!(err.to_string().contains("unexpected end of input"));
54    }
55
56    #[test]
57    fn test_custom_error() {
58        let err = JustcodeError::custom("test error");
59        assert_eq!(err.to_string(), "test error");
60    }
61}
62