Skip to main content

CodecError

Struct CodecError 

Source
pub struct CodecError { /* private fields */ }
Expand description

Error returned by canonical encoding and decoding operations.

Implementations§

Source§

impl CodecError

Source

pub const fn new(kind: CodecErrorKind, message: &'static str) -> Self

Creates a new codec error with a stable kind and actionable message.

Source

pub const fn kind(&self) -> CodecErrorKind

Returns the stable error category.

Examples found in repository?
examples/protocol_message.rs (line 72)
58fn main() -> Result<(), CodecError> {
59    let message = ProtocolMessage {
60        id: 42,
61        kind: MessageKind::Data(vec![1, 2, 3]),
62    };
63
64    let encoded = encode_to_vec(&message)?;
65    assert_eq!(encoded, [42, 0, 0, 0, 1, 3, 0, 0, 0, 1, 2, 3]);
66    assert_eq!(
67        decode_from_slice_exact::<ProtocolMessage>(&encoded)?,
68        message
69    );
70
71    let err = decode_from_slice_exact::<MessageKind>(&[9]).unwrap_err();
72    assert_eq!(err.kind(), CodecErrorKind::InvalidValue);
73    assert!(err.message().contains("unknown MessageKind tag"));
74
75    Ok(())
76}
More examples
Hide additional examples
examples/basic_encoding.rs (line 21)
5fn main() -> Result<(), CodecError> {
6    let port = 8080u16;
7    let encoded = encode_to_vec(&port)?;
8    assert_eq!(encoded, [0x90, 0x1f]);
9    assert_eq!(decode_from_slice_exact::<u16>(&encoded)?, port);
10
11    let text = "api";
12    let encoded = encode_to_vec(text)?;
13    assert_eq!(encoded, [3, 0, 0, 0, b'a', b'p', b'i']);
14    assert_eq!(decode_from_slice_exact::<String>(&encoded)?, text);
15
16    let (value, remaining) = decode_from_slice::<u8>(&[1, 2])?;
17    assert_eq!(value, 1);
18    assert_eq!(remaining, 1);
19
20    let err = decode_from_slice_exact::<u8>(&[1, 2]).unwrap_err();
21    assert_eq!(err.kind(), CodecErrorKind::TrailingBytes);
22
23    Ok(())
24}
Source

pub const fn message(&self) -> &'static str

Returns a human-readable error message.

Examples found in repository?
examples/protocol_message.rs (line 73)
58fn main() -> Result<(), CodecError> {
59    let message = ProtocolMessage {
60        id: 42,
61        kind: MessageKind::Data(vec![1, 2, 3]),
62    };
63
64    let encoded = encode_to_vec(&message)?;
65    assert_eq!(encoded, [42, 0, 0, 0, 1, 3, 0, 0, 0, 1, 2, 3]);
66    assert_eq!(
67        decode_from_slice_exact::<ProtocolMessage>(&encoded)?,
68        message
69    );
70
71    let err = decode_from_slice_exact::<MessageKind>(&[9]).unwrap_err();
72    assert_eq!(err.kind(), CodecErrorKind::InvalidValue);
73    assert!(err.message().contains("unknown MessageKind tag"));
74
75    Ok(())
76}
Source

pub const fn unexpected_eof() -> Self

Input ended before the requested bytes could be read.

Source

pub const fn invalid_value(message: &'static str) -> Self

Value used an invalid byte or tag.

Examples found in repository?
examples/protocol_message.rs (lines 51-53)
47    fn decode<R: DecodeSource + ?Sized>(reader: &mut R) -> Result<Self, CodecError> {
48        match u8::decode(reader)? {
49            0 => Ok(Self::Ping),
50            1 => Vec::<u8>::decode(reader).map(Self::Data),
51            _ => Err(CodecError::invalid_value(
52                "unknown MessageKind tag: expected 0x00 or 0x01",
53            )),
54        }
55    }
Source

pub const fn length_overflow(message: &'static str) -> Self

Decoded length cannot be represented or safely processed.

Source

pub const fn trailing_bytes() -> Self

Exact decode found bytes after the decoded value.

Source

pub const fn write_failed() -> Self

Writer failed to accept bytes.

Source

pub const fn read_failed() -> Self

Reader failed for a reason other than end of input.

Trait Implementations§

Source§

impl Clone for CodecError

Source§

fn clone(&self) -> CodecError

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for CodecError

Source§

impl Debug for CodecError

Source§

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

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

impl Display for CodecError

Source§

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

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

impl Eq for CodecError

Source§

impl Error for CodecError

Available on crate feature std only.
1.30.0 · 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
Source§

impl PartialEq for CodecError

Source§

fn eq(&self, other: &CodecError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for CodecError

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.