• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kaidokert / picojson-rs / 16297821328

15 Jul 2025 03:38PM UTC coverage: 93.249% (-0.6%) from 93.865%
16297821328

Pull #59

github

web-flow
Merge 583198908 into 1dbca311e
Pull Request #59: Big refactor

471 of 544 new or added lines in 8 files covered. (86.58%)

14 existing lines in 4 files now uncovered.

4738 of 5081 relevant lines covered (93.25%)

728.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.38
/picojson/src/event_processor.rs
1
// SPDX-License-Identifier: Apache-2.0
2

3
//! Shared event processing logic between SliceParser and StreamParser.
4
//!
5
//! This module extracts the common event handling patterns to reduce code duplication
6
//! while preserving the performance characteristics of each parser type.
7

8
use crate::shared::{ContentRange, State};
9
use crate::ujson::EventToken;
10
use crate::{Event, ParseError};
11

12
/// Escape handling trait for abstracting escape sequence processing between parsers
13
pub trait EscapeHandler {
14
    /// Get the current parser state for escape context checking
15
    fn parser_state(&self) -> &crate::shared::State;
16

17
    /// Process Unicode escape sequence using shared collector logic
18
    fn process_unicode_escape_with_collector(&mut self) -> Result<(), crate::ParseError>;
19

20
    /// Handle a simple escape character (after EscapeProcessor conversion)
21
    fn handle_simple_escape_char(&mut self, escape_char: u8) -> Result<(), crate::ParseError>;
22

23
    /// Begin escape sequence processing (lifecycle method with default no-op implementation)
24
    /// Called when escape sequence processing begins (e.g., on Begin(EscapeSequence))
25
    fn begin_escape_sequence(&mut self) -> Result<(), crate::ParseError>;
26

27
    /// Begin unicode escape sequence processing
28
    fn begin_unicode_escape(&mut self) -> Result<(), crate::ParseError>;
29
}
30

31
/// Result of processing a tokenizer event
32
#[derive(Debug)]
33
pub enum EventResult<'a, 'b> {
34
    /// Event processing is complete, return this event to the user
35
    Complete(Event<'a, 'b>),
36
    /// Continue processing more tokenizer events
37
    Continue,
38
    /// Extract string content (delegate to parser-specific logic)
39
    ExtractString,
40
    /// Extract key content (delegate to parser-specific logic)
41
    ExtractKey,
42
    /// Extract number content (delegate to parser-specific logic)
43
    /// bool indicates if number was terminated by container delimiter
44
    ExtractNumber(bool),
45
}
46

47
/// Process Begin events that have similar patterns between parsers
48
pub fn process_begin_events<C: ContentExtractor>(
4,366✔
49
    event: &crate::ujson::Event,
4,366✔
50
    content_extractor: &mut C,
4,366✔
51
) -> Option<EventResult<'static, 'static>> {
4,366✔
52
    match event {
3,479✔
53
        // String/Key Begin events - nearly identical patterns
54
        crate::ujson::Event::Begin(EventToken::Key) => {
55
            let pos = content_extractor.current_position();
356✔
56
            *content_extractor.parser_state_mut() = State::Key(pos);
356✔
57
            content_extractor.begin_string_content(pos);
356✔
58
            Some(EventResult::Continue)
356✔
59
        }
60
        crate::ujson::Event::Begin(EventToken::String) => {
61
            let pos = content_extractor.current_position();
768✔
62
            *content_extractor.parser_state_mut() = State::String(pos);
768✔
63
            content_extractor.begin_string_content(pos);
768✔
64
            Some(EventResult::Continue)
768✔
65
        }
66

67
        // Number Begin events - identical logic
68
        crate::ujson::Event::Begin(
69
            EventToken::Number | EventToken::NumberAndArray | EventToken::NumberAndObject,
70
        ) => {
71
            let pos = content_extractor.current_position();
471✔
72
            let number_start = ContentRange::number_start_from_current(pos);
471✔
73
            *content_extractor.parser_state_mut() = State::Number(number_start);
471✔
74
            Some(EventResult::Continue)
471✔
75
        }
76

77
        // Primitive Begin events - identical logic
78
        crate::ujson::Event::Begin(EventToken::True | EventToken::False | EventToken::Null) => {
79
            Some(EventResult::Continue)
25✔
80
        }
81

82
        _ => None,
2,746✔
83
    }
84
}
4,366✔
85

