1use zeroize::{Zeroize, ZeroizeOnDrop};
6
7use super::compare::require_type;
8use super::cursor::Cursor;
9use super::error::{error, CborError, ErrorReason};
10use super::float::Float;
11use super::limits::{Budget, Limits};
12use super::profile::{LengthPolicy, Profile};
13use super::read_header::{read_header_prefix, ArgumentWidth, Header, MajorType};
14use super::scan::{add, scan, tail};
15
16pub struct Integer {
19 negative: bool,
20 argument: u64,
21}
22
23impl Integer {
24 #[must_use]
26 pub const fn is_negative(&self) -> bool {
27 self.negative
28 }
29 #[must_use]
31 pub const fn argument(&self) -> u64 {
32 self.argument
33 }
34 #[must_use]
36 pub fn to_i128(&self) -> i128 {
37 if self.negative {
38 -1 - i128::from(self.argument)
39 } else {
40 i128::from(self.argument)
41 }
42 }
43}
44
45impl Drop for Integer {
46 fn drop(&mut self) {
47 self.argument.zeroize();
48 self.negative.zeroize();
49 }
50}
51impl ZeroizeOnDrop for Integer {}
52
53pub struct Frame<'a> {
59 pub(super) encoded: &'a [u8],
60 pub(super) body: &'a [u8],
61 pub(super) header: Header<'a>,
62 pub(super) limits: Limits,
63 pub(super) lengths: LengthPolicy,
64}
65
66impl<'a> Frame<'a> {
67 #[must_use]
69 pub const fn received_bytes(&self) -> &'a [u8] {
70 self.encoded
71 }
72 #[must_use]
74 pub const fn header(&self) -> &Header<'a> {
75 &self.header
76 }
77 pub fn validate(&self, profile: Profile, limits: Limits) -> Result<Item<'a>, CborError> {
79 validate_exact(self.encoded, profile, limits)
80 }
81 pub fn integer(&self) -> Result<Integer, CborError> {
83 let negative = match self.header.major_type() {
84 MajorType::Unsigned => false,
85 MajorType::Negative => true,
86 _ => return Err(error(ErrorReason::WrongType)),
87 };
88 Ok(Integer {
89 negative,
90 argument: self
91 .header
92 .argument()
93 .ok_or(error(ErrorReason::WrongType))?,
94 })
95 }
96 pub fn float(&self) -> Result<Float, CborError> {
98 self.header.float()?.ok_or(error(ErrorReason::WrongType))
99 }
100 pub fn simple_value(&self) -> Result<u8, CborError> {
102 self.header
103 .simple_value()?
104 .ok_or(error(ErrorReason::WrongType))
105 }
106 pub fn as_bool(&self) -> Result<bool, CborError> {
108 const FALSE: u8 = 20;
109 const TRUE: u8 = 21;
110 match self.simple_value()? {
111 FALSE => Ok(false),
112 TRUE => Ok(true),
113 _ => Err(error(ErrorReason::WrongType)),
114 }
115 }
116 pub fn as_bytes(&self) -> Result<&'a [u8], CborError> {
118 require_type(self.header.major_type(), MajorType::Bytes)?;
119 self.contiguous()
120 }
121 pub fn as_text(&self) -> Result<&'a str, CborError> {
123 require_type(self.header.major_type(), MajorType::Text)?;
124 core::str::from_utf8(self.contiguous()?).map_err(|_| error(ErrorReason::InvalidUtf8))
125 }
126 fn contiguous(&self) -> Result<&'a [u8], CborError> {
127 if self.header.argument_width() == ArgumentWidth::Indefinite {
128 return Err(error(ErrorReason::NonContiguousString));
129 }
130 Ok(self.body)
131 }
132 pub fn string_chunks(&self) -> Result<StringChunks<'a>, CborError> {
135 if !matches!(self.header.major_type(), MajorType::Bytes | MajorType::Text) {
136 return Err(error(ErrorReason::WrongType));
137 }
138 Ok(StringChunks {
139 remaining: self.body,
140 definite: self.header.argument_width() != ArgumentWidth::Indefinite,
141 done: false,
142 })
143 }
144 pub fn children(&self) -> Result<Cursor<'a>, CborError> {
148 if !matches!(
149 self.header.major_type(),
150 MajorType::Array | MajorType::Map | MajorType::Tag
151 ) {
152 return Err(error(ErrorReason::WrongType));
153 }
154 Cursor::new(self.body, self.limits, self.lengths)
155 }
156 pub fn tagged_bytes(&self) -> Result<TaggedBytes<'a>, CborError> {
159 require_type(self.header.major_type(), MajorType::Tag)?;
160 let child = frame_exact(self.body, self.limits, self.lengths)?;
161 Ok(TaggedBytes {
162 tag: self
163 .header
164 .argument()
165 .ok_or(error(ErrorReason::WrongType))?,
166 outer: self.encoded,
167 payload: child.as_bytes()?,
168 })
169 }
170}
171
172pub struct Item<'a> {
175 frame: Frame<'a>,
176 profile: Profile,
177}
178
179impl<'a> Item<'a> {
180 #[must_use]
182 pub const fn frame(&self) -> &Frame<'a> {
183 &self.frame
184 }
185 #[must_use]
187 pub const fn profile(&self) -> Profile {
188 self.profile
189 }
190 pub fn children(&self) -> Result<ItemChildren<'a>, CborError> {
196 Ok(ItemChildren {
197 frames: self.frame.children()?,
198 profile: self.profile,
199 })
200 }
201}
202
203pub struct ItemChildren<'a> {
205 frames: Cursor<'a>,
206 profile: Profile,
207}
208
209impl<'a> Iterator for ItemChildren<'a> {
210 type Item = Result<Item<'a>, CborError>;
211 fn next(&mut self) -> Option<Self::Item> {
212 let profile = self.profile;
213 self.frames
214 .next()
215 .map(|frame| frame.map(|frame| Item { frame, profile }))
216 }
217}
218
219impl core::iter::FusedIterator for ItemChildren<'_> {}
220
221pub struct TaggedBytes<'a> {
223 tag: u64,
224 outer: &'a [u8],
225 payload: &'a [u8],
226}
227
228impl<'a> TaggedBytes<'a> {
229 #[must_use]
231 pub const fn tag(&self) -> u64 {
232 self.tag
233 }
234 #[must_use]
236 pub const fn received_bytes(&self) -> &'a [u8] {
237 self.outer
238 }
239 #[must_use]
241 pub const fn payload_bytes(&self) -> &'a [u8] {
242 self.payload
243 }
244 pub fn validate_embedded(
247 &self,
248 profile: Profile,
249 limits: Limits,
250 ) -> Result<Item<'a>, CborError> {
251 const ENCODED_CBOR_TAG: u64 = 24;
252 if self.tag != ENCODED_CBOR_TAG {
253 return Err(error(ErrorReason::WrongTag));
254 }
255 if self.payload.is_empty() {
256 return Err(error(ErrorReason::EmptyEmbeddedItem));
257 }
258 validate_exact(self.payload, profile, limits)
259 }
260}
261
262impl Drop for TaggedBytes<'_> {
263 fn drop(&mut self) {
264 self.tag.zeroize();
265 }
266}
267impl ZeroizeOnDrop for TaggedBytes<'_> {}
268
269pub struct StringChunks<'a> {
271 remaining: &'a [u8],
272 definite: bool,
273 done: bool,
274}
275
276impl<'a> Iterator for StringChunks<'a> {
277 type Item = Result<&'a [u8], CborError>;
278 fn next(&mut self) -> Option<Self::Item> {
279 if self.done {
280 return None;
281 }
282 if self.definite {
283 self.done = true;
284 return Some(Ok(self.remaining));
285 }
286 if self.remaining.is_empty() {
287 self.done = true;
288 return None;
289 }
290 let result = (|| {
291 let header = read_header_prefix(self.remaining)?;
292 let length =
293 usize::try_from(header.argument().ok_or(error(ErrorReason::InvalidChunk))?)
294 .map_err(|_| error(ErrorReason::ArithmeticOverflow))?;
295 let start = header.received_bytes().len();
296 let end = add(start, length)?;
297 let bytes = self
298 .remaining
299 .get(start..end)
300 .ok_or(error(ErrorReason::Truncated))?;
301 self.remaining = tail(self.remaining, end)?;
302 Ok(bytes)
303 })();
304 if result.is_err() {
305 self.done = true;
306 }
307 Some(result)
308 }
309}
310
311impl core::iter::FusedIterator for StringChunks<'_> {}
312
313pub(super) fn check_input(input: &[u8], limits: Limits) -> Result<(), CborError> {
314 if input.len() > limits.input {
315 Err(error(ErrorReason::InputLimit))
316 } else {
317 Ok(())
318 }
319}
320
321pub fn frame_prefix(
323 input: &[u8],
324 limits: Limits,
325 lengths: LengthPolicy,
326) -> Result<(Frame<'_>, &[u8]), CborError> {
327 check_input(input, limits)?;
328 let frame = scan(input, &mut Budget::new(limits), 0, None, true, lengths)?;
329 let rest = tail(input, frame.encoded.len())?;
330 Ok((frame, rest))
331}
332
333pub fn frame_exact(
335 input: &[u8],
336 limits: Limits,
337 lengths: LengthPolicy,
338) -> Result<Frame<'_>, CborError> {
339 let (frame, rest) = frame_prefix(input, limits, lengths)?;
340 if !rest.is_empty() {
341 return Err(error(ErrorReason::TrailingData));
342 }
343 Ok(frame)
344}
345
346pub fn validate_prefix(
348 input: &[u8],
349 profile: Profile,
350 limits: Limits,
351) -> Result<(Item<'_>, &[u8]), CborError> {
352 check_input(input, limits)?;
353 let frame = scan(
354 input,
355 &mut Budget::new(limits),
356 0,
357 Some(profile),
358 true,
359 profile.lengths,
360 )?;
361 let rest = tail(input, frame.encoded.len())?;
362 Ok((Item { frame, profile }, rest))
363}
364
365pub fn validate_exact(
367 input: &[u8],
368 profile: Profile,
369 limits: Limits,
370) -> Result<Item<'_>, CborError> {
371 let (item, rest) = validate_prefix(input, profile, limits)?;
372 if !rest.is_empty() {
373 return Err(error(ErrorReason::TrailingData));
374 }
375 Ok(item)
376}