qubit-json 0.13.0

Resource-aware infrastructure for lenient and strict JSON processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Lexical-event consumer that builds a validated safe JSON value.

use serde_json::from_slice;

use super::validated_consumer_error::ValidatedConsumerError;
use super::validated_container::ValidatedContainer;
use crate::decode::JsonDecodeContext;
use crate::decode::JsonNumberPolicy;
use crate::decode::JsonNumberToken;
use crate::decode::JsonPathSegment;
use crate::decode::JsonValidatedDecodeOptions;
use crate::decode::JsonValidatedLimit;
use crate::lexical::JsonLexicalConsumer;
use crate::lexical::JsonLexicalEvent;
use crate::lexical::JsonNumberModel;
use crate::value::SafeJsonValue;
use crate::value::internal::JsonValueMaterializationError;
use crate::value::internal::LexicalJsonValueBuilder;

/// Builds one validated value while tracking lexical traversal state.
///
/// The container stack records only unclosed containers. When path tracking is
/// disabled, callback paths are not built, while builder behavior, limits, and
/// container progression remain identical in the value builder, while this
/// consumer's path and container stack stay unallocated. Object key segments
/// are pushed only after key acceptance and are popped after the scalar or
/// whole child container ends when path tracking is enabled. The builder
/// protects partial materialization; this consumer never commits the
/// surrounding decode transaction.
///
/// # Type Parameters
///
/// - `F` is the number-policy callback used for each number token.
/// - `E` is the error type returned by that callback.
pub(super) struct ValidatedValueConsumer<F, E> {
    /// Guarded builder for the value under construction.
    builder: LexicalJsonValueBuilder,
    /// Callback applied to each number before representation range checks.
    policy: F,
    /// Additional validated limits and number model.
    options: JsonValidatedDecodeOptions,
    /// Current callback path, maintained only when `track_path` is enabled.
    path: Vec<JsonPathSegment>,
    /// Whether to build callback paths; does not affect value or limit state.
    track_path: bool,
    /// Unclosed containers; array indices advance after each complete value.
    containers: Vec<ValidatedContainer>,
    /// Count of both values and object keys seen so far.
    nodes: usize,
    /// Policy consumed by the next matching number event; exact mode resets to
    /// preserve.
    next_number_policy: JsonNumberPolicy,
    /// Associates the policy error type with this consumer.
    marker: std::marker::PhantomData<E>,
}

impl<F, E> ValidatedValueConsumer<F, E> {
    /// Creates a consumer with the engine's validated decode configuration.
    ///
    /// # Parameters
    ///
    /// - `options` supplies validated limits and decoding options.
    /// - `policy` selects how number tokens are handled.
    /// - `model` selects the JSON number representation model.
    /// - `track_path` controls whether callback paths are maintained.
    ///
    /// # Returns
    ///
    /// A consumer initialized with an empty traversal stack and
    /// preserve-number policy.
    pub(super) fn new(
        options: JsonValidatedDecodeOptions,
        policy: F,
        model: JsonNumberModel,
        track_path: bool,
    ) -> Self {
        Self {
            builder: LexicalJsonValueBuilder::new(model),
            policy,
            options,
            path: Vec::new(),
            track_path,
            containers: Vec::new(),
            nodes: 0,
            next_number_policy: JsonNumberPolicy::Preserve,
            marker: std::marker::PhantomData,
        }
    }

    /// Finishes guarded materialization and returns the completed safe value.
    ///
    /// The engine remains responsible for committing or rolling back its
    /// surrounding transaction.
    ///
    /// # Returns
    ///
    /// The safely materialized JSON value, or the builder's materialization
    /// error.
    ///
    /// # Errors
    ///
    /// Returns the materialization error when guarded value construction fails.
    pub(super) fn finish(self) -> Result<SafeJsonValue, JsonValueMaterializationError> {
        self.builder.finish_guarded()
    }

    /// Completes one scalar or container and advances/pops its parent path
    /// state.
    fn complete_value(&mut self) {
        if !self.track_path {
            return;
        }
        if let Some(parent) = self.containers.last_mut() {
            match parent {
                ValidatedContainer::Array { next_index } => {
                    self.path.pop();
                    *next_index = next_index.saturating_add(1);
                }
                ValidatedContainer::Object => {
                    self.path.pop();
                }
            }
        }
    }
}

