Skip to main content

kacrab_protocol/string/
error.rs

1//! Error types for [`crate::string`].
2
3use crate::primitives::PrimitiveError;
4
5/// Error returned by string read/write operations.
6#[derive(Debug, thiserror::Error)]
7#[error("kafka string codec failed")]
8#[non_exhaustive]
9pub struct StringError {
10    /// What specifically went wrong.
11    #[source]
12    pub kind: StringErrorKind,
13}
14
15impl StringError {
16    /// Construct a `StringError` from its kind.
17    #[must_use]
18    pub const fn new(kind: StringErrorKind) -> Self {
19        Self { kind }
20    }
21}
22
23impl From<StringErrorKind> for StringError {
24    fn from(kind: StringErrorKind) -> Self {
25        Self::new(kind)
26    }
27}
28
29impl From<PrimitiveError> for StringError {
30    fn from(err: PrimitiveError) -> Self {
31        Self::new(StringErrorKind::Primitive(err))
32    }
33}
34
35/// Specific reason a string read/write failed.
36#[derive(Debug, thiserror::Error)]
37#[non_exhaustive]
38pub enum StringErrorKind {
39    /// Underlying primitive read failed (length prefix or bytes).
40    #[error(transparent)]
41    Primitive(#[from] PrimitiveError),
42
43    /// String bytes are not valid UTF-8.
44    #[error("invalid UTF-8 string: {source}")]
45    InvalidUtf8 {
46        /// UTF-8 validation failure.
47        #[source]
48        source: std::str::Utf8Error,
49    },
50
51    /// Non-nullable variant got the null marker (negative length / `0` varint).
52    #[error("non-nullable string has null marker; use the nullable variant")]
53    UnexpectedNull,
54
55    /// Length prefix is negative on a non-nullable encoding.
56    #[error("negative length {length} on non-nullable string")]
57    NegativeLength {
58        /// The negative length read.
59        length: i32,
60    },
61
62    /// String length exceeds the maximum encodable length.
63    #[error("string length {length} exceeds maximum {max}")]
64    TooLong {
65        /// Offending length: the value being encoded, or `usize::MAX` as a
66        /// sentinel when a wire length prefix did not fit in `usize`.
67        length: usize,
68        /// Protocol-constant maximum (e.g. `i32::MAX`), not a tunable.
69        max: usize,
70    },
71}