ring/io/
der_writer.rs

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(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
29pub(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
42#[allow(clippy::cast_possible_truncation)]
43fn write_tlv<F>(output: &mut dyn Accumulator, tag: Tag, write_value: F)
44where
45    F: Fn(&mut dyn Accumulator),
46{
47    let length: usize = {
48        let mut length = LengthMeasurement::zero();
49        write_value(&mut length);
50        length.into()
51    };
52
53    output.write_byte(tag as u8);
54    if length < 0x80 {
55        output.write_byte(length as u8);
56    } else if length < 0x1_00 {
57        output.write_byte(0x81);
58        output.write_byte(length as u8);
59    } else if length < 0x1_00_00 {
60        output.write_byte(0x82);
61        output.write_byte((length / 0x1_00) as u8);
62        output.write_byte(length as u8);
63    } else {
64        unreachable!();
65    };
66
67    write_value(output);
68}