impl<'input, F, E> JsonLexicalConsumer<'input> for ValidatedValueConsumer<F, E>
where
    F: for<'call> FnMut(&'call [JsonPathSegment], JsonNumberToken<'call>) -> Result<JsonNumberPolicy, E>,
{
    /// Internal failure category mapped by the decode engine to its public
    /// error.
    type Error = ValidatedConsumerError<E>;

    /// Counts a value and prepares its array path before consuming its event.
    ///
    /// # Parameters
    ///
    /// - `_depth` is the scanner depth; this consumer relies on its own
    ///   container stack.
    /// - `offset` is the source byte offset used when reporting a limit
    ///   violation.
    ///
    /// # Errors
    ///
    /// Returns a limit error when the value-and-key node count exceeds its
    /// maximum.
    fn before_value(&mut self, _depth: usize, offset: usize) -> Result<(), Self::Error> {
        if self.track_path
            && let Some(ValidatedContainer::Array { next_index }) = self.containers.last()
        {
            self.path.push(JsonPathSegment::Index(*next_index));
        }
        self.nodes = self.nodes.saturating_add(1);
        if let Some(maximum) = self.options.max_value_and_key_nodes()
            && self.nodes > maximum
        {
            return Err(ValidatedConsumerError::Limit {
                limit: JsonValidatedLimit::ValueAndKeyNodes,
                maximum,
                observed: self.nodes,
                offset,
            });
        }
        debug_assert!(self.track_path || (self.path.is_empty() && self.containers.is_empty()));
        Ok(())
    }

    /// Counts an object key toward the shared value-and-key node limit.
    ///
    /// # Parameters
    ///
    /// - `offset` is the source byte offset used when reporting a limit
    ///   violation.
    ///
    /// # Errors
    ///
    /// Returns a limit error when the value-and-key node count exceeds its
    /// maximum.
    fn before_key(&mut self, offset: usize) -> Result<(), Self::Error> {
        self.nodes = self.nodes.saturating_add(1);
        if let Some(maximum) = self.options.max_value_and_key_nodes()
            && self.nodes > maximum
        {
            return Err(ValidatedConsumerError::Limit {
                limit: JsonValidatedLimit::ValueAndKeyNodes,
                maximum,
                observed: self.nodes,
                offset,
            });
        }
        debug_assert!(self.track_path || (self.path.is_empty() && self.containers.is_empty()));
        Ok(())
    }

    /// Runs policy before the following number event performs representation
    /// checks.
    ///
    /// # Parameters
    ///
    /// - `token` is the validated source text of the number.
    /// - `offset` is the token's source byte offset.
    ///
    /// # Errors
    ///
    /// Returns the policy callback's error when it rejects the number token.
    fn before_number(&mut self, token: &'input str, offset: usize) -> Result<(), Self::Error> {
        self.next_number_policy = (self.policy)(&self.path, JsonNumberToken::from_validated(token, offset))
            .map_err(|source| ValidatedConsumerError::Policy { source, offset })?;
        debug_assert!(self.track_path || (self.path.is_empty() && self.containers.is_empty()));
        Ok(())
    }

    /// Applies one scanner event, completing path state only after its whole
    /// value.
    ///
    /// # Parameters
    ///
    /// - `event` is the next validated lexical event emitted by the scanner.
    ///
    /// # Errors
    ///
    /// Returns a policy, representation, limit, or materialization error when
    /// the event cannot be accepted under the configured decode rules.
    fn event(&mut self, event: JsonLexicalEvent<'input>) -> Result<(), Self::Error> {
        match event {
            JsonLexicalEvent::Number { token, offset }
                if self.next_number_policy == JsonNumberPolicy::ExactSafeInteger =>
            {
                let text = std::str::from_utf8(token).expect("scanner number token is UTF-8");
                let value = JsonNumberToken::from_validated(text, offset)
                    .exact_safe_integer()
                    .map_err(|source| ValidatedConsumerError::Exact { source, offset })?;
                self.builder.try_accept_number(value.into(), offset).map_err(|source| {
                    ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::Number,
                    }
                })?;
                self.next_number_policy = JsonNumberPolicy::Preserve;
                self.complete_value();
            }
            JsonLexicalEvent::Key { token, offset } => {
                let key = from_slice::<String>(token).expect("scanner admitted valid key token");
                let path_key = self.track_path.then(|| key.clone());
                self.builder.try_accept_decoded_key(key, offset).map_err(|source| {
                    ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::ObjectKey,
                    }
                })?;
                if let Some(key) = path_key {
                    self.path.push(JsonPathSegment::Key(key));
                }
            }
            JsonLexicalEvent::String { token, offset } => {
                self.builder
                    .try_accept(JsonLexicalEvent::String { token, offset })
                    .map_err(|source| ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::String,
                    })?;
                self.complete_value();
            }
            JsonLexicalEvent::BeginArray { .. } => {
                self.builder
                    .try_accept(event)
                    .map_err(|source| ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::Value,
                    })?;
                if self.track_path {
                    self.containers.push(ValidatedContainer::Array { next_index: 0 });
                }
            }
            JsonLexicalEvent::BeginObject { .. } => {
                self.builder
                    .try_accept(event)
                    .map_err(|source| ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::Value,
                    })?;
                if self.track_path {
                    self.containers.push(ValidatedContainer::Object);
                }
            }
            JsonLexicalEvent::EndArray { .. } | JsonLexicalEvent::EndObject { .. } => {
                self.builder
                    .try_accept(event)
                    .map_err(|source| ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::Value,
                    })?;
                if self.track_path {
                    self.containers.pop();
                }
                self.complete_value();
            }
            other => {
                self.builder
                    .try_accept(other)
                    .map_err(|source| ValidatedConsumerError::Materialization {
                        source,
                        context: JsonDecodeContext::Value,
                    })?;
                self.complete_value();
            }
        }
        debug_assert!(self.track_path || (self.path.is_empty() && self.containers.is_empty()));
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::ValidatedValueConsumer;
    use crate::decode::JsonNumberPolicy;
    use crate::decode::JsonNumberToken;
    use crate::decode::JsonPathSegment;
    use crate::decode::JsonValidatedDecodeOptions;
    use crate::lexical::JsonLexicalConsumer;
    use crate::lexical::JsonLexicalEvent;
    use crate::lexical::JsonNumberModel;

    #[test]
    fn test_no_path_mode_does_not_allocate_traversal_state() {
        let mut consumer = ValidatedValueConsumer::new(
            JsonValidatedDecodeOptions::builder().build(),
            |path: &[JsonPathSegment], _: JsonNumberToken<'_>| {
                assert!(path.is_empty());
                Ok::<JsonNumberPolicy, ()>(JsonNumberPolicy::Preserve)
            },
            JsonNumberModel::Integer64WithFiniteFallback,
            false,
        );
        macro_rules! assert_no_traversal_state {
            () => {{
                assert!(consumer.path.is_empty());
                assert_eq!(consumer.path.capacity(), 0);
                assert!(consumer.containers.is_empty());
                assert_eq!(consumer.containers.capacity(), 0);
            }};
        }
        macro_rules! before_value {
            ($offset:expr) => {{
                consumer.before_value(0, $offset).unwrap_or_else(|_| panic!());
                assert_no_traversal_state!();
            }};
        }
        macro_rules! before_number {
            ($token:expr, $offset:expr) => {{
                consumer
                    .before_number($token, $offset)
                    .unwrap_or_else(|_| panic!());
                assert_no_traversal_state!();
            }};
        }
        macro_rules! consume {
            ($event:expr) => {{
                consumer.event($event).unwrap_or_else(|_| panic!());
                assert_no_traversal_state!();
            }};
        }

        before_value!(0);
        consume!(JsonLexicalEvent::BeginArray { offset: 0 });
        before_value!(1);
        consume!(JsonLexicalEvent::BeginObject { offset: 1 });
        consumer.before_key(2).unwrap_or_else(|_| panic!());
        assert_no_traversal_state!();
        consume!(JsonLexicalEvent::Key {
            token: br#""a""#,
            offset: 2
        });
        before_value!(3);
        consume!(JsonLexicalEvent::BeginArray { offset: 3 });
        before_value!(4);
        before_number!("1", 4);
        consume!(JsonLexicalEvent::Number { token: b"1", offset: 4 });
        before_value!(5);
        consume!(JsonLexicalEvent::BeginObject { offset: 5 });
        consumer.before_key(6).unwrap_or_else(|_| panic!());
        assert_no_traversal_state!();
        consume!(JsonLexicalEvent::Key {
            token: br#""b""#,
            offset: 6
        });
        before_value!(7);
        consume!(JsonLexicalEvent::Boolean { value: true, offset: 7 });
        consume!(JsonLexicalEvent::EndObject { offset: 8 });
        consume!(JsonLexicalEvent::EndArray { offset: 9 });
        consume!(JsonLexicalEvent::EndObject { offset: 10 });
        before_value!(11);
        consume!(JsonLexicalEvent::String {
            token: br#""x""#,
            offset: 11
        });
        consume!(JsonLexicalEvent::EndArray { offset: 12 });

        assert_eq!(consumer.nodes, 9);
        let value = consumer.finish().unwrap_or_else(|_| panic!());
        assert_eq!(value.as_value(), &serde_json::json!([{"a": [1, {"b": true}]}, "x"]));
    }
}