1 // Copyright 2018 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 use alloc::{boxed::Box, vec::Vec};
16 
17 pub trait Accumulator {
write_byte(&mut self, value: u8)18     fn write_byte(&mut self, value: u8);
write_bytes(&mut self, value: &[u8])19     fn write_bytes(&mut self, value: &[u8]);
20 }
21 
22 pub(super) struct LengthMeasurement {
23     len: usize,
24 }
25 
26 impl Into<usize> for LengthMeasurement {
into(self) -> usize27     fn into(self) -> usize {
28         self.len
29     }
30 }
31 
32 impl LengthMeasurement {
zero() -> Self33     pub fn zero() -> Self {
34         Self { len: 0 }
35     }
36 }
37 
38 impl Accumulator for LengthMeasurement {
write_byte(&mut self, _value: u8)39     fn write_byte(&mut self, _value: u8) {
40         self.len += 1;
41     }
write_bytes(&mut self, value: &[u8])42     fn write_bytes(&mut self, value: &[u8]) {
43         self.len += value.len();
44     }
45 }
46 
47 pub(super) struct Writer {
48     bytes: Vec<u8>,
49     requested_capacity: usize,
50 }
51 
52 impl Writer {
with_capacity(capacity: LengthMeasurement) -> Self53     pub(super) fn with_capacity(capacity: LengthMeasurement) -> Self {
54         Self {
55             bytes: Vec::with_capacity(capacity.len),
56             requested_capacity: capacity.len,
57         }
58     }
59 }
60 
61 impl Into<Box<[u8]>> for Writer {
into(self) -> Box<[u8]>62     fn into(self) -> Box<[u8]> {
63         assert_eq!(self.requested_capacity, self.bytes.len());
64         self.bytes.into_boxed_slice()
65     }
66 }
67 
68 impl Accumulator for Writer {
write_byte(&mut self, value: u8)69     fn write_byte(&mut self, value: u8) {
70         self.bytes.push(value);
71     }
write_bytes(&mut self, value: &[u8])72     fn write_bytes(&mut self, value: &[u8]) {
73         self.bytes.extend(value);
74     }
75 }
76 
write_copy(accumulator: &mut dyn Accumulator, to_copy: untrusted::Input)77 pub fn write_copy(accumulator: &mut dyn Accumulator, to_copy: untrusted::Input) {
78     accumulator.write_bytes(to_copy.as_slice_less_safe())
79 }
80