stream_wave_parser/
error.rs

1//! Types to represent errors in `stream-wave-parser`.
2
3/// A specialized `Result` type for `stream-wave-parser`.
4pub type Result<T> = std::result::Result<T, Error>;
5
6type BoxError = Box<dyn std::error::Error + Send + Sync>;
7
8/// The error type for `stream-wave-parser`.
9pub enum Error {
10    /// The data does not begin `RIFF`.
11    RiffChunkHeaderIsNotFound,
12
13    /// The RIFF data does not have a `WAVE` chunk.
14    WaveChunkHeaderIsNotFound,
15
16    /// The RIFF WAVE data does not have a `fmt ` chunk before `data` chunk.
17    FmtChunkIsNotFound,
18
19    /// The length of `data` chunk is not enough for the amount that represented by the `length` field.
20    DataIsNotEnough,
21
22    /// The [`WaveChannelMixer`][`crate::WaveChannelMixer`] is only support PCM integer (`pcm_format` is 1).
23    MixerConstruction(&'static str),
24
25    /// The user defined type created by [`Error::custom()`].
26    Custom(BoxError),
27}
28
29impl Error {
30    /// Creates [`Error::Custom`].
31    pub fn custom(e: impl std::error::Error + Send + Sync + 'static) -> Self {
32        Self::Custom(Box::new(e))
33    }
34}
35
36impl std::error::Error for Error {}
37
38impl std::fmt::Debug for Error {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
40        if let Self::Custom(e) = self {
41            return format!("custom: {e:?}").fmt(f);
42        }
43
44        <Self as std::fmt::Display>::fmt(self, f)
45    }
46}
47
48impl std::fmt::Display for Error {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
50        use Error::*;
51
52        match self {
53            RiffChunkHeaderIsNotFound => "`RIFF` label is not found.".fmt(f),
54
55            WaveChunkHeaderIsNotFound => "`WAVE` label is not found.".fmt(f),
56
57            FmtChunkIsNotFound => "`fmt ` label is not found.".fmt(f),
58
59            DataIsNotEnough => "data is not enough.".fmt(f),
60
61            MixerConstruction(reason) => {
62                for msg in ["failed to construct a `WaveChannelMixer`: ", reason, "."] {
63                    msg.fmt(f)?;
64                }
65                Ok(())
66            }
67
68            Custom(e) => format!("custom: {e}.").fmt(f),
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    #[test]
78    fn test_fmt() {
79        assert_eq!(
80            format!("{}", Error::MixerConstruction("foo")),
81            "failed to construct a `WaveChannelMixer`: foo."
82        );
83    }
84}