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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use crate::error::*;
use std::fmt;
use std::marker::PhantomData;

use super::cpool;

pub trait Encoder: Sized {
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), EncodeError>;

    fn write<T: Encode>(&mut self, value: T) -> Result<&mut Self, EncodeError> {
        value.encode(self)?;
        Ok(self)
    }
}

pub trait Encode {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>;
}

impl<T: Encode> Encode for &T {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        (*self).encode(encoder)
    }
}

impl Encode for &[u8] {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        encoder.write_bytes(self)
    }
}

macro_rules! impl_encode {
    ($($t:ty,)*) => {
        $(
            impl Encode for $t {
                fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
                    encoder.write(self.to_be_bytes().as_ref())?;
                    Ok(())
                }
            }
        )*
    }
}

impl_encode! {
    u8, i8,
    u16, i16,
    u32, i32,
    u64, i64,
    // this will probably never be needed, but why not
    u128, i128,
}

impl Encode for f32 {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        encoder.write(self.to_bits().to_be_bytes().as_ref())?;
        Ok(())
    }
}

impl Encode for f64 {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        encoder.write(self.to_bits().to_be_bytes().as_ref())?;
        Ok(())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Offset(usize);

impl Offset {
    pub const fn new(position: usize) -> Offset {
        Offset(position)
    }

    pub const fn get(self) -> usize {
        self.0
    }

    pub const fn offset(self, by: usize) -> Offset {
        Offset(self.0 + by)
    }

    pub const fn sub(self, by: Offset) -> Offset {
        Offset(self.0 - by.0)
    }
}

#[derive(Clone, Debug)]
pub struct VecEncoder {
    buf: Vec<u8>,
}

impl VecEncoder {
    pub fn new(buf: Vec<u8>) -> VecEncoder {
        VecEncoder { buf }
    }

    pub fn position(&self) -> Offset {
        Offset::new(self.buf.len())
    }

    pub fn inner(&self) -> &[u8] {
        &self.buf
    }

    pub fn into_inner(self) -> Vec<u8> {
        self.buf
    }

    pub fn buf(&self) -> &[u8] {
        &self.buf
    }

    pub fn replacing(&mut self, at: Offset) -> ReplacingEncoder<'_> {
        ReplacingEncoder {
            buf: &mut self.buf[at.0..],
        }
    }
}

impl Encoder for VecEncoder {
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
        self.buf.extend_from_slice(bytes);
        Ok(())
    }
}

#[derive(Debug)]
pub struct ReplacingEncoder<'a> {
    buf: &'a mut [u8],
}

impl<'a> Encoder for ReplacingEncoder<'a> {
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
        assert!(bytes.len() <= self.buf.len(), "cannot replace bytes which do not exist");
        let (a, b) = std::mem::take(&mut self.buf).split_at_mut(bytes.len());
        a.copy_from_slice(bytes);
        self.buf = b;
        Ok(())
    }
}

/// An encoder writing the amount of bytes written since its creation to the front.
pub(crate) struct LengthWriter<Ctx> {
    /// The offset of the byte counter.
    length_offset: Offset,
    _marker: PhantomData<Ctx>,
}

impl<Ctx: EncoderContext> LengthWriter<Ctx> {
    pub(crate) fn new(context: &mut Ctx) -> Result<Self, EncodeError> {
        let length_offset = context.encoder().position();
        context.encoder().write(0u32)?;
        Ok(LengthWriter {
            length_offset,
            _marker: PhantomData,
        })
    }

    pub(crate) fn finish(self, context: &mut Ctx) -> Result<(), EncodeError> {
        let length = context.encoder().position().sub(self.length_offset).sub(Offset(4)); // subtract the amount of bytes the length takes up
        let length = u32::try_from(length.0)
            .map_err(|_| EncodeError::with_context(EncodeErrorKind::TooManyBytes, Context::None))?;
        context.encoder().replacing(self.length_offset).write(length)?;
        Ok(())
    }
}

impl<E: Encoder> Encoder for &mut E {
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
        (*self).write_bytes(bytes)
    }
}

pub trait InternalEncoderContext {
    fn encoder(&mut self) -> &mut VecEncoder;
}

impl<'a, Ctx: InternalEncoderContext> InternalEncoderContext for &'a mut Ctx {
    fn encoder(&mut self) -> &mut VecEncoder {
        (**self).encoder()
    }
}

