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

kaidokert / picojson-rs / 16308905452

16 Jul 2025 02:30AM UTC coverage: 93.976% (+0.1%) from 93.864%
16308905452

Pull #60

github

web-flow
Merge f9624e97e into d7962e604
Pull Request #60: Clean refactor

458 of 498 new or added lines in 8 files covered. (91.97%)

8 existing lines in 3 files now uncovered.

4727 of 5030 relevant lines covered (93.98%)

736.55 hits per line

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

85.99
/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 a completed number using shared number parsing logic
123
    ///
124
    /// # Arguments
125
    /// * `start_pos` - Position where the number started
126
    /// * `from_container_end` - True if number was terminated by container delimiter
127
    /// * `finished` - True if the parser has finished processing input (StreamParser-specific)
128
    fn extract_number(
129
        &mut self,
130
        start_pos: usize,
131
        from_container_end: bool,
132
        finished: bool,
133
    ) -> Result<crate::Event<'_, '_>, crate::ParseError>;
134

135
    /// Shared validation and extraction for string content
136
    fn validate_and_extract_string(&mut self) -> Result<crate::Event<'_, '_>, crate::ParseError> {
431✔
137
        let start_pos = match *self.parser_state() {
431✔
138
            crate::shared::State::String(pos) => pos,
431✔
139
            _ => return Err(crate::shared::UnexpectedState::StateMismatch.into()),
×
140
        };
141

142
        // Check for incomplete surrogate pairs before ending the string
143
        if self
431✔
144
            .unicode_escape_collector_mut()
431✔
145
            .has_pending_high_surrogate()
431✔
146
        {
147
            return Err(crate::ParseError::InvalidUnicodeCodepoint);
3✔
148
        }
428✔
149

150
        *self.parser_state_mut() = crate::shared::State::None;
428✔
151
        self.extract_string_content(start_pos)
428✔
152
    }
431✔
153

154
    /// Shared validation and extraction for key content
155
    fn validate_and_extract_key(&mut self) -> Result<crate::Event<'_, '_>, crate::ParseError> {
325✔
156
        let start_pos = match *self.parser_state() {
325✔
157
            crate::shared::State::Key(pos) => pos,
325✔
158
            _ => return Err(crate::shared::UnexpectedState::StateMismatch.into()),
×
159
        };
160

161
        // Check for incomplete surrogate pairs before ending the key
162
        if self
325✔
163
            .unicode_escape_collector_mut()
325✔
164
            .has_pending_high_surrogate()
325✔
165
        {
166
            return Err(crate::ParseError::InvalidUnicodeCodepoint);
×
167
        }
325✔
168

169
        *self.parser_state_mut() = crate::shared::State::None;
325✔
170
        self.extract_key_content(start_pos)
325✔
171
    }
325✔
172

173
    /// Shared validation and extraction for number content
174
    fn validate_and_extract_number(
27✔
175
        &mut self,
27✔
176
        from_container_end: bool,
27✔
177
    ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
27✔
178
        let start_pos = match *self.parser_state() {
27✔
179
            crate::shared::State::Number(pos) => pos,
27✔
180
            _ => return Err(crate::shared::UnexpectedState::StateMismatch.into()),
×
181
        };
182

183
        *self.parser_state_mut() = crate::shared::State::None;
27✔
184
        self.extract_number(start_pos, from_container_end, true)
27✔
185
    }
27✔
186
}
187

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

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

210
/// Shared utility to extract the first available event from storage
211
pub fn take_first_event(
8,549✔
212
    event_storage: &mut [Option<crate::ujson::Event>; 2],
8,549✔
213
) -> Option<crate::ujson::Event> {
8,549✔
214
    event_storage.iter_mut().find_map(|e| e.take())
9,451✔
215
}
8,549✔
216

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

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

240
    // Use unified escape token processing from EscapeProcessor
241
    let unescaped_char =