86
/// Clear event storage array - utility function
87
pub fn clear_events(event_storage: &mut [Option<crate::ujson::Event>; 2]) {
20,949✔
88
    event_storage[0] = None;
20,949✔
89
    event_storage[1] = None;
20,949✔
90
}
20,949✔
91

92
/// Trait for content extraction operations that differ between parsers
93
/// Consolidates ParserContext and ContentExtractor functionality
94
pub trait ContentExtractor: EscapeHandler {
95
    /// Get current position in the input
96
    fn current_position(&self) -> usize;
97

98
    /// Begin string/key content processing at current position
99
    fn begin_string_content(&mut self, pos: usize);
100

101
    /// Get mutable access to parser state
102
    fn parser_state_mut(&mut self) -> &mut crate::shared::State;
103

104
    /// Get mutable access to the Unicode escape collector
105
    /// This eliminates the need for wrapper methods that just forward calls
106
    fn unicode_escape_collector_mut(
107
        &mut self,
108
    ) -> &mut crate::escape_processor::UnicodeEscapeCollector;
109

110
    /// Extract string content using parser-specific logic
111
    fn extract_string_content(
112
        &mut self,
113
        start_pos: usize,
114
    ) -> Result<crate::Event<'_, '_>, crate::ParseError>;
115

116
    /// Extract key content using parser-specific logic
117
    fn extract_key_content(
118
        &mut self,
119
        start_pos: usize,
120
    ) -> Result<crate::Event<'_, '_>, crate::ParseError>;
121

122
    /// Extract number content using parser-specific logic
123
    fn extract_number_content(
124
        &mut self,
125
        start_pos: usize,
126
        from_container_end: bool,
127
    ) -> Result<crate::Event<'_, '_>, crate::ParseError>;
128

129
    /// Extract a completed number using shared number parsing logic
130
    ///
131
    /// # Arguments
132
    /// * `start_pos` - Position where the number started
133
    /// * `from_container_end` - True if number was terminated by container delimiter
134
    /// * `finished` - True if the parser has finished processing input (StreamParser-specific)
135
    fn extract_number(
136
        &mut self,
137
        start_pos: usize,
138
        from_container_end: bool,
139
        finished: bool,
140
    ) -> Result<crate::Event<'_, '_>, crate::ParseError>;
141

142
    /// Shared validation and extraction for string content
143
    fn validate_and_extract_string(&mut self) -> Result<crate::Event<'_, '_>, crate::ParseError> {
431✔
144
        let start_pos = match *self.parser_state() {
431✔
145
            crate::shared::State::String(pos) => pos,
431✔
146
            _ => return Err(crate::shared::UnexpectedState::StateMismatch.into()),
×
147
        };
148

149
        // Check for incomplete surrogate pairs before ending the string
150
        if self
431✔
151
            .unicode_escape_collector_mut()
431✔
152
            .has_pending_high_surrogate()
431✔
153
        {
154
            return Err(crate::ParseError::InvalidUnicodeCodepoint);
3✔
155
        }
428✔
156

157
        *self.parser_state_mut() = crate::shared::State::None;
428✔
158
        self.extract_string_content(start_pos)
428✔
159
    }
431✔
160

161
    /// Shared validation and extraction for key content
162
    fn validate_and_extract_key(&mut self) -> Result<crate::Event<'_, '_>, crate::ParseError> {
325✔
163
        let start_pos = match *self.parser_state() {
325✔
164
            crate::shared::State::Key(pos) => pos,
325✔
165
            _ => return Err(crate::shared::UnexpectedState::StateMismatch.into()),
×
166
        };
167

168
        // Check for incomplete surrogate pairs before ending the key
169
        if self
325✔
170
            .unicode_escape_collector_mut()
325✔
171
            .has_pending_high_surrogate()
325✔
172
        {
173
            return Err(crate::ParseError::InvalidUnicodeCodepoint);
×
174
        }
325✔
175

176
        *self.parser_state_mut() = crate::shared::State::None;
325✔
177
        self.extract_key_content(start_pos)
325✔
178
    }
325✔
179

180
    /// Shared validation and extraction for number content
181
    fn validate_and_extract_number(
27✔
182
        &mut self,
27✔
183
        from_container_end: bool,
27✔
184
    ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
27✔
185
        let start_pos = match *self.parser_state() {
27✔
186
            crate::shared::State::Number(pos) => pos,
27✔
187
            _ => return Err(crate::shared::UnexpectedState::StateMismatch.into()),
×
188
        };
189

190
        *self.parser_state_mut() = crate::shared::State::None;
27✔
191
        self.extract_number_content(start_pos, from_container_end)
27✔
192
    }
27✔
193
}
194

