xmachines_codec/
codecs.rs1use std::fmt;
5use std::sync::Arc;
6
7use serde_json::Value;
8
9use crate::{json, Error, EventCodec, SnapshotCodec};
10
11#[derive(Clone)]
17pub struct Codec {
18 name: String,
19 media_types: Vec<String>,
20 events: Option<Arc<dyn EventCodec>>,
21 emitted: Option<Arc<dyn EventCodec>>,
22 snapshots: Option<Arc<dyn SnapshotCodec>>,
23}
24
25impl fmt::Debug for Codec {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 f.debug_struct("Codec")
28 .field("name", &self.name)
29 .field("media_types", &self.media_types)
30 .field("events", &self.events.is_some())
31 .field("emitted", &self.emitted.is_some())
32 .field("snapshots", &self.snapshots.as_ref().map(|s| s.format()))
33 .finish()
34 }
35}
36
37impl Codec {
38 pub fn new(name: impl Into<String>) -> Self {
40 Self { name: name.into(), media_types: Vec::new(), events: None, emitted: None, snapshots: None }
41 }
42
43 pub fn with_media_types(mut self, media_types: &[&str]) -> Self {
46 self.media_types = media_types.iter().map(|t| t.to_ascii_lowercase()).collect();
47 self
48 }
49
50 pub fn with_events(mut self, events: Arc<dyn EventCodec>) -> Self {
52 self.events = Some(events);
53 self
54 }
55
56 pub fn with_emitted(mut self, emitted: Arc<dyn EventCodec>) -> Self {
58 self.emitted = Some(emitted);
59 self
60 }
61
62 pub fn with_snapshots(mut self, snapshots: Arc<dyn SnapshotCodec>) -> Self {
64 self.snapshots = Some(snapshots);
65 self
66 }
67
68 pub fn name(&self) -> &str {
70 &self.name
71 }
72
73 pub fn media_types(&self) -> &[String] {
75 &self.media_types
76 }
77
78 pub fn media_type(&self) -> Option<&str> {
80 self.media_types.first().map(String::as_str)
81 }
82
83 pub fn events(&self) -> Option<&Arc<dyn EventCodec>> {
85 self.events.as_ref()
86 }
87
88 pub fn emitted(&self) -> Option<&Arc<dyn EventCodec>> {
90 self.emitted.as_ref()
91 }
92
93 pub fn snapshots(&self) -> Option<&Arc<dyn SnapshotCodec>> {
95 self.snapshots.as_ref()
96 }
97}
98
99#[derive(Clone)]
104pub struct Codecs {
105 codecs: Vec<Codec>,
106}
107
108impl fmt::Debug for Codecs {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 f.debug_list().entries(self.codecs.iter()).finish()
111 }
112}
113
114impl Default for Codecs {
115 fn default() -> Self {
116 Self::new()
117 }
118}
119
120impl Codecs {
121 pub fn new() -> Self {
123 Self { codecs: vec![json::codec()] }
124 }
125
126 pub fn register(&mut self, codec: Codec) -> Result<&mut Self, Error> {
130 for other in self.codecs.iter().filter(|c| c.name != codec.name) {
131 if let Some(t) = codec.media_types.iter().find(|t| other.media_types.contains(t)) {
132 return Err(Error::Conflict(format!(
133 "codec \"{}\": media type {t} is codec \"{}\"'s",
134 codec.name, other.name
135 )));
136 }
137 let format = |c: &Codec| c.snapshots.as_ref().map(|s| s.format());
138 if let Some(f) = format(&codec).filter(|f| format(other) == Some(*f)) {
139 return Err(Error::Conflict(format!(
140 "codec \"{}\": snapshot format {f} is codec \"{}\"'s",
141 codec.name, other.name
142 )));
143 }
144 }
145 match self.codecs.iter_mut().find(|c| c.name == codec.name) {
146 Some(slot) => *slot = codec,
147 None => self.codecs.push(codec),
148 }
149 Ok(self)
150 }
151
152 pub fn get(&self, name: &str) -> Option<&Codec> {
154 self.codecs.iter().find(|c| c.name == name)
155 }
156
157 pub fn names(&self) -> impl Iterator<Item = &str> {
160 self.codecs.iter().map(|c| c.name.as_str())
161 }
162
163 pub fn by_media_type(&self, content_type: &str) -> Option<&Codec> {
165 let media = content_type.split(';').next().unwrap_or("").trim();
166 self.codecs.iter().find(|c| c.media_types.iter().any(|t| t.eq_ignore_ascii_case(media)))
167 }
168
169 pub fn decode_snapshot(&self, record: &[u8]) -> Result<Value, Error> {
172 let &format = record.first().ok_or_else(|| Error::Decode("empty snapshot record".into()))?;
173 let codec = self
174 .codecs
175 .iter()
176 .filter_map(|c| c.snapshots.as_ref())
177 .find(|s| s.format() == format)
178 .ok_or(Error::UnknownFormat(format))?;
179 codec.decode(record)
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use serde_json::json;
186
187 use super::*;
188
189 struct Raw(u8);
190
191 impl SnapshotCodec for Raw {
192 fn format(&self) -> u8 {
193 self.0
194 }
195
196 fn encode(&self, _: crate::Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
197 out.push(self.0);
198 Ok(())
199 }
200
201 fn decode(&self, _: &[u8]) -> Result<Value, Error> {
202 Ok(json!({ "raw": self.0 }))
203 }
204 }
205
206 #[test]
207 fn records_find_their_codec() {
208 let mut codecs = Codecs::new();
209 codecs
210 .register(Codec::new("raw").with_media_types(&["Application/Raw"]).with_snapshots(Arc::new(Raw(9))))
211 .unwrap();
212 assert_eq!(codecs.names().collect::<Vec<_>>(), ["json", "raw"]);
213 assert_eq!(codecs.by_media_type("application/raw; v=1").unwrap().name(), "raw");
214 assert_eq!(codecs.by_media_type("TEXT/JSON").unwrap().name(), "json");
215 assert!(codecs.by_media_type("text/plain").is_none());
216 assert_eq!(codecs.decode_snapshot(&[9]).unwrap(), json!({ "raw": 9 }));
217 assert_eq!(codecs.decode_snapshot(&[7, 1]), Err(Error::UnknownFormat(7)));
218 assert!(codecs.decode_snapshot(&[]).is_err());
219
220 let taken = Codec::new("other").with_media_types(&["application/json"]);
222 assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
223 let taken = Codec::new("other").with_snapshots(Arc::new(Raw(json::FORMAT)));
224 assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
225 codecs.register(Codec::new("raw").with_snapshots(Arc::new(Raw(8)))).unwrap();
226 assert_eq!(codecs.decode_snapshot(&[8]).unwrap(), json!({ "raw": 8 }));
227 assert!(codecs.by_media_type("application/raw").is_none());
228 }
229}