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
// Copyright 2023 RISC Zero, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use alloc::vec::Vec;
use core::mem::MaybeUninit;

use impl_trait_for_tuples::impl_for_tuples;

use super::{align_bytes_to_words, as_words_padded, pad_words, Result, ZeroioError};

pub struct Alloc<'a> {
    buf_left: MaybeUninit<&'a mut [u32]>,
    base: usize,
}

pub struct AllocBuf<'a> {
    buf: &'a mut [u32],
    base: usize,
}

impl<'a> Alloc<'a> {
    pub fn alloc(&mut self, words: usize) -> Result<AllocBuf<'a>> {
        // Juggle around the slice contianing remaining allocation buffer, since
        // the borrow checker doesn't understand that we're returning part of the
        // buffer back to self.buf_left when we're done.
        let mut tmp: MaybeUninit<&'a mut [u32]> = MaybeUninit::uninit();
        core::mem::swap(&mut self.buf_left, &mut tmp);
        let buf_left = unsafe { tmp.assume_init() };

        if buf_left.len() < words {
            return Err(ZeroioError::AllocationSizeMismatch);
        }
        let (new_buf, rest) = buf_left.split_at_mut(words);
        self.buf_left.write(rest);
        let old_base = self.base;
        self.base += words;
        Ok(AllocBuf {
            buf: new_buf,
            base: old_base,
        })
    }
}

impl<'a> AllocBuf<'a> {
    pub fn descend(&mut self, offset: usize, len: usize) -> Result<AllocBuf> {
        if offset + len > self.buf.len() {
            return Err(ZeroioError::FillOverrun);
        }
        Ok(AllocBuf {
            buf: &mut self.buf[offset..offset + len],
            base: self.base + offset,
        })
    }

    pub fn fill_from<const N: usize>(&mut self, val: [u32; N]) -> Result<()> {
        if self.buf.len() != N {
            return Err(ZeroioError::FillOverrun);
        }

        self.buf.clone_from_slice(&val[..]);
        Ok(())
    }

    pub fn buf(&mut self, len: usize) -> Result<&mut [u32]> {
        if self.buf.len() != len {
            return Err(ZeroioError::FillOverrun);
        }
        Ok(&mut self.buf)
    }

    pub fn rel_ptr_from(&self, other: &AllocBuf) -> u32 {
        (self.base - other.base) as u32
    }
}

pub fn serialize<T>(val: &T) -> Result<Vec<u32>>
where
    T: Serialize,
{
    let tot_len = val.tot_len();
    let padded = pad_words(tot_len);
    let mut buf: Vec<u32> = Vec::new();
    buf.resize(padded, 0);

    let (mut alloc_buf, _) = buf.as_mut_slice().split_at_mut(tot_len);

    log::trace!(
        "Starting to serialize type {:?} with {} words and {} fixed words",
        core::any::type_name::<T>(),
        tot_len,
        T::FIXED_WORDS
    );

    let mut alloc = Alloc {
        buf_left: MaybeUninit::new(&mut alloc_buf),
        base: 0,
    };

    let mut fixed = alloc.alloc(T::FIXED_WORDS)?;
    val.fill(&mut fixed, &mut alloc)?;

    Ok(buf)
}

pub trait Serialize {
    const FIXED_WORDS: usize;

    fn tot_len(&self) -> usize;

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()>;
}

impl Serialize for u32 {
    const FIXED_WORDS: usize = 1;

    fn tot_len(&self) -> usize {
        1
    }

    fn fill(&self, buf: &mut AllocBuf, _a: &mut Alloc) -> Result<()> {
        buf.fill_from([*self])?;
        Ok(())
    }
}

impl Serialize for alloc::string::String {
    const FIXED_WORDS: usize = 2;

    fn tot_len(&self) -> usize {
        Self::FIXED_WORDS + align_bytes_to_words(self.len())
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        let words = align_bytes_to_words(self.len());
        let str_data = a.alloc(words)?;

        for (w, val) in core::iter::zip(
            str_data.buf.iter_mut(),
            as_words_padded(self.as_bytes().into_iter().cloned()),
        ) {
            *w = val;
        }

        buf.fill_from([self.len() as u32, str_data.rel_ptr_from(buf)])?;
        Ok(())
    }
}

