Skip to main content

object_rainbow/
partial_byte_tag.rs

1use std::marker::PhantomData;
2
3use typenum::{ToInt, U1};
4
5use crate::{enumkind::UsizeTag, incr_byte_niche::IncrByteNiche, *};
6
7#[derive(
8    ToOutput,
9    InlineOutput,
10    Tagged,
11    ListHashes,
12    Topological,
13    ParseAsInline,
14    PartialEq,
15    Eq,
16    PartialOrd,
17    Ord,
18    ByteOrd,
19)]
20pub struct PartialByteTag<K>(u8, PhantomData<K>);
21
22impl<K> Size for PartialByteTag<K> {
23    type Size = U1;
24    const SIZE: usize = 1;
25}
26
27impl<K: ToInt<u8>, E: ParseInput> ParseInline<E> for PartialByteTag<K> {
28    fn parse_inline(input: &mut E) -> crate::Result<Self> {
29        let n = input.parse_inline()?;
30        if n < K::INT {
31            Ok(Self(n, PhantomData))
32        } else {
33            Err(crate::Error::OutOfBounds)
34        }
35    }
36}
37
38impl<K: ToInt<u8>> UsizeTag for PartialByteTag<K> {
39    fn from_usize(n: usize) -> Self {
40        assert!(n < K::INT as usize);
41        Self(n as _, PhantomData)
42    }
43
44    fn to_usize(&self) -> usize {
45        self.0.to_usize()
46    }
47
48    fn try_to_usize(&self) -> Option<usize> {
49        self.0.try_to_usize()
50    }
51}
52
53impl<K> MaybeHasNiche for PartialByteTag<K> {
54    type MnArray = SomeNiche<IncrByteNiche<K>>;
55}