Skip to main content

rustbinary/
probe.rs

1//! Allocation-free structural inspection using the self-describing decoder's parser.
2//! Reports consumed bytes, containers, elements and maximum depth, with the same
3//! wire validation and limits as decoding. Target-type compatibility and work
4//! spent on speculative deserialization still require a full decode.
5//!
6//! # Example
7//!
8//! ```
9//! use rustbinary::{options, Error};
10//!
11//! let frame = options().serialize(&vec![1u32, 2, 3]).unwrap();
12//! let probe = options().probe(&frame)?;
13//! assert_eq!(probe.bytes(), frame.len());
14//! assert_eq!(probe.containers(), 1);
15//! assert_eq!(probe.elements(), 3);
16//! # Ok::<(), rustbinary::Error>(())
17//! ```
18
19use crate::config::Config;
20use crate::error::Result;
21
22/// Exact structural footprint of one self-describing value.
23///
24/// Produced by [`Config::probe`]; the metrics are a pure function of the input
25/// bytes and the configuration, so two probes of the same frame always agree.
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub struct Probe {
28    bytes: usize,
29    containers: u64,
30    elements: u64,
31    depth: usize,
32    values: u64,
33    max_collection_len: u64,
34}
35
36impl Probe {
37    pub(crate) const fn new(
38        bytes: usize,
39        containers: u64,
40        elements: u64,
41        depth: usize,
42        values: u64,
43        max_collection_len: u64,
44    ) -> Self {
45        Self {
46            bytes,
47            containers,
48            elements,
49            depth,
50            values,
51            max_collection_len,
52        }
53    }
54    /// Tokens including keys and container starts; terminators are excluded.
55    pub const fn values(self) -> u64 {
56        self.values
57    }
58
59    /// Exact number of bytes the value occupies in the input.
60    pub const fn bytes(self) -> usize {
61        self.bytes
62    }
63
64    /// Number of array/object containers nested inside the value.
65    pub const fn containers(self) -> u64 {
66        self.containers
67    }
68
69    /// Total entries across every container: array elements plus object
70    /// key-value pairs (each pair counts once, matching the decoder's
71    /// collection-limit accounting).
72    pub const fn elements(self) -> u64 {
73        self.elements
74    }
75
76    /// Largest entry count of any single array or object.
77    pub const fn max_collection_len(self) -> u64 {
78        self.max_collection_len
79    }
80
81    /// Maximum container nesting depth (0 for a scalar value).
82    pub const fn depth(self) -> usize {
83        self.depth
84    }
85
86    /// Whether the value fits an input/work budget of `max_bytes` bytes.
87    pub const fn fits_input(self, max_bytes: u64) -> bool {
88        (self.bytes as u64) <= max_bytes
89    }
90
91    /// Whether the value's nesting fits a depth budget of `max_depth` levels.
92    pub const fn fits_depth(self, max_depth: usize) -> bool {
93        self.depth <= max_depth
94    }
95
96    /// Checks input, minimum read work, depth, visits and per-collection limits.
97    ///
98    /// The probe knows the exact byte count and shape; the budget supplies the
99    /// policy. Allocation and custom trait work cannot be decided here. This checks
100    /// necessary parser conditions, not whether typed decoding will succeed.
101    #[cfg(feature = "bounded")]
102    pub const fn fits_budget(self, budget: crate::bounded::Budget) -> bool {
103        (self.bytes as u64) <= budget.max_input()
104            && (self.bytes as u64) <= budget.max_work()
105            && self.depth <= budget.max_depth()
106            && self.values <= budget.max_values()
107            && self.max_collection_len <= budget.max_collection()
108    }
109}
110
111/// Walks one self-describing value and reports its exact structural footprint.
112///
113/// Allocation-free and side-effect free: the walker holds only the input
114/// borrow, a cursor, and counters.
115pub fn probe(config: Config, input: &[u8]) -> Result<Probe> {
116    crate::decoder::probe(input, config)
117}
118
119// ---------------------------------------------------------------------------
120// Tests
121// ---------------------------------------------------------------------------
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::tags::{MARKER_U16, TAG_END, TAG_STRING, TAG_U64};
127    use crate::Error;
128    use alloc::borrow::ToOwned;
129    use alloc::vec;
130    use alloc::vec::Vec;
131
132    fn value_for_scalars() -> Vec<nextjson::Value> {
133        use nextjson::{Number, Value};
134        vec![
135            Value::Null,
136            Value::Bool(true),
137            Value::Number(Number::U64(0)),
138            Value::Number(Number::U64(251)),
139            Value::Number(Number::U64(u64::MAX)),
140            Value::Number(Number::I64(-1)),
141            Value::Number(Number::F64(1.5)),
142            Value::String("hello".into()),
143        ]
144    }
145
146    #[test]
147    fn probe_matches_encoder_byte_accounting() {
148        let config = crate::options();
149        for value in value_for_scalars() {
150            let bytes = config.serialize(&value).unwrap();
151            let probe = probe(config, &bytes).unwrap();
152            assert_eq!(probe.bytes(), bytes.len(), "byte accounting for {value:?}");
153            assert_eq!(probe.containers(), 0);
154            assert_eq!(probe.elements(), 0);
155            assert_eq!(probe.depth(), 0);
156        }
157    }
158
159    #[test]
160    fn probe_reports_nested_shape() {
161        use nextjson::{Number, Value};
162        let config = crate::options();
163        // [ [1, 2], {"a": 3} ] — 3 containers, 5 entries total.
164        let object = Value::Object(
165            [("a".to_owned(), Value::Number(Number::U64(3)))]
166                .into_iter()
167                .collect(),
168        );
169        let frame = config
170            .serialize(&Value::Array(vec![
171                Value::Array(vec![
172                    Value::Number(Number::U64(1)),
173                    Value::Number(Number::U64(2)),
174                ]),
175                object,
176            ]))
177            .unwrap();
178        let probe = probe(config, &frame).unwrap();
179        assert_eq!(probe.bytes(), frame.len());
180        assert_eq!(probe.containers(), 3); // outer + inner array + object
181        assert_eq!(probe.elements(), 5); // 2 (outer) + 2 (inner array) + 1 (object pair)
182        assert_eq!(probe.depth(), 2);
183    }
184
185    #[test]
186    fn probe_acceptance_matches_deserialize() {
187        let config = crate::options().with_limit(64).with_collection_limit(8);
188        let frame = config.serialize(&vec![1u64, 2, 3, 4]).unwrap();
189        for cut in 0..frame.len() {
190            let decoded = config.deserialize::<Vec<u64>>(&frame[..cut]);
191            let probed = probe(config, &frame[..cut]);
192            assert_eq!(
193                probed.is_ok(),
194                decoded.is_ok(),
195                "acceptance drift at cut {cut}"
196            );
197            if let Ok(probe) = probed {
198                assert_eq!(probe.bytes(), frame.len().min(cut));
199            }
200        }
201        assert_eq!(probe(config, &frame).unwrap().bytes(), frame.len());
202    }
203
204    #[test]
205    fn probe_enforces_limits_like_decode() {
206        let encoded = crate::options().serialize(&vec![1u64, 2, 3]).unwrap();
207        let config = crate::options().with_collection_limit(2);
208        assert!(matches!(
209            probe(config, &encoded),
210            Err(Error::CollectionLimit { limit: 2 })
211        ));
212        assert!(matches!(
213            config.deserialize::<Vec<u64>>(&encoded),
214            Err(Error::CollectionLimit { limit: 2 })
215        ));
216
217        let deep = crate::options().serialize(&vec![vec![1u64]]).unwrap();
218        let config = crate::options().with_depth_limit(1);
219        assert!(probe(config, &deep).is_err());
220        assert!(config.deserialize::<Vec<Vec<u64>>>(&deep).is_err());
221
222        let wide = crate::options().serialize(&vec![1u64; 4]).unwrap();
223        let config = crate::options().with_limit(8);
224        assert!(probe(config, &wide).is_err());
225        assert!(config.deserialize::<Vec<u64>>(&wide).is_err());
226    }
227
228    #[test]
229    fn probe_rejects_malformed_and_trailing() {
230        let config = crate::options();
231        // Non-canonical varint.
232        assert!(matches!(
233            probe(config, &[TAG_U64, MARKER_U16, 5, 0]),
234            Err(Error::NonCanonicalVarint)
235        ));
236        // Invalid marker.
237        assert!(matches!(
238            probe(config, &[TAG_U64, 255]),
239            Err(Error::InvalidVarintMarker(255))
240        ));
241        // Terminator in value position.
242        assert!(matches!(probe(config, &[TAG_END]), Err(Error::Custom(_))));
243        assert!(matches!(
244            probe(config, &[TAG_STRING, 5, b'a']),
245            Err(Error::UnexpectedEnd)
246        ));
247        // Trailing bytes are rejected by default and allowed on request.
248        let mut frame = config.serialize(&7u64).unwrap();
249        frame.push(0);
250        assert!(matches!(
251            probe(config, &frame),
252            Err(Error::TrailingBytes { remaining: 1 })
253        ));
254        assert_eq!(
255            probe(config.allow_trailing_bytes(), &frame)
256                .unwrap()
257                .bytes(),
258            config.serialize(&7u64).unwrap().len()
259        );
260    }
261
262    #[test]
263    fn probe_walks_large_frames_without_allocating() {
264        let config = crate::options();
265        let frame = config
266            .serialize(&(0..10_000u64).collect::<Vec<_>>())
267            .unwrap();
268        let probe = probe(config, &frame).unwrap();
269        assert_eq!(probe.bytes(), frame.len());
270        assert_eq!(probe.containers(), 1);
271        assert_eq!(probe.elements(), 10_000);
272        assert_eq!(probe.depth(), 1);
273    }
274
275    #[cfg(feature = "bounded")]
276    #[test]
277    fn probe_integrates_with_budget() {
278        use crate::bounded::Budget;
279        let config = crate::options();
280        let frame = config.serialize(&vec![1u64, 2, 3]).unwrap();
281        let probe = probe(config, &frame).unwrap();
282        assert!(probe.fits_budget(Budget::default()));
283        assert!(probe.fits_budget(Budget::default().with_max_input(frame.len() as u64)));
284        assert!(!probe.fits_budget(Budget::default().with_max_input(frame.len() as u64 - 1)));
285        assert!(!probe.fits_budget(Budget::default().with_max_depth(0)));
286        assert!(probe.fits_input(frame.len() as u64));
287        assert!(probe.fits_depth(1));
288    }
289}