babbel_yaml 0.1.2

Fast, modular YAML 1.2 parser and emitter with anchors, aliases, and tags
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! File Source for Decoded Input
//!
//! Provides a file-based source for reading YAML or JSON data from disk.
//! Implements the `ISource` trait and file operations for traversing and reading byte content from files.
//!
//! Copyright (c) 2026 YAML Library Developers

use crate::io::traits::{ICharStream, IIndentationAware, IStatefulStream};

impl ICharStream for File {
    fn next(&mut self) {
        // Read next byte
        let mut byte1 = [0u8; 1];

        // Update position for current character before moving
        if self.current_byte.is_some() {
            self.column += 1;
            if self.current_byte.unwrap() == b'\n' {
                self.line += 1;
                self.column = 0;
            }
        }

        if self.file.read(&mut byte1).unwrap_or(0) == 1 {
            if byte1[0] == b'\r' {
                // Check if followed by \n (CRLF sequence)
                let mut byte2 = [0u8; 1];
                match self.file.read(&mut byte2) {
                    Ok(1) if byte2[0] == b'\n' => {
                        // CRLF - treat as single \n
                        self.current_byte = Some(b'\n');
                        self.column = 0; // Newlines have column 0
                    }
                    Ok(1) => {
                        // Standalone CR
                        self.current_byte = Some(byte1[0]);
                        let _ = self.file.seek(SeekFrom::Current(-1));
                    }
                    _ => {
                        self.current_byte = Some(byte1[0]);
                    }
                }
            } else {
                self.current_byte = Some(byte1[0]);
            }
        } else {
            self.current_byte = None;
        }
    }
    fn current(&mut self) -> Option<char> {
        self.current_byte.map(|b| b as char)
    }

    fn more(&mut self) -> bool {
        self.current_byte.is_some()
    }

    fn reset(&mut self) {
        if self.file.seek(SeekFrom::Start(0)).is_ok() {
            let mut byte = [0u8; 1];
            self.current_byte = if self.file.read(&mut byte).unwrap_or(0) == 1 {
                Some(byte[0])
            } else {
                None
            };
            self.column = 0;
            self.line = 0;
        }
    }
}

impl IIndentationAware for File {
    fn get_current_indent_level(&self) -> usize {
        self.column
    }
}

impl IStatefulStream for File {
    fn save_state(&mut self) -> crate::io::traits::SaveState {
        let pos = self.file.stream_position().unwrap_or(0);
        crate::io::traits::SaveState {
            pos,
            current_byte: self.current_byte,
            column: self.column,
            line: self.line,
        }
    }

    fn restore_state(&mut self, state: crate::io::traits::SaveState) {
        let _ = self.file.seek(SeekFrom::Start(state.pos));
        self.current_byte = state.current_byte;
        self.column = state.column;
        self.line = state.line;
    }
}
use crate::io::util::read_all;
use std::fs::File as StdFile;
use std::io::{Read, Seek, SeekFrom};

/// File

pub struct File {
    file: StdFile,
    current_byte: Option<u8>,
    column: usize,
    line: usize,
}
impl File {
    /// Reads the entire file into a `Vec<u8>` using shared helper
    pub fn read_all_bytes(&mut self) -> std::io::Result<Vec<u8>> {
        read_all(&mut self.file)
    }
}

impl File {
    /// new
    pub fn new(path: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
        let mut file = StdFile::open(path.as_ref())?;

        // Read first byte and handle CRLF
        let mut first = [0u8; 1];
        let current_byte = if file.read(&mut first)? == 1 {
            if first[0] == b'\r' {
                // Check if this is CRLF
                let mut next = [0u8; 1];
                if file.read(&mut next)? == 1 && next[0] == b'\n' {
                    // CRLF - treat as \n
                    Some(b'\n')
                } else {
                    // Standalone CR or CR followed by non-LF
                    if next[0] != 0 {
                        file.seek(SeekFrom::Current(-1))?;
                    }
                    Some(first[0])
                }
            } else {
                Some(first[0])
            }
        } else {
            None
        };

        Ok(Self {
            file,
            current_byte,
            column: 0,
            line: 0,
        })
    }
    pub fn next(&mut self) {
        ICharStream::next(self)
    }
    pub fn current(&mut self) -> Option<char> {
        ICharStream::current(self)
    }
    pub fn more(&mut self) -> bool {
        ICharStream::more(self)
    }
    pub fn reset(&mut self) {
        ICharStream::reset(self)
    }
    pub fn get_current_indent_level(&self) -> usize {
        IIndentationAware::get_current_indent_level(self)
    }
    pub fn save_state(&mut self) -> crate::io::traits::SaveState {
        IStatefulStream::save_state(self)
    }
    pub fn restore_state(&mut self, state: crate::io::traits::SaveState) {
        IStatefulStream::restore_state(self, state)
    }
}