688✔
242
        crate::escape_processor::EscapeProcessor::process_escape_token(escape_token)?;
688✔
243

244
    // Only process if we're inside a string or key
245
    match content_extractor.parser_state() {
688✔
246
        crate::shared::State::String(_) | crate::shared::State::Key(_) => {
247
            content_extractor.handle_simple_escape_char(unescaped_char)?;
688✔
248
        }
249
        _ => {} // Ignore if not in string/key context
×
250
    }
251

252
    Ok(())
686✔
253
}
688✔
254

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

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

296
        // Primitive values - identical processing
297
        crate::ujson::Event::End(EventToken::True) => {
298
            Some(EventResult::Complete(Event::Bool(true)))
11✔
299
        }
300
        crate::ujson::Event::End(EventToken::False) => {
301
            Some(EventResult::Complete(Event::Bool(false)))
6✔
302
        }
303
        crate::ujson::Event::End(EventToken::Null) => Some(EventResult::Complete(Event::Null)),
7✔
304

305
        // Content extraction triggers - identical logic
306
        crate::ujson::Event::End(EventToken::String) => Some(EventResult::ExtractString),
432✔
307
        crate::ujson::Event::End(EventToken::Key) => Some(EventResult::ExtractKey),
325✔
308
        crate::ujson::Event::End(EventToken::Number) => Some(EventResult::ExtractNumber(false)),
56✔
309
        crate::ujson::Event::End(EventToken::NumberAndArray) => {
310
            Some(EventResult::ExtractNumber(true))
140✔
311
        }
312
        crate::ujson::Event::End(EventToken::NumberAndObject) => {
313
            Some(EventResult::ExtractNumber(true))
83✔
314
        }
315

316
        // All other events need parser-specific handling
317
        _ => None,
4,361✔
318
    }
319
}
8,555✔
320

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

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