195
/// Creates a standard tokenizer callback for event storage
196
///
197
/// This callback stores tokenizer events in the parser's event array, filling the first
198
/// available slot. This pattern is identical across both SliceParser and StreamParser.
199
pub fn create_tokenizer_callback(
20,952✔
200
    event_storage: &mut [Option<crate::ujson::Event>; 2],
20,952✔
201
) -> impl FnMut(crate::ujson::Event, usize) + '_ {
20,952✔
202
    |event, _len| {
8,559✔
203
        for evt in event_storage.iter_mut() {
9,471✔
204
            if evt.is_none() {
9,471✔
205
                *evt = Some(event);
8,558✔
206
                return;
8,558✔
207
            }
913✔
208
        }
209
    }
8,559✔
210
}
20,952✔
211

212
/// Shared utility to check if any events are waiting to be processed
213
pub fn have_events(event_storage: &[Option<crate::ujson::Event>; 2]) -> bool {
50,967✔
214
    event_storage.iter().any(|evt| evt.is_some())
86,641✔
215
}
50,967✔
216

217
/// Shared utility to extract the first available event from storage
218
pub fn take_first_event(
8,549✔
219
    event_storage: &mut [Option<crate::ujson::Event>; 2],
8,549✔
220
) -> Option<crate::ujson::Event> {
8,549✔
221
    event_storage.iter_mut().find_map(|e| e.take())
9,451✔
222
}
8,549✔
223

224
/// Process Begin(EscapeSequence) events using the enhanced lifecycle interface
225
pub fn process_begin_escape_sequence_event<H: EscapeHandler>(
951✔
226
    handler: &mut H,
951✔
227
) -> Result<(), crate::ParseError> {
951✔
228
    // Only process if we're inside a string or key
229
    match handler.parser_state() {
951✔
230
        crate::shared::State::String(_) | crate::shared::State::Key(_) => {
231
            handler.begin_escape_sequence()?;
951✔
232
        }
233
        _ => {} // Ignore if not in string/key context
×
234
    }
235
    Ok(())
951✔
236
}
951✔
237

238
/// Process simple escape sequence events that have similar patterns between parsers
239
pub fn process_simple_escape_event<C: ContentExtractor>(
688✔
240
    escape_token: &EventToken,
688✔
241
    content_extractor: &mut C,
688✔
242
) -> Result<(), crate::ParseError> {
688✔
243
    // Clear any pending high surrogate state when we encounter a simple escape
244
    // This ensures that interrupted surrogate pairs (like \uD801\n\uDC37) are properly rejected
245
    content_extractor.unicode_escape_collector_mut().reset_all();
688✔
246

247
    // Use unified escape token processing from EscapeProcessor
248
    let unescaped_char =
688✔
249
        crate::escape_processor::EscapeProcessor::process_escape_token(escape_token)?;
688✔
250

251
    // Only process if we're inside a string or key
252
    match content_extractor.parser_state() {
688✔
253
        crate::shared::State::String(_) | crate::shared::State::Key(_) => {
254
            content_extractor.handle_simple_escape_char(unescaped_char)?;
688✔
255
        }
256
        _ => {} // Ignore if not in string/key context
×
257
    }
258

259
    Ok(())
686✔
260
}
688✔
261

