djs_model/util/
sound_data.rs1use core::fmt;
4
5use bytes::Bytes;
6use compact_str::CompactString;
7use serde::{Serialize, Serializer};
8
9use super::image_data::write_base64;
10
11#[derive(Clone, PartialEq, Eq, Hash)]
32pub struct SoundData {
33 data: Bytes,
34 content_type: CompactString,
35}
36
37impl SoundData {
38 pub fn new(data: impl Into<Bytes>) -> Result<Self, SoundDataError> {
48 let data = data.into();
49 let content_type = detect(&data).ok_or(SoundDataError)?;
50 Ok(Self {
51 data,
52 content_type: CompactString::const_new(content_type),
53 })
54 }
55
56 #[must_use]
60 pub fn with_content_type(
61 data: impl Into<Bytes>,
62 content_type: impl Into<CompactString>,
63 ) -> Self {
64 Self {
65 data: data.into(),
66 content_type: content_type.into(),
67 }
68 }
69
70 #[must_use]
74 pub const fn data(&self) -> &Bytes {
75 &self.data
76 }
77
78 #[must_use]
82 pub fn content_type(&self) -> &str {
83 &self.content_type
84 }
85}
86
87impl fmt::Display for SoundData {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str("data:")?;
91 f.write_str(&self.content_type)?;
92 f.write_str(";base64,")?;
93 write_base64(&self.data, f)
94 }
95}
96
97impl fmt::Debug for SoundData {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 f.debug_struct("SoundData")
101 .field("content_type", &self.content_type)
102 .field("len", &self.data.len())
103 .finish()
104 }
105}
106
107impl Serialize for SoundData {
108 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
109 serializer.collect_str(self)
110 }
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub struct SoundDataError;
119
120impl fmt::Display for SoundDataError {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.write_str("unknown sound format (expected MP3 or Ogg)")
123 }
124}
125
126impl core::error::Error for SoundDataError {}
127
128fn detect(data: &[u8]) -> Option<&'static str> {
130 match data {
131 [b'O', b'g', b'g', b'S', ..] => Some("audio/ogg"),
132 [b'I', b'D', b'3', ..] => Some("audio/mpeg"),
134 [0xff, second, ..] if second & 0xe0 == 0xe0 => Some("audio/mpeg"),
135 _ => None,
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 #[test]
144 fn detects_signatures() {
145 let detected = |data: &[u8]| SoundData::new(data.to_vec()).map(|sound| sound.content_type);
146 assert_eq!(detected(b"ID3\x04\0").unwrap(), "audio/mpeg");
147 assert_eq!(detected(b"\xff\xfb\x90\x64").unwrap(), "audio/mpeg");
148 assert_eq!(detected(b"OggS").unwrap(), "audio/ogg");
149 assert_eq!(detected(b"\xff\xd8\xff"), Err(SoundDataError));
150 assert_eq!(detected(b"RIFF"), Err(SoundDataError));
151 assert_eq!(detected(b""), Err(SoundDataError));
152 }
153
154 #[test]
155 fn serializes_and_hides_the_contents() {
156 let sound = SoundData::with_content_type(&b"abc"[..], "audio/mpeg");
157 assert_eq!(
158 serde_json::to_string(&sound).unwrap(),
159 r#""data:audio/mpeg;base64,YWJj""#
160 );
161 assert_eq!(
162 format!("{sound:?}"),
163 r#"SoundData { content_type: "audio/mpeg", len: 3 }"#
164 );
165 }
166}