pub trait EncoderContext: InternalEncoderContext {
    fn insert_constant<I: Into<cpool::Item>>(&mut self, item: I) -> Result<cpool::Index<I>, EncodeError>;
}

impl<'a, Ctx: EncoderContext> EncoderContext for &'a mut Ctx {
    fn insert_constant<I: Into<cpool::Item>>(&mut self, item: I) -> Result<cpool::Index<I>, EncodeError> {
        (**self).insert_constant(item)
    }
}

pub trait WriteAssembler: Sized {
    type Context: EncoderContext;

    fn new(context: Self::Context) -> Result<Self, EncodeError>;
}

pub trait WriteDisassembler {
    type Context: EncoderContext;

    fn finish(self) -> Result<Self::Context, EncodeError>;
}

pub struct ManyWriter<W: WriteAssembler, Count> {
    /// The offset of the counter starting at the pool end.
    count_offset: Offset,
    context: Option<W::Context>,
    count: Count,
    _marker: PhantomData<W>,
}

impl<W, Count> WriteAssembler for ManyWriter<W, Count>
where
    W: WriteAssembler,
    Count: Encode + Counter,
{
    type Context = W::Context;

    fn new(mut context: Self::Context) -> Result<Self, EncodeError> {
        let count_offset = context.encoder().position();
        let count = Count::zero();
        context.encoder().write(count)?;
        Ok(ManyWriter {
            context: Some(context),
            count_offset,
            count,
            _marker: PhantomData,
        })
    }
}

impl<W, Count> WriteDisassembler for ManyWriter<W, Count>
where
    W: WriteAssembler,
    Count: Encode + Counter,
{
    type Context = W::Context;

    fn finish(mut self) -> Result<Self::Context, EncodeError> {
        self.context
            .take()
            .ok_or_else(|| EncodeError::with_context(EncodeErrorKind::ErroredBefore, Context::None))
    }
}

impl<W, Count> ManyWriter<W, Count>
where
    W: WriteAssembler,
    Count: Encode + Counter,
{
    pub fn begin<D, F>(&mut self, f: F) -> Result<&mut Self, EncodeError>
    where
        D: WriteDisassembler<Context = W::Context>,
        F: FnOnce(W) -> Result<D, EncodeError>,
    {
        let context = self
            .context
            .take()
            .ok_or_else(|| EncodeError::with_context(EncodeErrorKind::ErroredBefore, Context::None))?;
        self.count.check()?;

        let mut context = f(W::new(context)?)?.finish()?;

        self.count.increment()?;
        context.encoder().replacing(self.count_offset).write(self.count)?;
        self.context = Some(context);
        Ok(self)
    }
}

impl<W: WriteAssembler, Count> fmt::Debug for ManyWriter<W, Count> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ManyWriter").finish()
    }
}

pub trait Counter: Copy {
    fn zero() -> Self;
    fn check(self) -> Result<(), EncodeError>;
    fn increment(&mut self) -> Result<(), EncodeError>;
}

macro_rules! impl_counter {
    ($v:ident) => {
        impl Counter for $v {
            fn zero() -> $v {
                0
            }

            fn check(self) -> Result<(), EncodeError> {
                if self == $v::MAX {
                    Err(EncodeError::with_context(
                        EncodeErrorKind::TooManyItems,
                        Context::None,
                    ))
                } else {
                    Ok(())
                }
            }

            fn increment(&mut self) -> Result<(), EncodeError> {
                match self.checked_add(1) {
                    Some(i) => {
                        *self = i;
                        Ok(())
                    }
                    None => Err(EncodeError::with_context(
                        EncodeErrorKind::TooManyItems,
                        Context::None,
                    )),
                }
            }
        }
    };
}

impl_counter!(u8);
impl_counter!(u16);

macro_rules! enc_state {
    ($vis:vis mod $mod:ident : $($state:ident),* $(,)?) => {
        #[allow(non_snake_case)]
        #[doc(hidden)]
        $vis mod $mod {
            pub trait State: sealed::Sealed {}

            $(
                #[derive(Debug)]
                pub struct $state(std::convert::Infallible);
                impl State for $state {}
            )*

            mod sealed {
                pub trait Sealed {}
                $(
                    impl Sealed for super::$state {}
                )*
            }
        }
    };
}

#[allow(unused_imports)]
pub(crate) use enc_state;