core_json/stack/
mod.rs

1use core::fmt::Debug;
2
3mod r#const;
4pub use r#const::ConstStack;
5
6/// An item within the stack, representing the state during deserialization.
7#[derive(Clone, Copy, Debug)]
8pub enum State {
9  /// Corresponds to `{`, used for representing objects
10  Object,
11  /// Corresponds to `[`, used for representing arrays
12  Array,
13  /// An unknown item is being read.
14  Unknown,
15}
16
17/// A trait representing a stack.
18pub trait Stack: Debug {
19  /// This stack's error type.
20  type Error: Sized + Copy + Debug;
21
22  /// Create an empty stack.
23  fn empty() -> Self;
24
25  /// The current stack depth.
26  fn depth(&self) -> usize;
27
28  /// Peek at the current item on the stack.
29  fn peek(&self) -> Option<State>;
30
31  /// Pop the next item from the stack.
32  fn pop(&mut self) -> Option<State>;
33
34  /// Push an item onto the stack.
35  fn push(&mut self, item: State) -> Result<(), Self::Error>;
36}
37
38#[cfg(feature = "alloc")]
39use alloc::vec::Vec;
40/// An unbounded `Stack` premised on the allocating `Vec`.
41///
42/// This SHOULD NOT be used. This allows serializations to use an unbounded amount of memory to
43/// represent objects of arbitrary depth. It's here solely to offer 'complete' support for all
44/// possible serializations (compliant with RFC 8259).
45#[cfg(feature = "alloc")]
46impl Stack for Vec<State> {
47  type Error = core::convert::Infallible;
48
49  #[inline(always)]
50  fn empty() -> Self {
51    Vec::with_capacity(1)
52  }
53
54  #[inline(always)]
55  fn depth(&self) -> usize {
56    self.len()
57  }
58
59  #[inline(always)]
60  fn peek(&self) -> Option<State> {
61    self.last().copied()
62  }
63
64  #[inline(always)]
65  fn pop(&mut self) -> Option<State> {
66    Vec::<State>::pop(self)
67  }
68
69  #[inline(always)]
70  fn push(&mut self, item: State) -> Result<(), Self::Error> {
71    Vec::<State>::push(self, item);
72    Ok(())
73  }
74}