impl Serialize for Vec<u8> {
    const FIXED_WORDS: usize = 2;

    fn tot_len(&self) -> usize {
        Self::FIXED_WORDS + align_bytes_to_words(self.len())
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        let words = align_bytes_to_words(self.len());
        let str_data = a.alloc(words)?;

        for (w, val) in core::iter::zip(
            str_data.buf.iter_mut(),
            as_words_padded(self.iter().cloned()),
        ) {
            *w = val;
        }

        buf.fill_from([self.len() as u32, str_data.rel_ptr_from(buf)])?;
        Ok(())
    }
}

impl<T: Serialize> Serialize for core::option::Option<T> {
    const FIXED_WORDS: usize = 1;

    fn tot_len(&self) -> usize {
        match self {
            None => 1,
            Some(val) => 1 + val.tot_len(),
        }
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        match self {
            None => {
                buf.fill_from([0])?;
                Ok(())
            }
            Some(val) => {
                let mut sub_buf = a.alloc(T::FIXED_WORDS)?;
                val.fill(&mut sub_buf, a)?;
                buf.fill_from([sub_buf.rel_ptr_from(buf)])?;
                Ok(())
            }
        }
    }
}

impl<T: Serialize> Serialize for alloc::boxed::Box<T> {
    const FIXED_WORDS: usize = T::FIXED_WORDS;

    fn tot_len(&self) -> usize {
        self.as_ref().tot_len()
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        self.as_ref().fill(buf, a)
    }
}

impl<T: Serialize> Serialize for alloc::vec::Vec<T> {
    const FIXED_WORDS: usize = 2;

    fn tot_len(&self) -> usize {
        self.iter().map(|x| x.tot_len()).sum::<usize>() + Self::FIXED_WORDS
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        let mut sub_buf = a.alloc(T::FIXED_WORDS * self.len())?;
        let mut pos = 0;
        for val in self {
            val.fill(&mut sub_buf.descend(pos, T::FIXED_WORDS)?, a)?;
            pos += T::FIXED_WORDS;
        }
        buf.fill_from([self.len() as u32, sub_buf.rel_ptr_from(buf)])?;
        Ok(())
    }
}

impl<T: Serialize, const N: usize> Serialize for [T; N] {
    const FIXED_WORDS: usize = T::FIXED_WORDS * N;

    fn tot_len(&self) -> usize {
        self.iter().map(|x| x.tot_len()).sum()
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        let mut pos = 0;
        for val in self {
            val.fill(&mut buf.descend(pos, T::FIXED_WORDS)?, a)?;
            pos += T::FIXED_WORDS;
        }
        Ok(())
    }
}

impl<const N: usize> Serialize for [u8; N] {
    const FIXED_WORDS: usize = align_bytes_to_words(N);

    fn tot_len(&self) -> usize {
        Self::FIXED_WORDS
    }

    fn fill(&self, buf: &mut AllocBuf, _a: &mut Alloc) -> Result<()> {
        for (w, val) in core::iter::zip(
            buf.buf(Self::FIXED_WORDS)?.iter_mut(),
            as_words_padded(self.into_iter().cloned()),
        ) {
            *w = val;
        }
        Ok(())
    }
}

#[impl_for_tuples(1, 5)]
impl Serialize for Tuple {
    for_tuples!(const FIXED_WORDS: usize = #(Tuple::FIXED_WORDS)+*; );

    fn tot_len(&self) -> usize {
        for_tuples!(#(Tuple.tot_len())+*)
    }

    fn fill(&self, buf: &mut AllocBuf, a: &mut Alloc) -> Result<()> {
        let mut pos = 0;
        for_tuples!(
            #(
                let fixed = Tuple::FIXED_WORDS;
                Tuple.fill(&mut buf.descend(pos, fixed)?, a)?;
                pos += fixed;
            )*);
        Ok(())
    }
}

impl Serialize for () {
    const FIXED_WORDS: usize = 0;

    fn tot_len(&self) -> usize {
        0
    }

    fn fill(&self, _buf: &mut AllocBuf, _a: &mut Alloc) -> Result<()> {
        Ok(())
    }
}