262
/// Process Unicode escape begin/end events that have similar patterns between parsers
263
pub fn process_unicode_escape_events<C: ContentExtractor>(
1,794✔
264
    event: &crate::ujson::Event,
1,794✔
265
    content_extractor: &mut C,
1,794✔
266
) -> Result<bool, crate::ParseError> {
1,794✔
267
    match event {
907✔
268
        crate::ujson::Event::Begin(EventToken::UnicodeEscape) => {
269
            // Start Unicode escape collection - reset collector for new sequence
270
            // Only handle if we're inside a string or key
271
            match content_extractor.parser_state() {
219✔
272
                crate::shared::State::String(_) | crate::shared::State::Key(_) => {
273
                    content_extractor.unicode_escape_collector_mut().reset();
219✔
274
                    content_extractor.begin_unicode_escape()?;
219✔
275
                }
276
                _ => {} // Ignore if not in string/key context
×
277
            }
278
            Ok(true) // Event was handled
219✔
279
        }
280
        crate::ujson::Event::End(EventToken::UnicodeEscape) => {
281
            // Handle end of Unicode escape sequence (\uXXXX)
282
            match content_extractor.parser_state() {
201✔
283
                crate::shared::State::String(_) | crate::shared::State::Key(_) => {
284
                    content_extractor.process_unicode_escape_with_collector()?;
201✔
285
                }
286
                _ => {} // Ignore if not in string/key context
×
287
            }
288
            Ok(true) // Event was handled
177✔
289
        }
290
        _ => Ok(false), // Event was not handled
1,374✔
291
    }
292
}
1,794✔
293

294
/// Process simple container and primitive events that are identical between parsers
295
pub fn process_simple_events(event: &crate::ujson::Event) -> Option<EventResult<'static, 'static>> {
8,555✔
296
    match event {
1,947✔
297
        // Container events - identical processing
298
        crate::ujson::Event::ObjectStart => Some(EventResult::Complete(Event::StartObject)),
251✔
299
        crate::ujson::Event::ObjectEnd => Some(EventResult::Complete(Event::EndObject)),
206✔
300
        crate::ujson::Event::ArrayStart => Some(EventResult::Complete(Event::StartArray)),
1,670✔
301
        crate::ujson::Event::ArrayEnd => Some(EventResult::Complete(Event::EndArray)),
1,007✔
302

303
        // Primitive values - identical processing
304
        crate::ujson::Event::End(EventToken::True) => {
305
            Some(EventResult::Complete(Event::Bool(true)))
11✔
306
        }
307
        crate::ujson::Event::End(EventToken::False) => {
308
            Some(EventResult::Complete(Event::Bool(false)))
6✔
309
        }
310
        crate::ujson::Event::End(EventToken::Null) => Some(EventResult::Complete(Event::Null)),
7✔
311

312
        // Content extraction triggers - identical logic
313
        crate::ujson::Event::End(EventToken::String) => Some(EventResult::ExtractString),
432✔
314
        crate::ujson::Event::End(EventToken::Key) => Some(EventResult::ExtractKey),
325✔
315
        crate::ujson::Event::End(EventToken::Number) => Some(EventResult::ExtractNumber(false)),
56✔
316
        crate::ujson::Event::End(EventToken::NumberAndArray) => {
317
            Some(EventResult::ExtractNumber(true))
140✔
318
        }
319
        crate::ujson::Event::End(EventToken::NumberAndObject) => {
320
            Some(EventResult::ExtractNumber(true))
83✔
321
        }
322

323
        // All other events need parser-specific handling
324
        _ => None,
4,361✔
325
    }
326
}
8,555✔
327

