use std::fmt;
use std::sync::Arc;
use serde_json::Value;
use crate::{json, Error, EventCodec, SnapshotCodec};
#[derive(Clone)]
pub struct Codec {
name: String,
media_types: Vec<String>,
events: Option<Arc<dyn EventCodec>>,
emitted: Option<Arc<dyn EventCodec>>,
snapshots: Option<Arc<dyn SnapshotCodec>>,
}
impl fmt::Debug for Codec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Codec")
.field("name", &self.name)
.field("media_types", &self.media_types)
.field("events", &self.events.is_some())
.field("emitted", &self.emitted.is_some())
.field("snapshots", &self.snapshots.as_ref().map(|s| s.format()))
.finish()
}
}
impl Codec {
pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into(), media_types: Vec::new(), events: None, emitted: None, snapshots: None }
}
pub fn with_media_types(mut self, media_types: &[&str]) -> Self {
self.media_types = media_types.iter().map(|t| t.to_ascii_lowercase()).collect();
self
}
pub fn with_events(mut self, events: Arc<dyn EventCodec>) -> Self {
self.events = Some(events);
self
}
pub fn with_emitted(mut self, emitted: Arc<dyn EventCodec>) -> Self {
self.emitted = Some(emitted);
self
}
pub fn with_snapshots(mut self, snapshots: Arc<dyn SnapshotCodec>) -> Self {
self.snapshots = Some(snapshots);
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn media_types(&self) -> &[String] {
&self.media_types
}
pub fn media_type(&self) -> Option<&str> {
self.media_types.first().map(String::as_str)
}
pub fn events(&self) -> Option<&Arc<dyn EventCodec>> {
self.events.as_ref()
}
pub fn emitted(&self) -> Option<&Arc<dyn EventCodec>> {
self.emitted.as_ref()
}
pub fn snapshots(&self) -> Option<&Arc<dyn SnapshotCodec>> {
self.snapshots.as_ref()
}
}
#[derive(Clone)]
pub struct Codecs {
codecs: Vec<Codec>,
}
impl fmt::Debug for Codecs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.codecs.iter()).finish()
}
}
impl Default for Codecs {
fn default() -> Self {
Self::new()
}
}
impl Codecs {
pub fn new() -> Self {
Self { codecs: vec![json::codec()] }
}
pub fn register(&mut self, codec: Codec) -> Result<&mut Self, Error> {
for other in self.codecs.iter().filter(|c| c.name != codec.name) {
if let Some(t) = codec.media_types.iter().find(|t| other.media_types.contains(t)) {
return Err(Error::Conflict(format!(
"codec \"{}\": media type {t} is codec \"{}\"'s",
codec.name, other.name
)));
}
let format = |c: &Codec| c.snapshots.as_ref().map(|s| s.format());
if let Some(f) = format(&codec).filter(|f| format(other) == Some(*f)) {
return Err(Error::Conflict(format!(
"codec \"{}\": snapshot format {f} is codec \"{}\"'s",
codec.name, other.name
)));
}
}
match self.codecs.iter_mut().find(|c| c.name == codec.name) {
Some(slot) => *slot = codec,
None => self.codecs.push(codec),
}
Ok(self)
}
pub fn get(&self, name: &str) -> Option<&Codec> {
self.codecs.iter().find(|c| c.name == name)
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.codecs.iter().map(|c| c.name.as_str())
}
pub fn by_media_type(&self, content_type: &str) -> Option<&Codec> {
let media = content_type.split(';').next().unwrap_or("").trim();
self.codecs.iter().find(|c| c.media_types.iter().any(|t| t.eq_ignore_ascii_case(media)))
}
pub fn decode_snapshot(&self, record: &[u8]) -> Result<Value, Error> {
let &format = record.first().ok_or_else(|| Error::Decode("empty snapshot record".into()))?;
let codec = self
.codecs
.iter()
.filter_map(|c| c.snapshots.as_ref())
.find(|s| s.format() == format)
.ok_or(Error::UnknownFormat(format))?;
codec.decode(record)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
struct Raw(u8);
impl SnapshotCodec for Raw {
fn format(&self) -> u8 {
self.0
}
fn encode(&self, _: crate::Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
out.push(self.0);
Ok(())
}
fn decode(&self, _: &[u8]) -> Result<Value, Error> {
Ok(json!({ "raw": self.0 }))
}
}
#[test]
fn records_find_their_codec() {
let mut codecs = Codecs::new();
codecs
.register(Codec::new("raw").with_media_types(&["Application/Raw"]).with_snapshots(Arc::new(Raw(9))))
.unwrap();
assert_eq!(codecs.names().collect::<Vec<_>>(), ["json", "raw"]);
assert_eq!(codecs.by_media_type("application/raw; v=1").unwrap().name(), "raw");
assert_eq!(codecs.by_media_type("TEXT/JSON").unwrap().name(), "json");
assert!(codecs.by_media_type("text/plain").is_none());
assert_eq!(codecs.decode_snapshot(&[9]).unwrap(), json!({ "raw": 9 }));
assert_eq!(codecs.decode_snapshot(&[7, 1]), Err(Error::UnknownFormat(7)));
assert!(codecs.decode_snapshot(&[]).is_err());
let taken = Codec::new("other").with_media_types(&["application/json"]);
assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
let taken = Codec::new("other").with_snapshots(Arc::new(Raw(json::FORMAT)));
assert!(matches!(codecs.register(taken), Err(Error::Conflict(_))));
codecs.register(Codec::new("raw").with_snapshots(Arc::new(Raw(8)))).unwrap();
assert_eq!(codecs.decode_snapshot(&[8]).unwrap(), json!({ "raw": 8 }));
assert!(codecs.by_media_type("application/raw").is_none());
}
}