Skip to main content

spoolframe_types/
wire.rs

1//! The simple enums' names on the wire, both ways, and every value an app
2//! offers: for an app that keeps a choice in its own settings, or reads
3//! one from a link, with the same names the server and the SDK use. No
4//! English labels: the apps word them.
5//!
6//! Each enum's list names every value but `Unknown` (a name this build
7//! does not know, never one to offer); a match over the list and
8//! `Unknown` stops it compiling when a value is added and not listed.
9
10use serde::de::value::StrDeserializer;
11use serde::{Serialize, de::DeserializeOwned};
12
13use crate::{
14    AudioCodec, AudioRole, BitmapPreference, Container, Delivery, DynamicRange, FilterPart,
15    ForcedPreference, HdrFormat, ItemFilter, ItemSort, Resolution, SdhPreference, SearchKind,
16    SearchScope, SortKey, SubtitleFormat, SubtitleMode, VideoCodec, WatchedState,
17};
18
19/// `value`'s name on the wire: its serde name.
20fn name_of(value: &impl Serialize) -> String {
21    match serde_json::to_value(value) {
22        Ok(serde_json::Value::String(name)) => name,
23        other => unreachable!("a simple enum serializes as its name, not {other:?}"),
24    }
25}
26
27/// The value of `all` serde reads from `name`; `None` for a name it reads
28/// as none of them. A type's `serde(other)` value reads from any name,
29/// so only that one is checked against its own name, which allocates;
30/// every other name is read without.
31fn named<T: Serialize + DeserializeOwned + PartialEq + Copy>(name: &str, all: &[T]) -> Option<T> {
32    let read = |name: &str| T::deserialize(StrDeserializer::<serde::de::value::Error>::new(name));
33    let value = read(name).ok()?;
34    // What a name nothing has reads as: the `serde(other)` value.
35    let other = read("\0").ok();
36    if other == Some(value) && name_of(&value) != name {
37        return None;
38    }
39    all.contains(&value).then_some(value)
40}
41
42/// How a type's wire name is had: its own `as_str`, or its serde name.
43macro_rules! wire_name_by {
44    (as_str, $value:expr) => {
45        $value.as_str().to_owned()
46    };
47    (serde, $value:expr) => {
48        name_of($value)
49    };
50    (as_str, $name:expr, $all:expr) => {
51        $all.iter().copied().find(|v| v.as_str() == $name)
52    };
53    (serde, $name:expr, $all:expr) => {
54        named($name, $all)
55    };
56}
57
58/// `value` as a settings string: its JSON.
59fn settings_of(value: &impl Serialize) -> String {
60    serde_json::to_string(value).expect("a sort or filter serializes")
61}
62
63/// The value a settings string holds; `None` for one that isn't one.
64fn from_settings<T: DeserializeOwned>(settings: &str) -> Option<T> {
65    serde_json::from_str(settings).ok()
66}
67
68macro_rules! wire_names {
69    ($(
70        $ty:ident ($by:ident), $from:ident, $all:ident, [$($v:ident),* $(,)?] $(, $unknown:ident)?;
71    )*) => {$(
72        impl $ty {
73            /// Every value an app offers, in the order a client lists
74            /// them: all but `Unknown`.
75            pub const ALL: &'static [$ty] = &[$($ty::$v),*];
76
77            /// The value named `name` on the wire; `None` for a name
78            /// this build doesn't know.
79            pub fn from_wire_name(name: &str) -> Option<Self> {
80                wire_name_by!($by, name, Self::ALL)
81            }
82        }
83
84        #[cfg_attr(feature = "uniffi", uniffi::export)]
85        impl $ty {
86            /// Its name on the wire, as the server and the SDK say it.
87            pub fn wire_name(&self) -> String {
88                wire_name_by!($by, self)
89            }
90        }
91
92        /// The value named `name` on the wire; `None` for a name this
93        /// build doesn't know.
94        #[cfg_attr(feature = "uniffi", uniffi::export)]
95        pub fn $from(name: String) -> Option<$ty> {
96            $ty::from_wire_name(&name)
97        }
98
99        /// Every value an app offers: all but `Unknown`, in order.
100        #[cfg_attr(feature = "uniffi", uniffi::export)]
101        pub fn $all() -> Vec<$ty> {
102            $ty::ALL.to_vec()
103        }
104
105        const _: fn($ty) = |value| match value {
106            $($ty::$v)|* $(| $ty::$unknown)? => {}
107        };
108    )*};
109}
110
111wire_names! {
112    SortKey (as_str), sort_key_from_wire_name, all_sort_keys,
113        [Title, Released, Added, LastPlayed, Rating, AudienceRating, Duration, Size], Unknown;
114    WatchedState (serde), watched_state_from_wire_name, all_watched_states,
115        [Unwatched, InProgress, Watched], Unknown;
116    Resolution (as_str), resolution_from_wire_name, all_resolutions, [Uhd, FullHd, Hd, Sd], Unknown;
117    DynamicRange (serde), dynamic_range_from_wire_name, all_dynamic_ranges,
118        [Sdr, Hdr, DolbyVision], Unknown;
119    FilterPart (as_str), filter_part_from_wire_name, all_filter_parts,
120        [Watched, Genres, Years, ContentRatings, Resolutions, DynamicRanges], Unknown;
121    SearchScope (serde), search_scope_from_wire_name, all_search_scopes,
122        [All, Movies, Shows, Episodes, Music];
123    SearchKind (serde), search_kind_from_wire_name, all_search_kinds,
124        [Shows, Movies, People, Artists, Albums, Tracks, Episodes];
125    VideoCodec (as_str), video_codec_from_wire_name, all_video_codecs,
126        [H264, Hevc, Av1, Vp9, Vp8, Mpeg2, Mpeg4, Vc1], Unknown;
127    AudioCodec (as_str), audio_codec_from_wire_name, all_audio_codecs,
128        [Aac, Ac3, Eac3, Dts, TrueHd, Flac, Alac, Opus, Vorbis, Mp3, Pcm], Unknown;
129    Container (as_str), container_from_wire_name, all_containers,
130        [Matroska, Mp4, MpegTs, Avi, Flac, Mp3, Ogg], Unknown;
131    SubtitleFormat (as_str), subtitle_format_from_wire_name, all_subtitle_formats,
132        [Srt, Ass, WebVtt, MovText, Pgs, VobSub, DvbSub], Unknown;
133    Delivery (serde), delivery_from_wire_name, all_deliveries, [Range, Hls, Progressive], Unknown;
134    HdrFormat (serde), hdr_format_from_wire_name, all_hdr_formats, [Hdr10, Hlg, DolbyVision], Unknown;
135    SubtitleMode (serde), subtitle_mode_from_wire_name, all_subtitle_modes,
136        [Always, ForeignOnly, Off, ForcedOnly];
137    SdhPreference (serde), sdh_preference_from_wire_name, all_sdh_preferences,
138        [Prefer, Avoid, Only, Accept];
139    ForcedPreference (serde), forced_preference_from_wire_name, all_forced_preferences,
140        [Prefer, Avoid, Only, Accept];
141    AudioRole (serde), audio_role_from_wire_name, all_audio_roles,
142        [Main, AudioDescription, Commentary, Other];
143    BitmapPreference (serde), bitmap_preference_from_wire_name, all_bitmap_preferences,
144        [Pictures, Text];
145}
146
147#[cfg_attr(feature = "uniffi", uniffi::export)]
148impl ItemSort {
149    /// It as a string to keep in an app's settings:
150    /// [`item_sort_from_settings`] reads it back.
151    pub fn settings_string(&self) -> String {
152        settings_of(self)
153    }
154}
155
156/// The sort `settings` holds ([`ItemSort::settings_string`]); `None` for
157/// a string that isn't one.
158#[cfg_attr(feature = "uniffi", uniffi::export)]
159pub fn item_sort_from_settings(settings: String) -> Option<ItemSort> {
160    from_settings(&settings)
161}
162
163#[cfg_attr(feature = "uniffi", uniffi::export)]
164impl ItemFilter {
165    /// It as a string to keep in an app's settings:
166    /// [`item_filter_from_settings`] reads it back.
167    pub fn settings_string(&self) -> String {
168        settings_of(self)
169    }
170}
171
172/// The filter `settings` holds ([`ItemFilter::settings_string`]); `None`
173/// for a string that isn't one.
174#[cfg_attr(feature = "uniffi", uniffi::export)]
175pub fn item_filter_from_settings(settings: String) -> Option<ItemFilter> {
176    from_settings(&settings)
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    /// Every value of `T` named on the wire reads back as itself, no two
184    /// share a name, and `Unknown`'s name reads as nothing.
185    fn round_trips<T: Copy + PartialEq + std::fmt::Debug + Serialize>(
186        all: &[T],
187        from: fn(&str) -> Option<T>,
188    ) {
189        let names: Vec<String> = all.iter().map(name_of).collect();
190        let back: Vec<Option<T>> = names.iter().map(|n| from(n)).collect();
191        let mut unique = names.clone();
192        unique.sort();
193        unique.dedup();
194        assert_eq!(
195            (back, unique.len(), from("unknown"), from("no-such-name")),
196            (
197                all.iter().copied().map(Some).collect(),
198                names.len(),
199                None,
200                None
201            ),
202            "{names:?}"
203        );
204    }
205
206    #[test]
207    fn every_value_offered_reads_back_from_its_wire_name() {
208        round_trips(SortKey::ALL, SortKey::from_wire_name);
209        round_trips(WatchedState::ALL, WatchedState::from_wire_name);
210        round_trips(Resolution::ALL, Resolution::from_wire_name);
211        round_trips(DynamicRange::ALL, DynamicRange::from_wire_name);
212        round_trips(FilterPart::ALL, FilterPart::from_wire_name);
213        round_trips(SearchScope::ALL, SearchScope::from_wire_name);
214        round_trips(SearchKind::ALL, SearchKind::from_wire_name);
215        round_trips(VideoCodec::ALL, VideoCodec::from_wire_name);
216        round_trips(AudioCodec::ALL, AudioCodec::from_wire_name);
217        round_trips(Container::ALL, Container::from_wire_name);
218        round_trips(SubtitleFormat::ALL, SubtitleFormat::from_wire_name);
219        round_trips(Delivery::ALL, Delivery::from_wire_name);
220        round_trips(HdrFormat::ALL, HdrFormat::from_wire_name);
221        round_trips(SubtitleMode::ALL, SubtitleMode::from_wire_name);
222        round_trips(SdhPreference::ALL, SdhPreference::from_wire_name);
223        round_trips(ForcedPreference::ALL, ForcedPreference::from_wire_name);
224        round_trips(AudioRole::ALL, AudioRole::from_wire_name);
225        round_trips(BitmapPreference::ALL, BitmapPreference::from_wire_name);
226    }
227
228    /// The vocabularies' own names are the wire names.
229    #[test]
230    fn a_codec_s_wire_name_is_its_vocabulary_name() {
231        assert_eq!(
232            (
233                VideoCodec::Hevc.wire_name(),
234                AudioCodec::TrueHd.wire_name(),
235                Resolution::Uhd.wire_name(),
236                Container::MpegTs.wire_name(),
237            ),
238            (
239                VideoCodec::Hevc.as_str().to_owned(),
240                AudioCodec::TrueHd.as_str().to_owned(),
241                "4k".to_owned(),
242                Container::MpegTs.as_str().to_owned(),
243            )
244        );
245    }
246
247    #[test]
248    fn a_sort_and_a_filter_read_back_from_their_settings_strings() {
249        let sort = ItemSort {
250            key: SortKey::LastPlayed,
251            descending: true,
252        };
253        let filter = ItemFilter {
254            watched: vec![WatchedState::InProgress],
255            year_from: Some(1990),
256            resolutions: vec![Resolution::Uhd],
257            ..ItemFilter::default()
258        };
259        assert_eq!(
260            (
261                item_sort_from_settings(sort.settings_string()),
262                item_filter_from_settings(filter.settings_string()),
263                item_sort_from_settings("not json".into()),
264            ),
265            (Some(sort), Some(filter), None)
266        );
267    }
268}