328
/// Process a specific byte through the tokenizer (for cases where byte is already available)
329
pub fn process_byte_through_tokenizer<T: crate::ujson::BitBucket, C: crate::ujson::DepthCounter>(
20,427✔
330
    byte: u8,
20,427✔
331
    tokenizer: &mut crate::ujson::Tokenizer<T, C>,
20,427✔
332
    event_storage: &mut [Option<crate::ujson::Event>; 2],
20,427✔
333
) -> Result<(), ParseError> {
20,427✔
334
    clear_events(event_storage);
20,427✔
335
    let mut callback = create_tokenizer_callback(event_storage);
20,427✔
336
    tokenizer
20,427✔
337
        .parse_chunk(&[byte], &mut callback)
20,427✔
338
        .map_err(ParseError::TokenizerError)?;
20,427✔
339
    Ok(())
20,422✔
340
}
20,427✔
341

342
/// Finish the tokenizer and collect any final events
343
pub fn finish_tokenizer<T: crate::ujson::BitBucket, C: crate::ujson::DepthCounter>(
522✔
344
    tokenizer: &mut crate::ujson::Tokenizer<T, C>,
522✔
345
    event_storage: &mut [Option<crate::ujson::Event>; 2],
522✔
346
) -> Result<(), ParseError> {
522✔
347
    clear_events(event_storage);
522✔
348
    let mut callback = create_tokenizer_callback(event_storage);
522✔
349
    tokenizer
522✔
350
        .finish(&mut callback)
522✔
351
        .map_err(ParseError::TokenizerError)?;
522✔
352
    Ok(())
518✔
353
}
522✔
354

