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 super::{der::*, writer::*, *};
16 use alloc::boxed::Box;
17
write_positive_integer(output: &mut dyn Accumulator, value: &Positive)18 pub(crate) fn write_positive_integer(output: &mut dyn Accumulator, value: &Positive) {
19 let first_byte = value.first_byte();
20 let value = value.big_endian_without_leading_zero_as_input();
21 write_tlv(output, Tag::Integer, |output| {
22 if (first_byte & 0x80) != 0 {
23 output.write_byte(0); // Disambiguate negative number.
24 }
25 write_copy(output, value)
26 })
27 }
28
write_all(tag: Tag, write_value: &dyn Fn(&mut dyn Accumulator)) -> Box<[u8]>29 pub(crate) fn write_all(tag: Tag, write_value: &dyn Fn(&mut dyn Accumulator)) -> Box<[u8]> {
30 let length = {
31 let mut length = LengthMeasurement::zero();
32 write_tlv(&mut length, tag, write_value);
33 length
34 };
35
36 let mut output = Writer::with_capacity(length);
37 write_tlv(&mut output, tag, write_value);
38
39 output.into()
40 }
41
write_tlv<F>(output: &mut dyn Accumulator, tag: Tag, write_value: F) where F: Fn(&mut dyn Accumulator),42 fn write_tlv<F>(output: &mut dyn Accumulator, tag: Tag, write_value: F)
43 where
44 F: Fn(&mut dyn Accumulator),
45 {
46 let length: usize = {
47 let mut length = LengthMeasurement::zero();
48 write_value(&mut length);
49 length.into()
50 };
51
52 output.write_byte(tag as u8);
53 if length < 0x80 {
54 output.write_byte(length as u8);
55 } else if length < 0x1_00 {
56 output.write_byte(0x81);
57 output.write_byte(length as u8);
58 } else if length < 0x1_00_00 {
59 output.write_byte(0x82);
60 output.write_byte((length / 0x1_00) as u8);
61 output.write_byte(length as u8);
62 } else {
63 unreachable!();
64 };
65
66 write_value(output);
67 }
68