Skip to main content

prolink_proto/
error.rs

1// SPDX-License-Identifier: GPL-3.0-only
2
3//! The one error type every codec in this crate returns.
4
5use std::fmt;
6
7/// What went wrong decoding or encoding a Pro DJ Link message.
8#[derive(Debug, thiserror::Error)]
9pub enum Error {
10    /// The datagram does not carry the Pro DJ Link magic, or a message does not
11    /// carry the magic its format requires.
12    #[error("bad magic: expected {expected}, got {got}")]
13    BadMagic {
14        /// What the format requires.
15        expected: HexBytes,
16        /// What the bytes held.
17        got: HexBytes,
18    },
19
20    /// The buffer ends before a field this format requires.
21    ///
22    /// For a stream protocol this is the *expected* outcome of trying to decode
23    /// too early, so callers distinguish it from [`Error::Malformed`] to decide
24    /// between "wait for more bytes" and "drop the connection".
25    #[error("truncated: need {need} bytes at offset {at}, {have} available")]
26    Truncated {
27        /// How many bytes the field needs.
28        need: usize,
29        /// Where in the buffer it starts.
30        at: usize,
31        /// How many bytes remain from there.
32        have: usize,
33    },
34
35    /// A field holds a value the format does not allow. Unlike
36    /// [`Error::Truncated`], more bytes will not help.
37    #[error("malformed at offset {at}: {reason}")]
38    Malformed {
39        /// Where the offending field starts.
40        at: usize,
41        /// What is wrong with it.
42        reason: String,
43    },
44
45    /// A length prefix claims more than any real message carries. Rejected
46    /// before allocating, so a corrupt or hostile word costs a parse failure
47    /// rather than four gigabytes.
48    #[error("implausible length {length} for {what} (limit {limit})")]
49    ImplausibleLength {
50        /// What was being read.
51        what: &'static str,
52        /// The length the bytes claimed.
53        length: u64,
54        /// The ceiling this codec enforces.
55        limit: u64,
56    },
57
58    /// A `binrw`-derived codec failed.
59    #[error(transparent)]
60    Binrw(#[from] binrw::Error),
61}
62
63impl Error {
64    /// True when more bytes could make this parse succeed.
65    ///
66    /// The distinction that matters on a TCP stream: a dbserver message is
67    /// framed by nothing but its own contents, so running off the end of the
68    /// buffer means "wait", and anything else means "this connection is not
69    /// speaking the protocol".
70    pub fn is_truncated(&self) -> bool {
71        match self {
72            Self::Truncated { .. } => true,
73            Self::Binrw(inner) => inner.is_eof(),
74            _ => false,
75        }
76    }
77
78    pub(crate) fn malformed(at: usize, reason: impl Into<String>) -> Self {
79        Self::Malformed {
80            at,
81            reason: reason.into(),
82        }
83    }
84}
85
86/// Result alias for this crate.
87pub type Result<T, E = Error> = std::result::Result<T, E>;
88
89/// A short byte string rendered as hex in error messages.
90#[derive(Clone, PartialEq, Eq)]
91pub struct HexBytes(pub Vec<u8>);
92
93impl fmt::Debug for HexBytes {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        fmt::Display::fmt(self, f)
96    }
97}
98
99impl fmt::Display for HexBytes {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        for byte in &self.0 {
102            write!(f, "{byte:02x}")?;
103        }
104        Ok(())
105    }
106}
107
108impl From<&[u8]> for HexBytes {
109    fn from(bytes: &[u8]) -> Self {
110        Self(bytes.to_vec())
111    }
112}