1use std::cmp::Ordering;
4use std::fmt;
5
6use super::{Integer, Map, MapKey, TAG_DECIMAL, TAG_UUID, Value, major, simple};
7
8pub const MAX_DEPTH: usize = 64;
10
11pub fn decode(bytes: &[u8]) -> Result<Value, DecodeError> {
20 let mut decoder = Decoder { bytes, position: 0 };
21 let value = decoder.value(0)?;
22 if decoder.position == bytes.len() {
23 Ok(value)
24 } else {
25 Err(DecodeError::new(
26 decoder.position,
27 DecodeErrorKind::TrailingBytes,
28 ))
29 }
30}
31
32pub fn decode_first(bytes: &[u8]) -> Result<(Value, usize), DecodeError> {
41 let mut decoder = Decoder { bytes, position: 0 };
42 let value = decoder.value(0)?;
43 Ok((value, decoder.position))
44}
45
46#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
48#[error("{kind} at byte {offset}")]
49pub struct DecodeError {
50 offset: usize,
51 kind: DecodeErrorKind,
52}
53
54impl DecodeError {
55 fn new(offset: usize, kind: DecodeErrorKind) -> Self {
56 Self { offset, kind }
57 }
58
59 #[must_use]
61 pub fn offset(&self) -> usize {
62 self.offset
63 }
64
65 #[must_use]
67 pub fn kind(&self) -> &DecodeErrorKind {
68 &self.kind
69 }
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum DecodeErrorKind {
76 UnexpectedEnd,
79 TrailingBytes,
81 NotShortest,
83 IndefiniteLength,
85 Reserved,
87 Float,
89 SimpleValue,
91 InvalidUtf8,
93 InvalidMapKey,
95 UnsortedKeys,
97 DuplicateKey,
99 UnsupportedTag,
101 InvalidTagContent,
103 TooDeep,
105}
106
107impl fmt::Display for DecodeErrorKind {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.write_str(match self {
110 Self::UnexpectedEnd => "unexpected end of input",
111 Self::TrailingBytes => "bytes after the end of the value",
112 Self::NotShortest => "number not in its shortest form",
113 Self::IndefiniteLength => "indefinite length",
114 Self::Reserved => "reserved additional information",
115 Self::Float => "floating-point number",
116 Self::SimpleValue => "simple value other than false, true and null",
117 Self::InvalidUtf8 => "text that is not valid UTF-8",
118 Self::InvalidMapKey => "map key that is neither an integer nor text",
119 Self::UnsortedKeys => "map key out of order",
120 Self::DuplicateKey => "duplicate map key",
121 Self::UnsupportedTag => "unsupported tag",
122 Self::InvalidTagContent => "invalid tag content",
123 Self::TooDeep => "nesting too deep",
124 })
125 }
126}
127
128struct Decoder<'a> {
129 bytes: &'a [u8],
130 position: usize,
131}
132
133impl<'a> Decoder<'a> {
134 fn value(&mut self, depth: usize) -> Result<Value, DecodeError> {
137 let start = self.position;
138 let initial = self.byte()?;
139 let (major, info) = (initial >> 5, initial & 0x1f);
140 match major {
141 major::UNSIGNED => {
142 let argument = self.argument(info, start)?;
143 Ok(Value::Integer(Integer::from(argument)))
144 }
145 major::NEGATIVE => {
146 let argument = self.argument(info, start)?;
147 let value = Integer::new(-1 - i128::from(argument)).expect("at least -2^64");
148 Ok(Value::Integer(value))
149 }
150 major::BYTES => {
151 let argument = self.argument(info, start)?;
152 Ok(Value::Bytes(self.take(argument, start)?.to_vec()))
153 }
154 major::TEXT => {
155 let argument = self.argument(info, start)?;
156 let bytes = self.take(argument, start)?;
157 let text = std::str::from_utf8(bytes)
158 .map_err(|_| DecodeError::new(start, DecodeErrorKind::InvalidUtf8))?;
159 Ok(Value::Text(text.to_owned()))
160 }
161 major::ARRAY => {
162 let argument = self.argument(info, start)?;
163 Self::enter(depth, start)?;
164 let count = self.count(argument, start)?;
165 let mut items = Vec::with_capacity(count);
166 for _ in 0..count {
167 items.push(self.value(depth + 1)?);
168 }
169 Ok(Value::Array(items))
170 }
171 major::MAP => {
172 let argument = self.argument(info, start)?;
173 Self::enter(depth, start)?;
174 let count = self.count(argument, start)?;
175 self.map(count, depth)
176 }
177 major::TAG => {
178 let argument = self.argument(info, start)?;
179 self.tag(argument, start)
180 }
181 _ => Self::simple(initial, start),
182 }
183 }
184
185 fn map(&mut self, count: usize, depth: usize) -> Result<Value, DecodeError> {
186 let mut entries: Vec<(MapKey, Value)> = Vec::with_capacity(count);
187 for _ in 0..count {
188 let key_start = self.position;
189 let key = self.map_key()?;
190 if let Some((previous, _)) = entries.last() {
191 match previous.cmp(&key) {
192 Ordering::Less => {}
193 Ordering::Equal => {
194 return Err(DecodeError::new(key_start, DecodeErrorKind::DuplicateKey));
195 }
196 Ordering::Greater => {
197 return Err(DecodeError::new(key_start, DecodeErrorKind::UnsortedKeys));
198 }
199 }
200 }
201 let value = self.value(depth + 1)?;
202 entries.push((key, value));
203 }
204 Ok(Value::Map(Map::from_sorted(entries)))
205 }
206
207 fn map_key(&mut self) -> Result<MapKey, DecodeError> {
210 let start = self.position;
211 let major = self.peek()? >> 5;
212 if !matches!(major, major::UNSIGNED | major::NEGATIVE | major::TEXT) {
213 return Err(DecodeError::new(start, DecodeErrorKind::InvalidMapKey));
214 }
215 match self.value(0)? {
216 Value::Integer(integer) => Ok(MapKey::Integer(integer)),
217 Value::Text(text) => Ok(MapKey::Text(text)),
218 _ => unreachable!("major types 0, 1 and 3 decode to integers or text"),
219 }
220 }
221
222 fn tag(&mut self, number: u64, start: usize) -> Result<Value, DecodeError> {
226 match number {
227 TAG_DECIMAL => {
228 let content = self.position;
229 let invalid = || DecodeError::new(content, DecodeErrorKind::InvalidTagContent);
230 let (major, count) = self.header()?;
231 if major != major::ARRAY || count != 2 {
232 return Err(invalid());
233 }
234 let exponent = self.integer().ok_or_else(invalid)??;
235 let mantissa = self.integer().ok_or_else(invalid)??;
236 Ok(Value::Decimal { exponent, mantissa })
237 }
238 TAG_UUID => {
239 let content = self.position;
240 let invalid = || DecodeError::new(content, DecodeErrorKind::InvalidTagContent);
241 let (major, len) = self.header()?;
242 if major != major::BYTES || len != 16 {
243 return Err(invalid());
244 }
245 let bytes = self.take(len, content)?;
246 Ok(Value::Uuid(bytes.try_into().expect("took 16 bytes")))
247 }
248 _ => Err(DecodeError::new(start, DecodeErrorKind::UnsupportedTag)),
249 }
250 }
251
252 fn integer(&mut self) -> Option<Result<Integer, DecodeError>> {
255 let major = match self.peek() {
256 Ok(initial) => initial >> 5,
257 Err(error) => return Some(Err(error)),
258 };
259 if !matches!(major, major::UNSIGNED | major::NEGATIVE) {
260 return None;
261 }
262 Some(self.value(0).map(|value| match value {
263 Value::Integer(integer) => integer,
264 _ => unreachable!("major types 0 and 1 decode to integers"),
265 }))
266 }
267
268 fn header(&mut self) -> Result<(u8, u64), DecodeError> {
270 let start = self.position;
271 let initial = self.byte()?;
272 let (major, info) = (initial >> 5, initial & 0x1f);
273 if major > major::TAG {
274 return Ok((major, 0));
275 }
276 Ok((major, self.argument(info, start)?))
277 }
278
279 fn simple(initial: u8, start: usize) -> Result<Value, DecodeError> {
280 match initial {
281 simple::FALSE => Ok(Value::Bool(false)),
282 simple::TRUE => Ok(Value::Bool(true)),
283 simple::NULL => Ok(Value::Null),
284 0xf9..=0xfb => Err(DecodeError::new(start, DecodeErrorKind::Float)),
285 0xfc..=0xfe => Err(DecodeError::new(start, DecodeErrorKind::Reserved)),
286 _ => Err(DecodeError::new(start, DecodeErrorKind::SimpleValue)),
287 }
288 }
289
290 fn enter(depth: usize, start: usize) -> Result<(), DecodeError> {
292 if depth < MAX_DEPTH {
293 Ok(())
294 } else {
295 Err(DecodeError::new(start, DecodeErrorKind::TooDeep))
296 }
297 }
298
299 fn argument(&mut self, info: u8, start: usize) -> Result<u64, DecodeError> {
302 let not_shortest = || DecodeError::new(start, DecodeErrorKind::NotShortest);
303 match info {
304 0..=23 => Ok(u64::from(info)),
305 24 => {
306 let argument = u64::from(self.byte()?);
307 if argument < 24 {
308 Err(not_shortest())
309 } else {
310 Ok(argument)
311 }
312 }
313 25 => {
314 let argument = u64::from(u16::from_be_bytes(self.array()?));
315 if argument <= 0xff {
316 Err(not_shortest())
317 } else {
318 Ok(argument)
319 }
320 }
321 26 => {
322 let argument = u64::from(u32::from_be_bytes(self.array()?));
323 if argument <= 0xffff {
324 Err(not_shortest())
325 } else {
326 Ok(argument)
327 }
328 }
329 27 => {
330 let argument = u64::from_be_bytes(self.array()?);
331 if argument <= 0xffff_ffff {
332 Err(not_shortest())
333 } else {
334 Ok(argument)
335 }
336 }
337 28..=30 => Err(DecodeError::new(start, DecodeErrorKind::Reserved)),
338 _ => Err(DecodeError::new(start, DecodeErrorKind::IndefiniteLength)),
339 }
340 }
341
342 fn count(&self, count: u64, start: usize) -> Result<usize, DecodeError> {
346 usize::try_from(count)
347 .ok()
348 .filter(|&count| count <= self.remaining())
349 .ok_or_else(|| DecodeError::new(start, DecodeErrorKind::UnexpectedEnd))
350 }
351
352 fn take(&mut self, len: u64, start: usize) -> Result<&'a [u8], DecodeError> {
354 let len = self.count(len, start)?;
355 let bytes = &self.bytes[self.position..self.position + len];
356 self.position += len;
357 Ok(bytes)
358 }
359
360 fn peek(&self) -> Result<u8, DecodeError> {
361 self.bytes
362 .get(self.position)
363 .copied()
364 .ok_or_else(|| DecodeError::new(self.position, DecodeErrorKind::UnexpectedEnd))
365 }
366
367 fn byte(&mut self) -> Result<u8, DecodeError> {
368 let byte = *self
369 .bytes
370 .get(self.position)
371 .ok_or_else(|| DecodeError::new(self.position, DecodeErrorKind::UnexpectedEnd))?;
372 self.position += 1;
373 Ok(byte)
374 }
375
376 fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
377 let start = self.position;
378 let bytes = self.take(N as u64, start)?;
379 Ok(bytes.try_into().expect("took exactly N bytes"))
380 }
381
382 fn remaining(&self) -> usize {
383 self.bytes.len() - self.position
384 }
385}