Skip to main content

azalea_codec/
types.rs

1use std::{
2    any::{self, Any},
3    marker::PhantomData,
4};
5
6use crate::{
7    Codec, Interchangeable, MapCodec, Ops,
8    error::{ReadError, ReadResult, WriteResult},
9};
10
11/// Represents a string value that must be matched exactly when decoding this
12/// codec.
13///
14/// This is useful for representing enums with tag fields.
15#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
16pub struct StringLiteral<const S: &'static str>;
17impl<const S: &'static str, O: Ops> Codec<O> for StringLiteral<S> {
18    fn codec_read(ops: &O) -> ReadResult<Self> {
19        let s = ops.get_string()?;
20        if s == S {
21            Ok(Self)
22        } else {
23            Err(ReadError::custom(format!("'{s}' != '{S}'")))
24        }
25    }
26    fn codec_write(&self) -> WriteResult<O> {
27        O::create_string(S)
28    }
29}
30
31#[derive(Clone, Debug)]
32pub struct FromLiteral<const S: &'static str, T> {
33    _unused: PhantomData<T>,
34}
35impl<const S: &'static str, T> Default for FromLiteral<S, T> {
36    fn default() -> Self {
37        Self {
38            _unused: Default::default(),
39        }
40    }
41}
42impl<const S: &'static str, T: const ConstFromStr + Codec<O> + PartialEq, O: Ops> Codec<O>
43    for FromLiteral<S, T>
44{
45    fn codec_read(ops: &O) -> ReadResult<Self> {
46        let attempt = T::codec_read(ops)?;
47        let solution = const { T::const_from_str(S).expect("invalid variant") };
48        if attempt == solution {
49            Ok(Self::default())
50        } else if let Ok(attempt_as_string) = String::codec_read(ops) {
51            Err(ReadError::custom(format!(
52                "mismatching FromLiteral, '{attempt_as_string}' does not match '{S}'"
53            )))
54        } else {
55            Err(ReadError::custom(format!(
56                "mismatching FromLiteral, does not match {S}"
57            )))
58        }
59    }
60    fn codec_write(&self) -> WriteResult<O> {
61        let ident = const { T::const_from_str(S).expect("invalid variant") };
62        ident.codec_write()
63    }
64}
65/// Types that can be converted from a `&'static str` at compile-time.
66///
67/// Used for compile-time validation of `#[codec(tag_as = ...)]` tags.
68pub const trait ConstFromStr: Sized {
69    fn const_from_str(s: &str) -> Option<Self>;
70}
71
72/// A codec that always matches everything and writes nothing.
73#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
74pub struct Drain;
75impl<O: Ops> Codec<O> for Drain {
76    fn codec_read(_ops: &O) -> ReadResult<Self> {
77        Ok(Self)
78    }
79    fn codec_write(&self) -> WriteResult<O> {
80        O::empty()
81    }
82}
83impl<O: Ops> MapCodec<O> for Drain {
84    fn codec_read_map_item(
85        _incomplete: &mut <Self as crate::Codec<O>>::Incomplete,
86        _k: &O,
87        _v: &O,
88    ) {
89    }
90    fn codec_write_to_map(&self, _map: &mut Vec<(O, O)>) -> WriteResult<()> {
91        Ok(())
92    }
93    fn get_and_reset_result(_incomplete: &mut <Self as Codec<O>>::Incomplete) -> ReadResult<()> {
94        Ok(())
95    }
96}
97
98#[derive(Clone, Debug, PartialEq)]
99pub struct CompactListCodec<T>(pub T);
100impl<O: Ops, T: IntoIterator<Item = V> + FromIterator<V> + Clone, V: Codec<O> + Any> Codec<O>
101    for CompactListCodec<T>
102{
103    fn codec_read(ops: &O) -> ReadResult<Self> {
104        let mut errors = Vec::new();
105        match V::codec_read(ops) {
106            Ok(v) => {
107                return Ok(Self(T::from_iter([v])));
108            }
109            Err(e) => errors.push((any::type_name::<V>(), e)),
110        }
111        match Vec::<V>::codec_read(ops) {
112            Ok(v) => return Ok(Self(T::from_iter(v))),
113            Err(e) => errors.push((any::type_name::<Vec<V>>(), e)),
114        }
115        Err(ReadError::no_variants_matched(errors))
116    }
117    fn codec_write(&self) -> WriteResult<O> {
118        let v = self.0.clone().into_iter().collect::<Vec<V>>();
119        if v.len() == 1 {
120            v[0].codec_write()
121        } else {
122            v.codec_write()
123        }
124    }
125}
126
127impl<T> Interchangeable<CompactListCodec<Vec<T>>> for Vec<T> {
128    fn interchangeable_into(self) -> CompactListCodec<Vec<T>> {
129        CompactListCodec(self)
130    }
131    fn interchangeable_from(other: CompactListCodec<Vec<T>>) -> Self {
132        other.0
133    }
134}