Skip to main content

hang/catalog/
skipped.rs

1use std::collections::BTreeMap;
2
3use serde::de::{DeserializeSeed, Deserializer, Error as _, IgnoredAny, MapAccess, SeqAccess, Visitor};
4
5use crate::catalog::VERSION;
6
7/// The catalog entries a reader skipped because a newer moq-hang draft defines them.
8///
9/// Each section maps a skipped entry's ID to its `version`. The rest of the catalog reads as if
10/// those entries were absent, so a player plays what it can and may tell its user to upgrade for
11/// the rest.
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct Skipped {
15	/// Skipped video renditions.
16	pub video: BTreeMap<String, u64>,
17	/// Skipped audio renditions.
18	pub audio: BTreeMap<String, u64>,
19	/// Skipped text renditions.
20	pub text: BTreeMap<String, u64>,
21	/// Skipped JSON tracks.
22	pub json: BTreeMap<String, u64>,
23	/// Skipped binary tracks.
24	pub binary: BTreeMap<String, u64>,
25	/// Skipped includes.
26	pub include: BTreeMap<String, u64>,
27}
28
29impl Skipped {
30	fn sections(&self) -> [&BTreeMap<String, u64>; 6] {
31		[
32			&self.video,
33			&self.audio,
34			&self.text,
35			&self.json,
36			&self.binary,
37			&self.include,
38		]
39	}
40
41	/// Whether every entry was read.
42	pub fn is_empty(&self) -> bool {
43		self.sections().iter().all(|section| section.is_empty())
44	}
45
46	/// The draft a reader needs to read every skipped entry, or `None` if none was skipped.
47	pub fn version(&self) -> Option<u64> {
48		self.sections().into_iter().flat_map(BTreeMap::values).copied().max()
49	}
50}
51
52/// What a reader checks before decoding any section: the root `version`, and which entries are too
53/// new to read.
54///
55/// Read straight from the bytes where it can, so a repeated `version` member is caught rather than
56/// resolved to either copy. Nothing here refuses an entry before the root `version` is checked,
57/// since a newer draft may have reshaped any section; every other shape is left to the catalog's
58/// own decoding.
59#[derive(Default)]
60pub(crate) struct Probe {
61	pub version: Option<u64>,
62	pub skipped: Skipped,
63	/// An entry repeats its `version` member, which refuses the catalog once the root is read.
64	pub repeated: bool,
65}
66
67impl Probe {
68	/// Refuse a root `version` above [`VERSION`], then an entry that repeats its `version`.
69	///
70	/// A root `version` above this reader means the newer draft changed something it would
71	/// misread, not merely added something it would miss.
72	pub fn check(&self) -> crate::Result<()> {
73		match self.version {
74			Some(version) if version > VERSION => Err(crate::Error::UnsupportedVersion(version)),
75			_ if self.repeated => Err(crate::Error::Json(
76				"duplicate field `version` in a catalog entry".to_string(),
77			)),
78			_ => Ok(()),
79		}
80	}
81}
82
83impl<'de> serde::Deserialize<'de> for Probe {
84	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
85		Lenient(RootSeed).deserialize(deserializer)
86	}
87}
88
89/// Reads one JSON object's members.
90trait MapSeed {
91	type Value: Default;
92	fn visit<'de, A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error>;
93}
94
95/// Reads an object with its [`MapSeed`] and anything else as the seed's default.
96struct Lenient<S>(S);
97
98impl<'de, S: MapSeed> DeserializeSeed<'de> for Lenient<S> {
99	type Value = S::Value;
100
101	fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
102		deserializer.deserialize_any(self)
103	}
104}
105
106impl<'de, S: MapSeed> Visitor<'de> for Lenient<S> {
107	type Value = S::Value;
108
109	fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
110		f.write_str("any JSON value")
111	}
112
113	fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
114		self.0.visit(map)
115	}
116
117	fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
118		while seq.next_element::<IgnoredAny>()?.is_some() {}
119		Ok(Default::default())
120	}
121
122	fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {
123		Ok(Default::default())
124	}
125
126	fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {
127		Ok(Default::default())
128	}
129
130	fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {
131		Ok(Default::default())
132	}
133
134	fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {
135		Ok(Default::default())
136	}
137
138	fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {
139		Ok(Default::default())
140	}
141
142	fn visit_unit<E>(self) -> Result<Self::Value, E> {
143		Ok(Default::default())
144	}
145}
146
147struct RootSeed;
148
149impl MapSeed for RootSeed {
150	type Value = Probe;
151
152	fn visit<'de, A: MapAccess<'de>>(self, mut map: A) -> Result<Probe, A::Error> {
153		let mut probe = Probe::default();
154		while let Some(key) = map.next_key::<String>()? {
155			let skipped = &mut probe.skipped;
156			let repeated = &mut probe.repeated;
157			let (section, entries) = match key.as_str() {
158				"version" => {
159					if probe.version.is_some() {
160						return Err(A::Error::duplicate_field("version"));
161					}
162					probe.version = Some(map.next_value()?);
163					continue;
164				}
165				"video" => (&mut skipped.video, Some("renditions")),
166				"audio" => (&mut skipped.audio, Some("renditions")),
167				"text" => (&mut skipped.text, Some("renditions")),
168				"json" => (&mut skipped.json, Some("tracks")),
169				"binary" => (&mut skipped.binary, Some("tracks")),
170				"include" => (&mut skipped.include, None),
171				_ => {
172					map.next_value::<IgnoredAny>()?;
173					continue;
174				}
175			};
176			*section = match entries {
177				Some(key) => map.next_value_seed(Lenient(SectionSeed(key, repeated)))?,
178				None => map.next_value_seed(Lenient(EntriesSeed(repeated)))?,
179			};
180		}
181		Ok(probe)
182	}
183}
184
185/// A section holding its entries under one key (`renditions`, `tracks`).
186struct SectionSeed<'a>(&'static str, &'a mut bool);
187
188impl MapSeed for SectionSeed<'_> {
189	type Value = BTreeMap<String, u64>;
190
191	fn visit<'de, A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
192		let Self(entries, repeated) = self;
193		let mut skipped = BTreeMap::new();
194		while let Some(key) = map.next_key::<String>()? {
195			if key == entries {
196				skipped = map.next_value_seed(Lenient(EntriesSeed(&mut *repeated)))?;
197			} else {
198				map.next_value::<IgnoredAny>()?;
199			}
200		}
201		Ok(skipped)
202	}
203}
204
205/// A map of entries keyed by ID, yielding the ones newer than this reader.
206struct EntriesSeed<'a>(&'a mut bool);
207
208impl MapSeed for EntriesSeed<'_> {
209	type Value = BTreeMap<String, u64>;
210
211	fn visit<'de, A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
212		let mut skipped = BTreeMap::new();
213		while let Some(id) = map.next_key::<String>()? {
214			if let Some(version) = map.next_value_seed(Lenient(EntrySeed(&mut *self.0)))?
215				&& version > VERSION
216			{
217				skipped.insert(id, version);
218			}
219		}
220		Ok(skipped)
221	}
222}
223
224/// One entry, yielding its `version` when it is one. A malformed `version` is left to the entry's
225/// own decoding, which refuses it once the root `version` has been checked.
226struct EntrySeed<'a>(&'a mut bool);
227
228impl MapSeed for EntrySeed<'_> {
229	type Value = Option<u64>;
230
231	fn visit<'de, A: MapAccess<'de>>(self, mut map: A) -> Result<Option<u64>, A::Error> {
232		let mut version = None;
233		while let Some(key) = map.next_key::<String>()? {
234			if key != "version" {
235				map.next_value::<IgnoredAny>()?;
236			} else if version.replace(map.next_value::<serde_json::Value>()?).is_some() {
237				*self.0 = true;
238			}
239		}
240		Ok(version.as_ref().and_then(serde_json::Value::as_u64))
241	}
242}