#[cfg(test)]
mod tests {
    use super::*;
    use crate::nodes::node::{BlockStyle, Node, Numeric, QuoteType};
    use crate::parse;
    use std::fs;
    use std::fs::OpenOptions;
    use std::io::Write;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TEST_FILE_COUNTER: AtomicUsize = AtomicUsize::new(0);

    struct TestFile {
        path: String,
    }

    impl TestFile {
        fn new(content: &[u8]) -> Self {
            let id = TEST_FILE_COUNTER.fetch_add(1, Ordering::SeqCst);
            let pid = std::process::id();
            let mut temp_path = std::env::temp_dir();
            temp_path.push(format!("test_yaml_temp_file_{}_{}.yaml", pid, id));
            let path = temp_path.to_str().unwrap().to_string();
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&path)
                .unwrap();
            file.write_all(content).unwrap();
            Self { path }
        }
    }

    impl Drop for TestFile {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.path);
        }
    }

    #[test]
    fn test_file_new_and_current() {
        let test_file = TestFile::new(b"abc");
        let mut file = File::new(&test_file.path).unwrap();
        assert_eq!(file.current(), Some('a'));
    }

    #[test]
    fn test_file_next_and_more() {
        let test_file = TestFile::new(b"ab");
        let mut file = File::new(&test_file.path).unwrap();
        assert!(file.more());
        assert_eq!(file.current(), Some('a'));
        file.next();
        assert_eq!(file.current(), Some('b'));
        assert!(file.more());
        file.next();
        assert_eq!(file.current(), None);
        assert!(!file.more());
    }

    #[test]
    fn test_file_reset() {
        let test_file = TestFile::new(b"xy");
        let mut file = File::new(&test_file.path).unwrap();
        file.next();
        assert_eq!(file.current(), Some('y'));
        file.reset();
        assert_eq!(file.current(), Some('x'));
    }

    #[test]
    fn test_file_save_restore() {
        let test_file = TestFile::new(b"123\r\n456");
        let mut file = File::new(&test_file.path).unwrap();

        assert_eq!(file.current(), Some('1'));
        let s1 = file.save_state();
        file.next();
        let s2 = file.save_state();
        file.next();
        let s3 = file.save_state();
        file.next();
        let s_newline = file.save_state();
        file.next();
        assert_eq!(file.current(), Some('4'));

        file.restore_state(s_newline);
        assert_eq!(file.current(), Some('\n'));
        file.restore_state(s3);
        assert_eq!(file.current(), Some('3'));
        file.restore_state(s2);
        assert_eq!(file.current(), Some('2'));
        file.restore_state(s1);
        assert_eq!(file.current(), Some('1'));
        assert_eq!(file.get_current_indent_level(), 0);
    }

    #[test]
    fn test_file_get_current_indent_level() {
        let test_file = TestFile::new(b"abc\ndef");
        let mut file = File::new(&test_file.path).unwrap();
        assert_eq!(file.get_current_indent_level(), 0);
        file.next();
        assert_eq!(file.get_current_indent_level(), 1);
        file.next();
        assert_eq!(file.get_current_indent_level(), 2);
        file.next();
        assert_eq!(file.get_current_indent_level(), 3);
        file.next();
        assert_eq!(file.get_current_indent_level(), 0);
    }

    #[test]
    fn test_file_new_empty_file() {
        let test_file = TestFile::new(b"");
        let mut file = File::new(&test_file.path).unwrap();
        assert_eq!(file.current(), None);
        assert!(!file.more());
    }

    #[test]
    fn test_file_handles_crlf_newlines() {
        let test_file = TestFile::new(b"ab\r\ncd\r\nef");
        let mut file = File::new(&test_file.path).unwrap();

        assert_eq!(file.current(), Some('a'));
        assert_eq!(file.get_current_indent_level(), 0);

        file.next();
        assert_eq!(file.current(), Some('b'));
        assert_eq!(file.get_current_indent_level(), 1);

        file.next();
        assert_eq!(file.current(), Some('\n'));
        assert_eq!(file.get_current_indent_level(), 0);

        file.next();
        assert_eq!(file.current(), Some('c'));
        assert_eq!(file.get_current_indent_level(), 0);

        file.next();
        assert_eq!(file.current(), Some('d'));
        assert_eq!(file.get_current_indent_level(), 1);

        file.next();
        assert_eq!(file.current(), Some('\n'));
        assert_eq!(file.get_current_indent_level(), 0);

        file.next();
        assert_eq!(file.current(), Some('e'));
        assert_eq!(file.get_current_indent_level(), 0);

        file.next();
        assert_eq!(file.current(), Some('f'));
        assert_eq!(file.get_current_indent_level(), 1);

        file.next();
        assert_eq!(file.current(), None);
    }

    #[test]
    fn test_file_eof_after_consumption() {
        let test_file = TestFile::new(b"xy");
        let mut file = File::new(&test_file.path).unwrap();

        file.next();
        file.next();
        assert_eq!(file.current(), None);
        assert!(!file.more());
    }

    #[test]
    fn test_file_next_safe_at_eof() {
        let test_file = TestFile::new(b"a");
        let mut file = File::new(&test_file.path).unwrap();
        assert_eq!(file.current(), Some('a'));
        file.next();
        assert_eq!(file.current(), None);

        file.next();
        assert_eq!(file.current(), None);
        assert!(!file.more());
    }

    #[test]
    fn test_file_reset_restores_after_eof() {
        let test_file = TestFile::new(b"- [Sammy Sosa, 63, 0.288]");
        let mut file = File::new(&test_file.path).unwrap();
        assert_eq!(file.current(), Some('-'));
        file.next();
        file.next();
        assert_eq!(file.current(), Some('['));
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        file.next();
        assert_eq!(file.current(), None);
        file.reset();
        assert_eq!(file.current(), Some('-'));
        assert!(file.more());
    }
    #[test]
    fn test_file_parse_nested_sequences() {
        let test_file = TestFile::new(b"- [Sammy Sosa, 63, 0.288]");
        let mut file = File::new(&test_file.path).unwrap();
        let node = parse(&mut file).unwrap();
        assert_eq!(
            node,
            Node::Documents(vec![Node::Document(vec![Node::Array(vec![Node::Array(
                vec![
                    Node::Str(
                        "Sammy Sosa".to_string(),
                        QuoteType::Unquoted,
                        BlockStyle::None
                    ),
                    Node::Number(Numeric::Integer(63)),
                    Node::Number(Numeric::Float(0.288))
                ]
            )])])])
        );
    }

    fn create_temp_file(data: &[u8], name: &str) -> String {
        let path = format!("test_temp_{}.txt", name);
        let mut f = StdFile::create(&path).unwrap();
        f.write_all(data).unwrap();
        path
    }

    #[test]
    fn file_handles_only_newlines() {
        let path = create_temp_file(b"\n\n\n", "only_newlines");
        let mut file = File::new(&path).unwrap();
        for _ in 0..3 {
            assert_eq!(file.current(), Some('\n'));
            file.next();
        }
        assert_eq!(file.current(), None);
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn file_handles_mixed_line_endings() {
        let path = create_temp_file(b"a\r\nb\rc\nd", "mixed_lines");
        let mut file = File::new(&path).unwrap();
        assert_eq!(file.current(), Some('a'));
        file.next(); // '\r'
        assert_eq!(file.current(), Some('\n'));
        file.next(); // 'b'
        assert_eq!(file.current(), Some('b'));
        file.next(); // '\r'
        assert_eq!(file.current(), Some('\r'));
        file.next(); // 'c'
        assert_eq!(file.current(), Some('c'));
        file.next(); // '\n'
        assert_eq!(file.current(), Some('\n'));
        file.next(); // 'd'
        assert_eq!(file.current(), Some('d'));
        file.next();
        assert_eq!(file.current(), None);
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn file_reset_after_partial_read() {
        let path = create_temp_file(b"xyz", "reset_partial");
        let mut file = File::new(&path).unwrap();
        file.next();
        assert_eq!(file.current(), Some('y'));
        file.reset();
        assert_eq!(file.current(), Some('x'));
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn file_handles_large_input() {
        let data = vec![b'a'; 10_000];
        let path = create_temp_file(&data, "large_input");
        let mut file = File::new(&path).unwrap();
        let mut count = 0;
        while file.more() {
            assert_eq!(file.current(), Some('a'));
            file.next();
            count += 1;
        }
        assert_eq!(count, 10_000);
        fs::remove_file(path).unwrap();
    }
}