1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! Traits to better express parsing semantics.

use crate::atomic::*;
use crate::mode::*;
use crate::rcore::*;

use super::{atomic_object::*, *};

pub mod static_pair;

/// This factory always reads the same amount of bytes or returns error.
pub trait FixedSizeFactory<'a, Ctx: Context<'a>>: InliningFactory<'a, Ctx> {
    /// For [`ConstSizeFactory`] this must return [`ConstSizeFactory::SIZE`].
    fn size(&self) -> usize;
}

/// Compile-time analogue of [`FixedSizeFactory`].
pub trait ConstSizeFactory<'a, Ctx: Context<'a>>: FixedSizeFactory<'a, Ctx> {
    /// Must be equal to [`FixedSizeFactory::size()`].
    const SIZE: usize;
}

/// Object analogue of [`InliningFactory`].
pub trait InliningObject<'a, Ctx: Context<'a>>: Mentionable<'a, Ctx> {}

/// Object analogue of [`FixedSizeFactory`].
pub trait FixedSizeObject<'a, Ctx: Context<'a>>: InliningObject<'a, Ctx> {
    /// For [`ConstSizeObject`] this must return [`ConstSizeObject::SIZE`].
    fn size(&self) -> usize;
}

/// Object analogue of [`ConstSizeFactory`].
pub trait ConstSizeObject<'a, Ctx: Context<'a>>: FixedSizeObject<'a, Ctx> {
    /// Must be equal to [`FixedSizeObject::size()`].
    const SIZE: usize;
}

/// Atomic analogue of [`ConstSizeFactory`]/[`ConstSizeObject`].
///
/// Note: `FixedSizeAtomic` doesn't exist because it would
/// either be const anyway
/// or have a very undesireable implementation.
pub trait ConstSizeAtomic: InliningAtomic {
    const SIZE: usize;
}

impl<'a, Ctx: Context<'a>, A: ConstSizeAtomic + AtomicModeParse> FixedSizeFactory<'a, Ctx>
    for AtomicFactory<A>
{
    fn size(&self) -> usize {
        A::SIZE
    }
}

impl<'a, Ctx: Context<'a>, A: ConstSizeAtomic + AtomicModeParse> ConstSizeFactory<'a, Ctx>
    for AtomicFactory<A>
{
    const SIZE: usize = A::SIZE;
}

impl<'a, Ctx: Context<'a>, A: Mentionable<'a, Ctx>> InliningObject<'a, Ctx> for A where
    A::Fctr: InliningFactory<'a, Ctx>
{
}

impl<'a, Ctx: Context<'a>, A: Mentionable<'a, Ctx>> FixedSizeObject<'a, Ctx> for A
where
    A::Fctr: FixedSizeFactory<'a, Ctx>,
{
    fn size(&self) -> usize {
        self.factory().size()
    }
}

impl<'a, Ctx: Context<'a>, A: Mentionable<'a, Ctx>> ConstSizeObject<'a, Ctx> for A
where
    A::Fctr: ConstSizeFactory<'a, Ctx>,
{
    const SIZE: usize = A::Fctr::SIZE;
}

/// Error returned by [`CheckedParse::deserialize_checked`]/[`CheckedSerialize::serialize_checked`].
#[derive(Debug)]
pub struct SizeError {
    expected: usize,
    received: usize,
}

impl Display for SizeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "expected {} bytes, read/wrote {} instead",
            self.expected, self.received
        )
    }
}

impl Error for SizeError {}

/// Wrapper for [`SizeError`]/[`FactoryBase::ParseError`].
#[derive(Debug)]
pub enum CheckedParseError<P: Error> {
    Parse(P),
    Size(SizeError),
}

impl<P: Error> Display for CheckedParseError<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Parse(parse_error) => write!(f, "{}", parse_error),
            Self::Size(size_error) => {
                write!(f, "size check failed: {}", size_error)
            }
        }
    }
}

impl<P: Error> From<P> for CheckedParseError<P> {
    fn from(value: P) -> Self {
        Self::Parse(value)
    }
}

pub type CheckedParseFailure<'a, F> = CheckedParseError<ParseError<'a, F>>;

/// Returned by [`CheckedParse::deserialize_checked`].
pub type CheckedParseResult<'a, F> = Result<Mtbl<'a, F>, CheckedParseFailure<'a, F>>;

/// Extension trait for factories that ensures fixed size read.
pub trait CheckedParse<'a, Ctx: Context<'a>>: FixedSizeFactory<'a, Ctx> {
    /// Verify proper read length using [`Deserializer::tell`].
    fn deserialize_checked(&self, inctx: impl InCtx<'a, Ctx>) -> CheckedParseResult<'a, Self> {
        let expected_size = self.size();
        let start = inctx.itell();
        let (result, inctx) = self.ideserialize(inctx)?;
        let end = inctx.itell();
        let received_size = end - start;
        if received_size == expected_size {
            Ok(result)
        } else {
            Err(CheckedParseError::Size(SizeError {
                expected: expected_size,
                received: received_size,
            }))
        }
    }
}

/// Extension trait for factories that ensures fixed size write.
pub trait CheckedSerialize<'a, Ctx: Context<'a>>: Serializable + FixedSizeObject<'a, Ctx> {
    /// Verify proper write length using [`Serializer::tell`].
    fn serialize_checked(&self, serializer: &mut dyn Serializer) -> Result<(), SizeError> {
        let expected_size = self.size();
        let start = serializer.tell();
        self.serialize(serializer);
        let end = serializer.tell();
        let received_size = end - start;
        if received_size == expected_size {
            Ok(())
        } else {
            Err(SizeError {
                expected: expected_size,
                received: received_size,
            })
        }
    }
}

impl<'a, Ctx: Context<'a>, F: FixedSizeFactory<'a, Ctx>> CheckedParse<'a, Ctx> for F {}

impl<'a, Ctx: Context<'a>, A: Mentionable<'a, Ctx> + FixedSizeObject<'a, Ctx>>
    CheckedSerialize<'a, Ctx> for A
{
}

/// Trait useful for objects which aren't influenced by
/// whether some other type (for example, a generic parameter type)
/// is fixed-size or not.
pub trait AlwaysFixedSize {
    fn asize(&self) -> usize;
}

impl<'a, Ctx: Context<'a>, F: AlwaysFixedSize + InliningFactory<'a, Ctx>> FixedSizeFactory<'a, Ctx>
    for F
{
    fn size(&self) -> usize {
        self.asize()
    }
}

/// Compile-time analogue of [`AlwaysFixedSize`].
pub trait AlwaysConstSize {
    const ASIZE: usize;
}

impl<F: AlwaysConstSize> AlwaysFixedSize for F {
    fn asize(&self) -> usize {
        Self::ASIZE
    }
}

impl<'a, Ctx: Context<'a>, F: AlwaysConstSize + InliningFactory<'a, Ctx>> ConstSizeFactory<'a, Ctx>
    for F
{
    const SIZE: usize = Self::ASIZE;
}