348
#[cfg(test)]
349
mod tests {
350
    use super::*;
351

352
    #[test]
353
    fn test_container_events() {
1✔
354
        assert!(matches!(
1✔
355
            process_simple_events(&crate::ujson::Event::ObjectStart),
1✔
356
            Some(EventResult::Complete(Event::StartObject))
357
        ));
358

359
        assert!(matches!(
1✔
360
            process_simple_events(&crate::ujson::Event::ArrayEnd),
1✔
361
            Some(EventResult::Complete(Event::EndArray))
362
        ));
363
    }
1✔
364

365
    #[test]
366
    fn test_primitive_events() {
1✔
367
        assert!(matches!(
1✔
368
            process_simple_events(&crate::ujson::Event::End(EventToken::True)),
1✔
369
            Some(EventResult::Complete(Event::Bool(true)))
370
        ));
371

372
        assert!(matches!(
1✔
373
            process_simple_events(&crate::ujson::Event::End(EventToken::Null)),
1✔
374
            Some(EventResult::Complete(Event::Null))
375
        ));
376
    }
1✔
377

378
    #[test]
379
    fn test_extraction_triggers() {
1✔
380
        assert!(matches!(
1✔
381
            process_simple_events(&crate::ujson::Event::End(EventToken::String)),
1✔
382
            Some(EventResult::ExtractString)
383
        ));
384

385
        assert!(matches!(
1✔
386
            process_simple_events(&crate::ujson::Event::End(EventToken::Number)),
1✔
387
            Some(EventResult::ExtractNumber(false))
388
        ));
389

390
        assert!(matches!(
1✔
391
            process_simple_events(&crate::ujson::Event::End(EventToken::NumberAndArray)),
1✔
392
            Some(EventResult::ExtractNumber(true))
393
        ));
394
    }
1✔
395

396
    #[test]
397
    fn test_complex_events_not_handled() {
1✔
398
        assert!(process_simple_events(&crate::ujson::Event::Begin(EventToken::String)).is_none());
1✔
399
        assert!(
1✔
400
            process_simple_events(&crate::ujson::Event::Begin(EventToken::EscapeQuote)).is_none()
1✔
401
        );
402
    }
1✔
403

404
    // Mock ContentExtractor for testing
405
    struct MockContentExtractor {
406
        position: usize,
407
        state: crate::shared::State,
408
        string_begin_calls: Vec<usize>,
409
    }
410

411
    impl MockContentExtractor {
412
        fn new() -> Self {
5✔
413
            Self {
5✔
414
                position: 42,
5✔
415
                state: crate::shared::State::None,
5✔
416
                string_begin_calls: Vec::new(),
5✔
417
            }
5✔
418
        }
5✔
419
    }
420

421
    impl EscapeHandler for MockContentExtractor {
422
        fn parser_state(&self) -> &crate::shared::State {
×
423
            &self.state
×
424
        }
×
425

426
        fn process_unicode_escape_with_collector(&mut self) -> Result<(), crate::ParseError> {
×
427
            Ok(())
×
428
        }
×
429

430
        fn handle_simple_escape_char(&mut self, _escape_char: u8) -> Result<(), crate::ParseError> {
×
431
            Ok(())
×
432
        }
×
433

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

NEW
438
        fn begin_escape_sequence(&mut self) -> Result<(), crate::ParseError> {
×
NEW
439
            Ok(())
×
NEW
440
        }
×
441
    }
442

443
    impl ContentExtractor for MockContentExtractor {
444
        fn current_position(&self) -> usize {
3✔
445
            self.position
3✔
446
        }
3✔
447

448
        fn begin_string_content(&mut self, pos: usize) {
2✔
449
            self.string_begin_calls.push(pos);
2✔
450
        }
2✔
451

452
        fn parser_state_mut(&mut self) -> &mut crate::shared::State {
3✔
453
            &mut self.state
3✔
454
        }
3✔
455

456
        fn unicode_escape_collector_mut(
×
457
            &mut self,
×
458
        ) -> &mut crate::escape_processor::UnicodeEscapeCollector {
×
459
            unimplemented!("Mock doesn't need unicode collector")
×
460
        }
461

462
        fn extract_string_content(
×
463
            &mut self,
×
464
            _start_pos: usize,
×
465
        ) -> Result<crate::Event<'_, '_>, crate::ParseError> {
×
466
            unimplemented!("Mock doesn't need extraction")
×
467
        }
468

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

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

486
    #[test]
487
    fn test_begin_events_key() {
1✔
488
        let mut context = MockContentExtractor::new();
1✔
489
        let event = crate::ujson::Event::Begin(EventToken::Key);
1✔
490

491
        let result = process_begin_events(&event, &mut context);
1✔
492

493
        assert!(matches!(result, Some(EventResult::Continue)));
1✔
494
        assert!(matches!(context.state, crate::shared::State::Key(42)));
1✔
495
        assert_eq!(context.string_begin_calls, vec![42]);
1✔
496
    }
1✔
497

498
    #[test]
499
    fn test_begin_events_string() {
1✔
500
        let mut context = MockContentExtractor::new();
1✔
501
        let event = crate::ujson::Event::Begin(EventToken::String);
1✔
502

503
        let result = process_begin_events(&event, &mut context);
1✔
504

505
        assert!(matches!(result, Some(EventResult::Continue)));
1✔
506
        assert!(matches!(context.state, crate::shared::State::String(42)));
1✔
507
        assert_eq!(context.string_begin_calls, vec![42]);
1✔
508
    }
1✔
509

510
    #[test]
511
    fn test_begin_events_number() {
1✔
512
        let mut context = MockContentExtractor::new();
1✔
513
        let event = crate::ujson::Event::Begin(EventToken::Number);
1✔
514

515
        let result = process_begin_events(&event, &mut context);
1✔
516

517
        assert!(matches!(result, Some(EventResult::Continue)));
1✔
518
        // Number should get position adjusted by ContentRange::number_start_from_current
519
        assert!(matches!(context.state, crate::shared::State::Number(_)));
1✔
520
        assert_eq!(context.string_begin_calls, Vec::<usize>::new()); // No string calls for numbers
1✔
521
    }
1✔
522

523
    #[test]
524
    fn test_begin_events_primitives() {
1✔
525
        let mut context = MockContentExtractor::new();
1✔
526

527
        for token in [EventToken::True, EventToken::False, EventToken::Null] {
3✔
528
            let event = crate::ujson::Event::Begin(token);
3✔
529
            let result = process_begin_events(&event, &mut context);
3✔
530
            assert!(matches!(result, Some(EventResult::Continue)));
3✔
531
        }
532

533
        // Should not affect state or string processing
534
        assert!(matches!(context.state, crate::shared::State::None));
1✔
535
        assert!(context.string_begin_calls.is_empty());
1✔
536
    }
1✔
537

538
    #[test]
539
    fn test_begin_events_not_handled() {
1✔
540
        let mut context = MockContentExtractor::new();
1✔
541
        let event = crate::ujson::Event::Begin(EventToken::EscapeQuote);
1✔
542

543
        let result = process_begin_events(&event, &mut context);
1✔
544

545
        assert!(result.is_none());
1✔
546
        assert!(matches!(context.state, crate::shared::State::None));
1✔
547
        assert!(context.string_begin_calls.is_empty());
1✔
548
    }
1✔
549

550
    #[test]
551
    fn test_tokenizer_callback() {
1✔
552
        let mut event_storage = [None, None];
1✔
553

554
        // Initially no events
555
        assert!(!have_events(&event_storage));
1✔
556

557
        {
1✔
558
            let mut callback = create_tokenizer_callback(&mut event_storage);
1✔
559

1✔
560
            // Add first event
1✔
561
            callback(crate::ujson::Event::ObjectStart, 1);
1✔
562
        }
1✔
563
        assert!(have_events(&event_storage));
1✔
564
        assert!(event_storage[0].is_some());
1✔
565
        assert!(event_storage[1].is_none());
1✔
566

567
        {
1✔
568
            let mut callback = create_tokenizer_callback(&mut event_storage);
1✔
569
            // Add second event
1✔
570
            callback(crate::ujson::Event::ArrayStart, 1);
1✔
571
        }
1✔
572
        assert!(event_storage[0].is_some());
1✔
573
        assert!(event_storage[1].is_some());
1✔
574

575
        {
1✔
576
            let mut callback = create_tokenizer_callback(&mut event_storage);
1✔
577
            // Storage is full, third event should be ignored (no panic)
1✔
578
            callback(crate::ujson::Event::ObjectEnd, 1);
1✔
579
        }
1✔
580
        assert!(event_storage[0].is_some());
1✔
581
        assert!(event_storage[1].is_some());
1✔
582
    }
1✔
583

584
    #[test]
585
    fn test_event_extraction() {
1✔
586
        let mut event_storage = [
1✔
587
            Some(crate::ujson::Event::ObjectStart),
1✔
588
            Some(crate::ujson::Event::ArrayStart),
1✔
589
        ];
1✔
590

591
        // Extract first event
592
        let first = take_first_event(&mut event_storage);
1✔
593
        assert!(matches!(first, Some(crate::ujson::Event::ObjectStart)));
1✔
594
        assert!(event_storage[0].is_none());
1✔
595
        assert!(event_storage[1].is_some());
1✔
596

597
        // Extract second event
598
        let second = take_first_event(&mut event_storage);
1✔
599
        assert!(matches!(second, Some(crate::ujson::Event::ArrayStart)));
1✔
600
        assert!(event_storage[0].is_none());
1✔
601
        assert!(event_storage[1].is_none());
1✔
602

603
        // No more events
604
        let none = take_first_event(&mut event_storage);
1✔
605
        assert!(none.is_none());
1✔
606
        assert!(!have_events(&event_storage));
1✔
607
    }
1✔
608
}
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