Error

Enum Error 

Source
pub enum Error {
    InsufficientData {
        requested: usize,
        available: usize,
    },
    OutOfBounds {
        pos: usize,
        requested: usize,
        len: usize,
    },
    NotValid,
    NotValidAscii,
    NotValidUTF8(Utf8Error),
    Custom(Box<dyn Error + Send + Sync>),
}
Expand description

The error type for ByteCraft operations.

This enum represents all possible errors that can occur when working with binary data using ByteCraft. Each variant provides detailed information about what went wrong to help with debugging and error handling.

§Error Handling Patterns

use bytecraft::error::{Error, Result};
use bytecraft::reader::ByteReader;

fn process_data(data: &[u8]) -> Result<String> {
    let mut reader = ByteReader::new(data);
     
    // Handle specific errors
    let value = match reader.read::<u32>() {
        Ok(v) => v,
        Err(Error::InsufficientData { requested, available }) => {
            return Err(Error::Custom(
                format!("Not enough data: need {}, have {}", requested, available).into()
            ));
        }
        Err(e) => return Err(e),
    };
     
    Ok(value.to_string())
}

Variants§

§

InsufficientData

Insufficient data available for the requested operation.

This error occurs when trying to read more bytes than are available in the remaining data stream. It provides exact information about how much data was requested versus how much is actually available.

§Examples

use bytecraft::error::Error;
use bytecraft::reader::ByteReader;

let data = [0x01, 0x02]; // Only 2 bytes
let mut reader = ByteReader::new(&data[..]);

// Trying to read u32 (4 bytes) from 2 bytes of data
match reader.read::<u32>() {
    Err(Error::InsufficientData { requested, available }) => {
        assert_eq!(requested, 4);
        assert_eq!(available, 2);
    }
    _ => panic!("Expected InsufficientData error"),
}

§When This Error Occurs

  • Reading primitive types when not enough bytes remain
  • Reading strings or arrays of specific sizes
  • Any operation that requires more data than available

Fields

§requested: usize

The number of bytes requested for the operation

§available: usize

The number of bytes actually available in the stream

§

OutOfBounds

Attempted to seek or set position outside the valid data boundaries.

This error occurs when trying to set the cursor position to an invalid location, either beyond the end of the data or to a negative position.

§Examples

use bytecraft::error::Error;
use bytecraft::reader::ByteReader;
use bytecraft::common::SeekFrom;

let data = [0x01, 0x02, 0x03, 0x04];
let mut reader = ByteReader::new(&data[..]);

// Trying to seek beyond the end of data
match reader.seek(SeekFrom::Start(100)) {
    Err(Error::OutOfBounds { pos, requested, len }) => {
        assert_eq!(pos, 0); // current position
        assert_eq!(requested, 100); // requested position
        assert_eq!(len, 4); // actual data length
    }
    _ => panic!("Expected OutOfBounds error"),
}

§When This Error Occurs

  • Setting position beyond data length using set_position()
  • Seeking to invalid positions using seek()
  • Skipping more bytes than available using skip()

Fields

§pos: usize

The current position in the data stream

§requested: usize

The requested position or shift that caused the error

§len: usize

The actual length of the data

§

NotValid

Data is not valid for the requested operation.

This is a generic error for cases where the data format is invalid or doesn’t match expected patterns. It’s typically used when more specific error types don’t apply.

§Examples

use bytecraft::error::Error;
use bytecraft::reader::ByteReader;

// This might occur when parsing custom formats with invalid flags
// or when data doesn't match expected scheme, pattern or magic numbers

§When This Error Occurs

  • Invalid magic numbers or file signatures
  • Unexpected flag values in binary protocols
  • Data that doesn’t conform to expected format specifications
§

NotValidAscii

Data contains non-ASCII characters when ASCII was expected.

This error occurs specifically when trying to read ASCII strings and the data contains bytes that are not valid ASCII characters (values outside the 0-127 range).

§Examples

use bytecraft::error::Error;
use bytecraft::reader::ByteReader;

// Data containing non-ASCII bytes
let data: &[u8] = "📚".as_bytes(); // Valid UTF-8 but non-ASCII // "\xF0\x9F\x93\x9A"
let mut reader: ByteReader = ByteReader::new(data);

match reader.read_ascii(4) {
    Err(Error::NotValidAscii) => {
        // Data contains non-ASCII bytes
    }
    _ => panic!("Expected NotValidAscii error"),
}

§When This Error Occurs

  • Using read_ascii() on data containing non-ASCII bytes
  • Parsing ASCII-only protocols with invalid character data
§

NotValidUTF8(Utf8Error)

UTF-8 string data is malformed or invalid.

This error wraps the underlying Utf8Error from Rust’s standard library and occurs when trying to convert byte sequences to UTF-8 strings that contain invalid UTF-8 sequences.

§Examples

use bytecraft::error::Error;
use bytecraft::reader::ByteReader;
use core::str;

// Invalid UTF-8 sequence
let data = [0xC0, 0x80]; // Invalid UTF-8
let mut reader = ByteReader::new(&data[..]);

match reader.read_bytes(2).and_then(|bytes| Ok(str::from_utf8(bytes))) {
    Err(_) => {
        // Would result in NotValidUTF8 error if used in string reading methods
    }
    _ => {}
}

§When This Error Occurs

  • Reading UTF-8 strings from malformed byte sequences
  • Parsing text data that contains invalid UTF-8
  • Converting binary data to strings without proper validation
§

Custom(Box<dyn Error + Send + Sync>)

A custom error from user-defined types or operations.

This variant allows Readable and Peekable implementations to return their own custom errors while maintaining compatibility with the ByteCraft error system. It can contain any error type that implements std::error::Error + Send + Sync.

§Examples

use bytecraft::error::Error;
use bytecraft::error::Result;
use bytecraft::readable::Readable;
use bytecraft::reader::ReadStream;
use bytecraft::common::SeekFrom;
use std::error::Error as StdError;

#[derive(Debug)]
struct CustomParseError(String);

impl std::fmt::Display for CustomParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Custom parse error: {}", self.0)
    }
}

impl StdError for CustomParseError {}

struct MyCustomType;

impl<'a> Readable<'a> for MyCustomType {
    fn read<'r>(mut s: ReadStream<'a, 'r>) -> Result<Self> {
        // Some custom validation that fails
        Err(Error::Custom(Box::new(CustomParseError("Invalid format".to_string()))))
    }
}

§When This Error Occurs

  • User-defined Readable implementations returning custom errors
  • Domain-specific validation failures in complex data structures
  • Wrapping external library errors in ByteCraft’s error system

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementations§

§

impl Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.