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 { |
18 | fn write_byte(&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 From<LengthMeasurement> for usize { |
27 | fn from(len: LengthMeasurement) -> usize { |
28 | len.len |
29 | } |
30 | } |
31 | |
32 | impl LengthMeasurement { |
33 | pub fn zero() -> Self { |
34 | Self { len: 0 } |
35 | } |
36 | } |
37 | |
38 | impl Accumulator for LengthMeasurement { |
39 | fn write_byte(&mut self, _value: u8) { |
40 | self.len += 1; |
41 | } |
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 { |
53 | 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 From<Writer> for Box<[u8]> { |
62 | fn from(writer: Writer) -> Self { |
63 | assert_eq!(writer.requested_capacity, writer.bytes.len()); |
64 | writer.bytes.into_boxed_slice() |
65 | } |
66 | } |
67 | |
68 | impl Accumulator for Writer { |
69 | fn write_byte(&mut self, value: u8) { |
70 | self.bytes.push(value); |
71 | } |
72 | fn write_bytes(&mut self, value: &[u8]) { |
73 | self.bytes.extend(iter:value); |
74 | } |
75 | } |
76 | |
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 | |