rusty_opus/error.rs
1//! The error type shared by the encoder, decoder, and packet utilities.
2
3use std::fmt;
4
5/// Why an encoder, decoder, or packet operation failed.
6///
7/// The variants mirror libopus' error codes ([`Error::code`] returns the libopus
8/// integer), and each carries a short static description of the specific
9/// condition. `Display` prints that description, so code that formatted the
10/// former `&'static str` errors produces identical text.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub enum Error {
14 /// An argument was outside its valid range (libopus `OPUS_BAD_ARG`).
15 BadArg(&'static str),
16 /// The caller's output buffer cannot hold the result
17 /// (libopus `OPUS_BUFFER_TOO_SMALL`).
18 BufferTooSmall(&'static str),
19 /// The input packet is malformed, truncated, or otherwise not valid Opus
20 /// (libopus `OPUS_INVALID_PACKET`).
21 InvalidPacket(&'static str),
22 /// An internal codec stage failed (libopus `OPUS_INTERNAL_ERROR`).
23 Internal(&'static str),
24}
25
26impl Error {
27 /// The equivalent libopus error code (always negative).
28 #[must_use]
29 pub const fn code(&self) -> i32 {
30 match self {
31 Self::BadArg(_) => -1,
32 Self::BufferTooSmall(_) => -2,
33 Self::Internal(_) => -3,
34 Self::InvalidPacket(_) => -4,
35 }
36 }
37
38 /// The description of the specific condition.
39 #[must_use]
40 pub const fn message(&self) -> &'static str {
41 match self {
42 Self::BadArg(m)
43 | Self::BufferTooSmall(m)
44 | Self::InvalidPacket(m)
45 | Self::Internal(m) => m,
46 }
47 }
48}
49
50impl fmt::Display for Error {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 f.write_str(self.message())
53 }
54}
55
56impl std::error::Error for Error {}