| 1 | #[cfg(not(feature = "std"))] |
| 2 | use alloc::vec::Vec; |
| 3 | |
| 4 | use core::mem; |
| 5 | |
| 6 | use crate::state_tracker::{StructureError, Token}; |
| 7 | |
| 8 | /// The state of current level of the decoder |
| 9 | #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] |
| 10 | enum State<S: AsRef<[u8]>, E> { |
| 11 | /// An inner list. Allows any token |
| 12 | Seq, |
| 13 | /// Inside a map, expecting a key. Contains the last key read, so sorting can be validated |
| 14 | MapKey(Option<S>), |
| 15 | /// Inside a map, expecting a value. Contains the last key read, so sorting can be validated |
| 16 | MapValue(S), |
| 17 | /// Received an error while decoding |
| 18 | Failed(E), |
| 19 | } |
| 20 | |
| 21 | /// Used to validate that a structure is valid |
| 22 | #[derive(Debug)] |
| 23 | pub struct StateTracker<S: AsRef<[u8]>, E = StructureError> { |
| 24 | state: Vec<State<S, E>>, |
| 25 | max_depth: usize, |
| 26 | } |
| 27 | |
| 28 | impl<S: AsRef<[u8]>, E> Default for StateTracker<S, E> { |
| 29 | fn default() -> Self { |
| 30 | StateTracker { |
| 31 | state: Vec::with_capacity(2048), |
| 32 | max_depth: 2048, |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl<S: AsRef<[u8]>, E> StateTracker<S, E> |
| 38 | where |
| 39 | S: AsRef<[u8]>, |
| 40 | E: From<StructureError> + Clone, |
| 41 | { |
| 42 | pub fn new() -> Self { |
| 43 | <Self as Default>::default() |
| 44 | } |
| 45 | |
| 46 | pub fn set_max_depth(&mut self, new_max_depth: usize) { |
| 47 | self.max_depth = new_max_depth |
| 48 | } |
| 49 | |
| 50 | pub fn remaining_depth(&self) -> usize { |
| 51 | self.max_depth - self.state.len() |
| 52 | } |
| 53 | |
| 54 | /// Observe that an EOF was seen. This function is idempotent. |
| 55 | pub fn observe_eof(&mut self) -> Result<(), E> { |
| 56 | self.check_error()?; |
| 57 | |
| 58 | if self.state.is_empty() { |
| 59 | Ok(()) |
| 60 | } else { |
| 61 | self.latch_err(Err(E::from(StructureError::UnexpectedEof))) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | #[allow(clippy::match_same_arms)] |
| 66 | pub fn observe_token<'a>(&mut self, token: &Token<'a>) -> Result<(), E> |
| 67 | where |
| 68 | S: From<&'a [u8]>, |
| 69 | { |
| 70 | use self::{State::*, Token::*}; |
| 71 | match (self.state.last_mut(), *token) { |
| 72 | (None, End) => { |
| 73 | return self.latch_err(Err(E::from(StructureError::invalid_state( |
| 74 | "End not allowed at top level", |
| 75 | )))); |
| 76 | }, |
| 77 | (Some(Seq), End) | (Some(MapKey(_)), End) => { |
| 78 | self.state.pop(); |
| 79 | }, |
| 80 | (Some(MapKey(Some(oldlabel))), String(label)) if oldlabel.as_ref() >= label => { |
| 81 | self.state.pop(); |
| 82 | return self.latch_err(Err(E::from(StructureError::UnsortedKeys))); |
| 83 | }, |
| 84 | (Some(MapKey(Some(_oldlabel))), String(label)) => { |
| 85 | *self.state.last_mut().unwrap() = MapValue(S::from(label)); |
| 86 | }, |
| 87 | (Some(MapKey(None)), String(label)) => { |
| 88 | *self.state.last_mut().unwrap() = MapValue(S::from(label)); |
| 89 | }, |
| 90 | (Some(_oldstate @ MapKey(_)), _tok) => { |
| 91 | return self.latch_err(Err(E::from(StructureError::invalid_state( |
| 92 | "Map keys must be strings", |
| 93 | )))); |
| 94 | }, |
| 95 | (Some(MapValue(label)), List) | (Some(MapValue(label)), Dict) => { |
| 96 | let dummy: &[u8] = &[]; |
| 97 | *self.state.last_mut().unwrap() = |
| 98 | MapKey(Some(mem::replace(label, dummy.into()))); |
| 99 | if self.state.len() >= self.max_depth { |
| 100 | return self.latch_err(Err(E::from(StructureError::NestingTooDeep))); |
| 101 | } |
| 102 | self.state |
| 103 | .push(if token == &List { Seq } else { MapKey(None) }); |
| 104 | }, |
| 105 | (Some(_oldstate @ MapValue(_)), End) => { |
| 106 | self.state.pop(); |
| 107 | return self.latch_err(Err(E::from(StructureError::invalid_state( |
| 108 | "Missing map value", |
| 109 | )))); |
| 110 | }, |
| 111 | (Some(MapValue(label)), _) => { |
| 112 | let dummy: &[u8] = &[]; |
| 113 | *self.state.last_mut().unwrap() = |
| 114 | MapKey(Some(mem::replace(label, dummy.into()))); |
| 115 | }, |
| 116 | (_oldstate, List) | (_oldstate, Dict) => { |
| 117 | if self.state.len() >= self.max_depth { |
| 118 | return self.latch_err(Err(E::from(StructureError::NestingTooDeep))); |
| 119 | } |
| 120 | self.state |
| 121 | .push(if token == &List { Seq } else { MapKey(None) }); |
| 122 | }, |
| 123 | _ => {}, |
| 124 | } |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | pub fn latch_err<T>(&mut self, result: Result<T, E>) -> Result<T, E> { |
| 129 | self.check_error()?; |
| 130 | if let Err(ref err) = result { |
| 131 | self.state.push(State::Failed(err.clone())) |
| 132 | } |
| 133 | result |
| 134 | } |
| 135 | |
| 136 | pub fn check_error(&self) -> Result<(), E> { |
| 137 | if let Some(State::Failed(error)) = self.state.last() { |
| 138 | Err(error.clone()) |
| 139 | } else { |
| 140 | Ok(()) |
| 141 | } |
| 142 | } |
| 143 | } |