1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use core::convert::{TryFrom, TryInto};
use crate::{Encodable, ErrorKind, header::Header, Length, Result, Tag};
#[derive(Debug)]
pub struct Encoder<'a> {
bytes: Option<&'a mut [u8]>,
position: Length,
}
impl<'a> Encoder<'a> {
pub fn new(bytes: &'a mut [u8]) -> Self {
Self {
bytes: Some(bytes),
position: Length::zero(),
}
}
pub fn encode<T: Encodable>(&mut self, encodable: &T) -> Result<()> {
if self.is_failed() {
self.error(ErrorKind::Failed)?;
}
encodable.encode(self).map_err(|e| {
self.bytes.take();
e.nested(self.position)
})
}
pub fn error<T>(&mut self, kind: ErrorKind) -> Result<T> {
self.bytes.take();
Err(kind.at(self.position))
}
pub fn is_failed(&self) -> bool {
self.bytes.is_none()
}
pub fn finish(self) -> Result<&'a [u8]> {
let position = self.position;
match self.bytes {
Some(bytes) => bytes
.get(..self.position.into())
.ok_or_else(|| ErrorKind::Truncated.at(position)),
None => Err(ErrorKind::Failed.at(position)),
}
}
pub fn encode_tagged_collection(&mut self, tag: Tag, encodables: &[&dyn Encodable]) -> Result<()> {
let expected_len = Length::try_from(encodables)?;
Header::new(tag, expected_len).and_then(|header| header.encode(self))?;
let mut nested_encoder = Encoder::new(self.reserve(expected_len)?);
for encodable in encodables {
encodable.encode(&mut nested_encoder)?;
}
if nested_encoder.finish()?.len() == expected_len.into() {
Ok(())
} else {
self.error(ErrorKind::Length { tag })
}
}
pub fn encode_untagged_collection(&mut self, encodables: &[&dyn Encodable]) -> Result<()> {
let expected_len = Length::try_from(encodables)?;
let mut nested_encoder = Encoder::new(self.reserve(expected_len)?);
for encodable in encodables {
encodable.encode(&mut nested_encoder)?;
}
Ok(())
}
pub(crate) fn byte(&mut self, byte: u8) -> Result<()> {
match self.reserve(1u8)?.first_mut() {
Some(b) => {
*b = byte;
Ok(())
}
None => self.error(ErrorKind::Truncated),
}
}
pub(crate) fn bytes(&mut self, slice: &[u8]) -> Result<()> {
self.reserve(slice.len())?.copy_from_slice(slice);
Ok(())
}
fn reserve(&mut self, len: impl TryInto<Length>) -> Result<&mut [u8]> {
let len = len
.try_into()
.or_else(|_| self.error(ErrorKind::Overflow))?;
if len > self.remaining_len()? {
self.error(ErrorKind::Overlength)?;
}
let end = (self.position + len).or_else(|e| self.error(e.kind()))?;
let range = self.position.into()..end.into();
let position = &mut self.position;
let slice = &mut self.bytes.as_mut().expect("DER encoder tainted")[range];
*position = end;
Ok(slice)
}
fn buffer_len(&self) -> Result<Length> {
self.bytes
.as_ref()
.map(|bytes| bytes.len())
.ok_or_else(|| ErrorKind::Failed.at(self.position))
.and_then(TryInto::try_into)
}
fn remaining_len(&self) -> Result<Length> {
self.buffer_len()?
.to_usize()
.checked_sub(self.position.into())
.ok_or_else(|| ErrorKind::Truncated.at(self.position))
.and_then(TryInto::try_into)
}
}
#[cfg(test)]
mod tests {
use core::convert::TryFrom;
use crate::{Encodable, Tag, TaggedSlice};
#[test]
fn zero_length() {
let tv = TaggedSlice::from(Tag::try_from(42).unwrap(), &[]).unwrap();
let mut buf = [0u8; 4];
assert_eq!(tv.encode_to_slice(&mut buf).unwrap(), &[0x2A, 0x00]);
}
}