opus_codec/
error.rs

1//! Error types for Opus codec operations
2
3use crate::bindings::{
4    OPUS_ALLOC_FAIL, OPUS_BAD_ARG, OPUS_BUFFER_TOO_SMALL, OPUS_INTERNAL_ERROR, OPUS_INVALID_PACKET,
5    OPUS_INVALID_STATE, OPUS_UNIMPLEMENTED,
6};
7use std::fmt;
8
9/// Convenient result alias for this crate.
10pub type Result<T> = std::result::Result<T, Error>;
11
12/// Opus error variants.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum Error {
15    /// Bad argument passed to a function.
16    BadArg,
17    /// Provided buffer was too small.
18    BufferTooSmall,
19    /// Internal libopus error.
20    InternalError,
21    /// Packet is invalid or unsupported.
22    InvalidPacket,
23    /// Feature not implemented.
24    Unimplemented,
25    /// Invalid state.
26    InvalidState,
27    /// Memory allocation failure.
28    AllocFail,
29    /// Unknown error code.
30    Unknown(i32),
31}
32
33impl Error {
34    /// Map a libopus error code to [`Error`].
35    #[must_use]
36    pub fn from_code(code: i32) -> Self {
37        match code {
38            OPUS_BAD_ARG => Self::BadArg,
39            OPUS_BUFFER_TOO_SMALL => Self::BufferTooSmall,
40            OPUS_INTERNAL_ERROR => Self::InternalError,
41            OPUS_INVALID_PACKET => Self::InvalidPacket,
42            OPUS_UNIMPLEMENTED => Self::Unimplemented,
43            OPUS_INVALID_STATE => Self::InvalidState,
44            OPUS_ALLOC_FAIL => Self::AllocFail,
45            _ => Self::Unknown(code),
46        }
47    }
48
49    /// Convert [`Error`] back to libopus code.
50    #[must_use]
51    pub const fn to_code(self) -> i32 {
52        match self {
53            Self::BadArg => OPUS_BAD_ARG,
54            Self::BufferTooSmall => OPUS_BUFFER_TOO_SMALL,
55            Self::InternalError => OPUS_INTERNAL_ERROR,
56            Self::InvalidPacket => OPUS_INVALID_PACKET,
57            Self::Unimplemented => OPUS_UNIMPLEMENTED,
58            Self::InvalidState => OPUS_INVALID_STATE,
59            Self::AllocFail => OPUS_ALLOC_FAIL,
60            Self::Unknown(code) => code,
61        }
62    }
63}
64
65impl fmt::Display for Error {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::BadArg => write!(f, "Bad arguments passed to Opus function"),
69            Self::BufferTooSmall => write!(f, "Buffer too small"),
70            Self::InternalError => write!(f, "Internal Opus error"),
71            Self::InvalidPacket => write!(f, "Invalid packet"),
72            Self::Unimplemented => write!(f, "Unimplemented feature"),
73            Self::InvalidState => write!(f, "Invalid state"),
74            Self::AllocFail => write!(f, "Memory allocation failed"),
75            Self::Unknown(code) => write!(f, "Unknown Opus error code: {code}"),
76        }
77    }
78}
79
80impl std::error::Error for Error {}