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