355
#[cfg(test)]
356
mod tests {
357
    use super::*;
358

359
    #[test]
360
    fn test_container_events() {
1✔
361
        assert!(matches!(
1✔
362
            process_simple_events(&crate::ujson::Event::ObjectStart),
1✔
363
            Some(EventResult::Complete(Event::StartObject))
364
        ));
365

366
        assert!(matches!(
1✔
367
            process_simple_events(&crate::ujson::Event::ArrayEnd),
1✔
368
            Some(EventResult::Complete(Event::EndArray))
369
        ));
370
    }
1✔
371

372
    #[test]
373
    fn test_primitive_events() {
1✔
374
        assert!(matches!(
1✔
375
            process_simple_events(&crate::ujson::Event::End(EventToken::True)),
1✔
376
            Some(EventResult::Complete(Event::Bool(true)))
377
        ));
378

379
        assert!(matches!(
1✔
380
            process_simple_events(&crate::ujson::Event::End(EventToken::Null)),
1✔
381
            Some(EventResult::Complete(Event::Null))
382
        ));
383
    }
1✔
384

385
    #[test]
386
    fn test_extraction_triggers() {
1✔
387
        assert!(matches!(
1✔
388
            process_simple_events(&crate::ujson::Event::End(EventToken::String)),
1✔
389
            Some(EventResult::ExtractString)
390
        ));
391

392
        assert!(matches!(
1✔
393
            process_simple_events(&crate::ujson::Event::End(EventToken::Number)),
1✔
394
            Some(EventResult::ExtractNumber(false))
395
        ));
396

397
        assert!(matches!(
1✔
398
            process_simple_events(&crate::ujson::Event::End(EventToken::NumberAndArray)),
1✔
399
            Some(EventResult::ExtractNumber(true))
400
        ));
401
    }
1✔
402

403
    #[test]
404
    fn test_complex_events_not_handled() {
1✔
405
        assert!(process_simple_events(&crate::ujson::Event::Begin(EventToken::String)).is_none());
1✔
406
        assert!(
1✔
407
            process_simple_events(&crate::ujson::Event::Begin(EventToken::EscapeQuote)).is_none()
1✔
408
        );
409
    }
1✔
410

411
    // Mock ContentExtractor for testing
412
    struct MockContentExtractor {
413
        position: usize,
414
        state: crate::shared::State,
415
        string_begin_calls: Vec<usize>,
416
    }
417

418
    impl MockContentExtractor {
419
        fn new() -> Self {
5✔
420
            Self {
5✔
421
                position: 42,
5✔
422
                state: crate::shared::State::None,
5✔
423
                string_begin_calls: Vec::new(),
5✔
424
            }
5✔
425
        }
5✔
426
    }
427

428
    impl EscapeHandler for MockContentExtractor {
429
        fn parser_state(&self) -> &crate::shared::State {
×
430
            &self.state
×
431
        }
×
432

433
        fn process_unicode_escape_with_collector(&mut self) -> Result<(), crate::ParseError> {
×
434
            Ok(())
×
435
        }
×
436

437
        fn handle_simple_escape_char(&mut self, _escape_char: u8) -> Result<(), crate::ParseError> {
×
438
            Ok(())
×
439
        }
×
440

NEW
441
        fn begin_unicode_escape(&mut self) -> Result<(), crate::ParseError> {
×
NEW
442
            Ok(())
×
NEW
443
        }
×
444

NEW
445
        fn begin_escape_sequence(&mut self) -> Result<(), crate::ParseError> {
×
NEW
446
            Ok(())
×
NEW
447
        }
×
448
    }
449

450
    impl ContentExtractor for MockContentExtractor {
451
        fn current_position(&self) -> usize {
3✔
452
            self.position
3✔
453
        }
3✔
454

455
        fn begin_string_content(&mut self, pos: usize) {
2✔
456
            self.string_begin_calls.push(pos);
2✔
457
        }
2✔
458

459
        fn parser_state_mut(&mut self) -> &mut crate::shared::State {
3✔
460
            &mut self.state
3✔
461
        }
3✔
462

463
        fn unicode_escape_collector_mut(
×
464
            &mut self,
×
465
        ) -> &mut crate::escape_processor::UnicodeEscapeCollector {
×
466
            unimplemented!("Mock doesn't need unicode collector")
×
467
        }
468

469
        fn extract_string_content(
×
470
            &mut self,
×
471
            _start_pos: usize,
×
472
        ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
×
473
            unimplemented!("Mock doesn't need extraction")
×
474
        }
475

476
        fn extract_key_content(
×
477
            &mut self,
×
478
            _start_pos: usize,
×
479
        ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
×
480
            unimplemented!("Mock doesn't need extraction")
×
481
        }
482

483
        fn extract_number_content(
×
484
            &mut self,
×
485
            _start_pos: usize,
×
486
            _from_container_end: bool,
×
487
        ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
×
488
            unimplemented!("Mock doesn't need extraction")
×
489
        }
490

NEW
491
        fn extract_number(
×
NEW
492
            &mut self,
×
NEW
493
            _start_pos: usize,
×
NEW
494
            _from_container_end: bool,
×
NEW
495
            _finished: bool,
×
NEW
496
        ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
×
NEW
497
            unimplemented!("Mock doesn't need extraction")
×
498
        }
499
    }
500

501
    #[test]
502
    fn test_begin_events_key() {
1✔
503
        let mut context = MockContentExtractor::new();
1✔
504
        let event = crate::ujson::Event::Begin(EventToken::Key);
1✔
505

506
        let result = process_begin_events(&event, &mut context);
1✔
507

508
        assert!(matches!(result, Some(EventResult::Continue)));
1✔
509
        assert!(matches!(context.state, crate::shared::State::Key(42)));
1✔
510
        assert_eq!(context.string_begin_calls, vec![42]);
1✔
511
    }
1✔
512

513
    #[test]
514
    fn test_begin_events_string() {
1✔
515
        let mut context = MockContentExtractor::new();
1✔
516
        let event = crate::ujson::Event::Begin(EventToken::String);
1✔
517

518
        let result = process_begin_events(&event, &mut context);
1✔
519

520
        assert!(matches!(result, Some(EventResult::Continue)));
1✔
521
        assert!(matches!(context.state, crate::shared::State::String(42)));
1✔
522
        assert_eq!(context.string_begin_calls, vec![42]);
1✔
523
    }
1✔
524

525
    #[test]
526
    fn test_begin_events_number() {
1✔
527
        let mut context = MockContentExtractor::new();
1✔
528
        let event = crate::ujson::Event::Begin(EventToken::Number);
1✔
529

530
        let result = process_begin_events(&event, &mut context);
1✔
531

532
        assert!(matches!(result, Some(EventResult::Continue)));
1✔
533
        // Number should get position adjusted by ContentRange::number_start_from_current
534
        assert!(matches!(context.state, crate::shared::State::Number(_)));
1✔
535
        assert_eq!(context.string_begin_calls, Vec::<usize>::new()); // No string calls for numbers
1✔
536
    }
1✔
537

538
    #[test]
539
    fn test_begin_events_primitives() {
1✔
540
        let mut context = MockContentExtractor::new();
1✔
541

542
        for token in [EventToken::True, EventToken::False, EventToken::Null] {
3✔
543
            let event = crate::ujson::Event::Begin(token);
3✔
544
            let result = process_begin_events(&event, &mut context);
3✔
545
            assert!(matches!(result, Some(EventResult::Continue)));
3✔
546
        }
547

548
        // Should not affect state or string processing
549
        assert!(matches!(context.state, crate::shared::State::None));
1✔
550
        assert!(context.string_begin_calls.is_empty());
1✔
551
    }
1✔
552

553
    #[test]
554
    fn test_begin_events_not_handled() {
1✔
555
        let mut context = MockContentExtractor::new();
1✔
556
        let event = crate::ujson::Event::Begin(EventToken::EscapeQuote);
1✔
557

558
        let result = process_begin_events(&event, &mut context);
1✔
559

560
        assert!(result.is_none());
1✔
561
        assert!(matches!(context.state, crate::shared::State::None));
1✔
562
        assert!(context.string_begin_calls.is_empty());
1✔
563
    }
1✔
564

565
    #[test]
566
    fn test_tokenizer_callback() {
1✔
567
        let mut event_storage = [None, None];
1✔
568

569
        // Initially no events
570
        assert!(!have_events(&event_storage));
1✔
571

572
        {
1✔
573
            let mut callback = create_tokenizer_callback(&mut event_storage);
1✔
574

1✔
575
            // Add first event
1✔
576
            callback(crate::ujson::Event::ObjectStart, 1);
1✔
577
        }
1✔
578
        assert!(have_events(&event_storage));
1✔
579
        assert!(event_storage[0].is_some());
1✔
580
        assert!(event_storage[1].is_none());
1✔
581

582
        {
1✔
583
            let mut callback = create_tokenizer_callback(&mut event_storage);
1✔
584
            // Add second event
1✔
585
            callback(crate::ujson::Event::ArrayStart, 1);
1✔
586
        }
1✔
587
        assert!(event_storage[0].is_some());
1✔
588
        assert!(event_storage[1].is_some());
1✔
589

590
        {
1✔
591
            let mut callback = create_tokenizer_callback(&mut event_storage);
1✔
592
            // Storage is full, third event should be ignored (no panic)
1✔
593
            callback(crate::ujson::Event::ObjectEnd, 1);
1✔
594
        }
1✔
595
        assert!(event_storage[0].is_some());
1✔
596
        assert!(event_storage[1].is_some());
1✔
597
    }
1✔
598

599
    #[test]
600
    fn test_event_extraction() {
1✔
601
        let mut event_storage = [
1✔
602
            Some(crate::ujson::Event::ObjectStart),
1✔
603
            Some(crate::ujson::Event::ArrayStart),
1✔
604
        ];
1✔
605

606
        // Extract first event
607
        let first = take_first_event(&mut event_storage);
1✔
608
        assert!(matches!(first, Some(crate::ujson::Event::ObjectStart)));
1✔
609
        assert!(event_storage[0].is_none());
1✔
610
        assert!(event_storage[1].is_some());
1✔
611

612
        // Extract second event
613
        let second = take_first_event(&mut event_storage);
1✔
614
        assert!(matches!(second, Some(crate::ujson::Event::ArrayStart)));
1✔
615
        assert!(event_storage[0].is_none());
1✔
616
        assert!(event_storage[1].is_none());
1✔
617

618
        // No more events
619
        let none = take_first_event(&mut event_storage);
1✔
620
        assert!(none.is_none());
1✔
621
        assert!(!have_events(&event_storage));
1✔
622
    }
1✔
623
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc