ged_io 0.12.3

A parser for GEDCOM files
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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Builder pattern implementation for configuring GEDCOM parsing.
//!
//! The `GedcomBuilder` provides a fluent API for configuring how GEDCOM files
//! are parsed, offering fine-grained control over parsing behavior, validation,
//! and error handling.
//!
//! # Example
//!
//! ```rust
//! use ged_io::GedcomBuilder;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let source = "0 HEAD\n1 GEDC\n2 VERS 5.5\n0 TRLR";
//! let gedcom_data = GedcomBuilder::new()
//!     .strict_mode(false)
//!     .validate_references(true)
//!     .build_from_str(source)?;
//!
//! println!("Parsed {} individuals", gedcom_data.individuals.len());
//! # Ok(())
//! # }
//! ```

use crate::{
    encoding::{decode_gedcom_bytes, GedcomEncoding},
    tokenizer::Tokenizer,
    types::GedcomData,
    GedcomError,
};
use std::str::Chars;

/// Configuration options for GEDCOM parsing.
///
/// This struct holds all configuration settings that affect how the parser
/// processes GEDCOM data. It is used internally by `GedcomBuilder`.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// When true, the parser will fail on any non-standard or unknown tags.
    /// When false, unknown tags are skipped or stored as custom data.
    pub strict_mode: bool,

    /// When true, the parser validates that all cross-references (xrefs)
    /// point to existing records.
    pub validate_references: bool,

    /// When true, unknown/unrecognized tags are silently ignored.
    /// When false, they may be stored as custom data or cause errors (depending on `strict_mode`).
    pub ignore_unknown_tags: bool,

    /// When true, the parser attempts to auto-detect the character encoding.
    /// When false, UTF-8 is assumed.
    pub encoding_detection: bool,

    /// When true, dates are validated for proper GEDCOM format.
    /// When false, dates are stored as-is without validation.
    pub date_validation: bool,

    /// Optional maximum file size in bytes. If set, files exceeding this size
    /// will cause an error before parsing begins.
    pub max_file_size: Option<usize>,

    /// When true, original spacing and formatting in text values is preserved.
    /// When false, text may be normalized.
    pub preserve_formatting: bool,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            strict_mode: false,
            validate_references: false,
            ignore_unknown_tags: false,
            encoding_detection: false,
            date_validation: false,
            max_file_size: None,
            preserve_formatting: true,
        }
    }
}

/// A builder for creating and configuring a GEDCOM parser.
///
/// `GedcomBuilder` provides a fluent interface for setting parsing options
/// before processing GEDCOM data. This allows users to customize parsing
/// behavior without breaking backward compatibility with the existing API.
///
/// # Example
///
/// ```rust
/// use ged_io::GedcomBuilder;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let source = "0 HEAD\n1 GEDC\n2 VERS 5.5\n0 TRLR";
///
/// // Basic usage with defaults
/// let data = GedcomBuilder::new()
///     .build_from_str(source)?;
///
/// // With custom configuration
/// let data = GedcomBuilder::new()
///     .strict_mode(true)
///     .validate_references(true)
///     .build_from_str(source)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct GedcomBuilder {
    config: ParserConfig,
}

impl GedcomBuilder {
    /// Creates a new `GedcomBuilder` with default configuration.
    ///
    /// Default settings:
    /// - `strict_mode`: false
    /// - `validate_references`: false
    /// - `ignore_unknown_tags`: false
    /// - `encoding_detection`: false
    /// - `date_validation`: false
    /// - `max_file_size`: None (unlimited)
    /// - `preserve_formatting`: true
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: ParserConfig::default(),
        }
    }

    /// Enables or disables strict parsing mode.
    ///
    /// When strict mode is enabled, the parser will fail on any non-standard
    /// tags or structural issues. When disabled (default), the parser is more
    /// lenient and will attempt to continue parsing despite minor issues.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable strict mode
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new()
    ///     .strict_mode(true);
    /// ```
    #[must_use]
    pub fn strict_mode(mut self, enabled: bool) -> Self {
        self.config.strict_mode = enabled;
        self
    }

    /// Enables or disables cross-reference validation.
    ///
    /// When enabled, the parser will validate that all cross-references (xrefs)
    /// in the GEDCOM file point to existing records. This is useful for
    /// detecting broken references but may slow down parsing.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to validate references
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new()
    ///     .validate_references(true);
    /// ```
    #[must_use]
    pub fn validate_references(mut self, enabled: bool) -> Self {
        self.config.validate_references = enabled;
        self
    }

    /// Enables or disables ignoring unknown tags.
    ///
    /// When enabled, unknown or unrecognized GEDCOM tags will be silently
    /// ignored during parsing. When disabled, unknown tags may be stored
    /// as custom data or cause errors (depending on `strict_mode` setting).
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to ignore unknown tags
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new()
    ///     .ignore_unknown_tags(true);
    /// ```
    #[must_use]
    pub fn ignore_unknown_tags(mut self, enabled: bool) -> Self {
        self.config.ignore_unknown_tags = enabled;
        self
    }

    /// Enables or disables automatic encoding detection.
    ///
    /// When enabled, the parser will attempt to auto-detect the character
    /// encoding of the GEDCOM file from the header or BOM. When disabled,
    /// UTF-8 encoding is assumed.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to auto-detect encoding
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new()
    ///     .encoding_detection(true);
    /// ```
    #[must_use]
    pub fn encoding_detection(mut self, enabled: bool) -> Self {
        self.config.encoding_detection = enabled;
        self
    }

    /// Enables or disables date format validation.
    ///
    /// When enabled, the parser will validate that date values conform to
    /// the GEDCOM date format specification. Invalid dates will cause errors.
    /// When disabled (default), dates are stored as-is without validation.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to validate dates
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new()
    ///     .date_validation(true);
    /// ```
    #[must_use]
    pub fn date_validation(mut self, enabled: bool) -> Self {
        self.config.date_validation = enabled;
        self
    }

    /// Sets a maximum file size limit for parsing.
    ///
    /// When set, the parser will return an error if the input exceeds
    /// the specified size in bytes. This can be used as a safety measure
    /// to prevent parsing extremely large files.
    ///
    /// # Arguments
    ///
    /// * `size` - Maximum file size in bytes
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// // Limit to 10 MB
    /// let builder = GedcomBuilder::new()
    ///     .max_file_size(10 * 1024 * 1024);
    /// ```
    #[must_use]
    pub fn max_file_size(mut self, size: usize) -> Self {
        self.config.max_file_size = Some(size);
        self
    }

    /// Enables or disables preservation of original formatting.
    ///
    /// When enabled (default), original spacing and formatting in text
    /// values is preserved. When disabled, text may be normalized
    /// (e.g., collapsing multiple spaces).
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to preserve formatting
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new()
    ///     .preserve_formatting(false);
    /// ```
    #[must_use]
    pub fn preserve_formatting(mut self, enabled: bool) -> Self {
        self.config.preserve_formatting = enabled;
        self
    }

    /// Returns a reference to the current parser configuration.
    ///
    /// This can be used to inspect the configuration before building.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// let builder = GedcomBuilder::new().strict_mode(true);
    /// assert!(builder.config().strict_mode);
    /// ```
    #[must_use]
    pub fn config(&self) -> &ParserConfig {
        &self.config
    }

    /// Builds the parser and parses the GEDCOM data from a character iterator.
    ///
    /// This method consumes the builder and returns the parsed `GedcomData`
    /// or an error if parsing fails.
    ///
    /// # Arguments
    ///
    /// * `chars` - A character iterator over the GEDCOM content
    ///
    /// # Errors
    ///
    /// Returns a `GedcomError` if:
    /// - The GEDCOM data is malformed
    /// - Validation fails (when strict mode or validation options are enabled)
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let source = "0 HEAD\n1 GEDC\n2 VERS 5.5\n0 TRLR";
    /// let data = GedcomBuilder::new()
    ///     .strict_mode(false)
    ///     .build(source.chars())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(self, chars: Chars<'_>) -> Result<GedcomData, GedcomError> {
        let mut tokenizer = Tokenizer::new(chars);
        tokenizer.next_token()?;

        let data = GedcomData::new(&mut tokenizer, 0)?;

        // Post-parse validation if enabled
        if self.config.validate_references {
            self.validate_references_internal(&data)?;
        }

        Ok(data)
    }

    /// Builds the parser and parses the GEDCOM data from raw bytes.
    ///
    /// This method automatically detects the character encoding of the input
    /// and converts it to UTF-8 before parsing. Supported encodings include:
    /// - UTF-8 (with or without BOM)
    /// - UTF-16 LE/BE (with BOM)
    /// - ISO-8859-1 (Latin-1)
    /// - ISO-8859-15 (Latin-9)
    /// - ASCII
    ///
    /// # Arguments
    ///
    /// * `bytes` - The raw bytes of the GEDCOM file
    ///
    /// # Errors
    ///
    /// Returns a `GedcomError` if:
    /// - The encoding cannot be detected or decoded
    /// - The GEDCOM data is malformed
    /// - Validation fails (when strict mode or validation options are enabled)
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // Read file as bytes to handle any encoding
    /// let bytes = b"0 HEAD\n1 GEDC\n2 VERS 5.5\n1 CHAR UTF-8\n0 TRLR";
    /// let data = GedcomBuilder::new()
    ///     .build_from_bytes(bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_from_bytes(self, bytes: &[u8]) -> Result<GedcomData, GedcomError> {
        // Check file size limit if configured
        if let Some(max_size) = self.config.max_file_size {
            let size = bytes.len();
            if size > max_size {
                return Err(GedcomError::FileSizeLimitExceeded { size, max_size });
            }
        }

        // Decode bytes to UTF-8 string
        let (content, _encoding) = decode_gedcom_bytes(bytes)?;

        self.build(content.chars())
    }

    /// Builds the parser and parses the GEDCOM data from raw bytes with a specific encoding.
    ///
    /// Use this method when you know the encoding of the file and want to skip
    /// auto-detection.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The raw bytes of the GEDCOM file
    /// * `encoding` - The encoding to use for decoding
    ///
    /// # Errors
    ///
    /// Returns a `GedcomError` if:
    /// - The bytes cannot be decoded with the specified encoding
    /// - The GEDCOM data is malformed
    /// - Validation fails (when strict mode or validation options are enabled)
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::{GedcomBuilder, GedcomEncoding};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let bytes = b"0 HEAD\n1 GEDC\n2 VERS 5.5\n0 TRLR";
    /// let data = GedcomBuilder::new()
    ///     .build_from_bytes_with_encoding(bytes, GedcomEncoding::Utf8)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_from_bytes_with_encoding(
        self,
        bytes: &[u8],
        encoding: GedcomEncoding,
    ) -> Result<GedcomData, GedcomError> {
        // Check file size limit if configured
        if let Some(max_size) = self.config.max_file_size {
            let size = bytes.len();
            if size > max_size {
                return Err(GedcomError::FileSizeLimitExceeded { size, max_size });
            }
        }

        // Decode bytes with specified encoding
        let (content, _) = crate::encoding::decode_with_encoding(bytes, encoding)?;

        self.build(content.chars())
    }

    /// Builds the parser and parses the GEDCOM data from a string.
    ///
    /// This is a convenience method that accepts a string slice directly.
    ///
    /// # Arguments
    ///
    /// * `content` - The GEDCOM content as a string slice
    ///
    /// # Errors
    ///
    /// Returns a `GedcomError` if:
    /// - The GEDCOM data is malformed
    /// - Validation fails (when strict mode or validation options are enabled)
    ///
    /// # Example
    ///
    /// ```rust
    /// use ged_io::GedcomBuilder;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let source = "0 HEAD\n1 GEDC\n2 VERS 5.5\n0 TRLR";
    /// let data = GedcomBuilder::new()
    ///     .build_from_str(source)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_from_str(self, content: &str) -> Result<GedcomData, GedcomError> {
        // Check file size limit if configured
        if let Some(max_size) = self.config.max_file_size {
            let size = content.len();
            if size > max_size {
                return Err(GedcomError::FileSizeLimitExceeded { size, max_size });
            }
        }

        self.build(content.chars())
    }

    /// Builds the parser and parses the GEDCOM data from a GEDZIP archive.
    ///
    /// This method reads a GEDZIP file (ZIP archive containing `gedcom.ged`)
    /// and parses the GEDCOM data from it. GEDZIP is the standard format for
    /// bundling GEDCOM 7.0 datasets with associated media files.
    ///
    /// Requires the `gedzip` feature to be enabled.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The raw bytes of the GEDZIP file
    ///
    /// # Errors
    ///
    /// Returns a `GedcomError` if:
    /// - The bytes are not a valid ZIP archive
    /// - The archive does not contain a `gedcom.ged` file
    /// - The GEDCOM data is malformed
    /// - Validation fails (when strict mode or validation options are enabled)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "gedzip")]
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use ged_io::GedcomBuilder;
    ///
    /// let bytes = std::fs::read("family.gdz")?;
    /// let data = GedcomBuilder::new()
    ///     .build_from_gedzip(&bytes)?;
    /// println!("Found {} individuals", data.individuals.len());
    /// # Ok(())
    /// # }
    /// # #[cfg(not(feature = "gedzip"))]
    /// # fn main() {}
    /// ```
    #[cfg(feature = "gedzip")]
    pub fn build_from_gedzip(self, bytes: &[u8]) -> Result<GedcomData, GedcomError> {
        use crate::gedzip::GedzipReader;

        let cursor = std::io::Cursor::new(bytes);
        let mut reader = GedzipReader::new(cursor)
            .map_err(|e| GedcomError::InvalidFormat(format!("Invalid GEDZIP archive: {e}")))?;

        let gedcom_bytes = reader
            .read_gedcom_bytes()
            .map_err(|e| GedcomError::InvalidFormat(format!("Failed to read gedcom.ged: {e}")))?;

        // Check file size limit if configured
        if let Some(max_size) = self.config.max_file_size {
            let size = gedcom_bytes.len();
            if size > max_size {
                return Err(GedcomError::FileSizeLimitExceeded { size, max_size });
            }
        }

        self.build_from_bytes(&gedcom_bytes)
    }

    /// Validates that all cross-references point to existing records.
    #[allow(clippy::unused_self)]
    fn validate_references_internal(&self, data: &GedcomData) -> Result<(), GedcomError> {
        use std::collections::HashSet;

        // Collect all xrefs
        let mut xrefs: HashSet<&str> = HashSet::new();

        for individual in &data.individuals {
            if let Some(ref xref) = individual.xref {
                xrefs.insert(xref.as_str());
            }
        }

        for family in &data.families {
            if let Some(ref xref) = family.xref {
                xrefs.insert(xref.as_str());
            }
        }

        for source in &data.sources {
            if let Some(ref xref) = source.xref {
                xrefs.insert(xref.as_str());
            }
        }

        for repo in &data.repositories {
            if let Some(ref xref) = repo.xref {
                xrefs.insert(xref.as_str());
            }
        }

        for submitter in &data.submitters {
            if let Some(ref xref) = submitter.xref {
                xrefs.insert(xref.as_str());
            }
        }

        for multimedia in &data.multimedia {
            if let Some(ref xref) = multimedia.xref {
                xrefs.insert(xref.as_str());
            }
        }

        // Validate family references
        for family in &data.families {
            if let Some(ref husb) = family.individual1 {
                if !xrefs.contains(husb.as_str()) {
                    return Err(GedcomError::InvalidFormat(format!(
                        "Family references non-existent individual: {husb}"
                    )));
                }
            }
            if let Some(ref wife) = family.individual2 {
                if !xrefs.contains(wife.as_str()) {
                    return Err(GedcomError::InvalidFormat(format!(
                        "Family references non-existent individual: {wife}"
                    )));
                }
            }
            for child in &family.children {
                if !xrefs.contains(child.as_str()) {
                    return Err(GedcomError::InvalidFormat(format!(
                        "Family references non-existent child: {child}"
                    )));
                }
            }
        }

        // Validate individual family links
        for individual in &data.individuals {
            for family_link in &individual.families {
                if !xrefs.contains(family_link.xref.as_str()) {
                    return Err(GedcomError::InvalidFormat(format!(
                        "Individual references non-existent family: {}",
                        family_link.xref
                    )));
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_default() {
        let builder = GedcomBuilder::new();
        assert!(!builder.config().strict_mode);
        assert!(!builder.config().validate_references);
        assert!(!builder.config().ignore_unknown_tags);
        assert!(!builder.config().encoding_detection);
        assert!(!builder.config().date_validation);
        assert!(builder.config().max_file_size.is_none());
        assert!(builder.config().preserve_formatting);
    }

    #[test]
    fn test_builder_fluent_api() {
        let builder = GedcomBuilder::new()
            .strict_mode(true)
            .validate_references(true)
            .ignore_unknown_tags(true)
            .encoding_detection(true)
            .date_validation(true)
            .max_file_size(1_000_000)
            .preserve_formatting(false);

        assert!(builder.config().strict_mode);
        assert!(builder.config().validate_references);
        assert!(builder.config().ignore_unknown_tags);
        assert!(builder.config().encoding_detection);
        assert!(builder.config().date_validation);
        assert_eq!(builder.config().max_file_size, Some(1_000_000));
        assert!(!builder.config().preserve_formatting);
    }

    #[test]
    fn test_builder_build_minimal() {
        let sample = "0 HEAD\n1 GEDC\n2 VERS 5.5\n0 TRLR";
        let result = GedcomBuilder::new().build_from_str(sample);
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_with_individuals() {
        let sample = "\
            0 HEAD\n\
            1 GEDC\n\
            2 VERS 5.5\n\
            0 @I1@ INDI\n\
            1 NAME John /Doe/\n\
            0 TRLR";

        let data = GedcomBuilder::new().build_from_str(sample).unwrap();

        assert_eq!(data.individuals.len(), 1);
    }

    #[test]
    fn test_builder_validate_references_error() {
        let sample = "\
            0 HEAD\n\
            1 GEDC\n\
            2 VERS 5.5\n\
            0 @F1@ FAM\n\
            1 HUSB @I_NONEXISTENT@\n\
            0 TRLR";

        let result = GedcomBuilder::new()
            .validate_references(true)
            .build_from_str(sample);

        assert!(result.is_err());
    }

    #[test]
    fn test_builder_validate_references_success() {
        let sample = "\
            0 HEAD\n\
            1 GEDC\n\
            2 VERS 5.5\n\
            0 @I1@ INDI\n\
            1 NAME John /Doe/\n\
            0 @F1@ FAM\n\
            1 HUSB @I1@\n\
            0 TRLR";

        let result = GedcomBuilder::new()
            .validate_references(true)
            .build_from_str(sample);

        assert!(result.is_ok());
    }

    #[test]
    fn test_parser_config_clone() {
        let config = ParserConfig {
            strict_mode: true,
            validate_references: true,
            ignore_unknown_tags: true,
            encoding_detection: true,
            date_validation: true,
            max_file_size: Some(1000),
            preserve_formatting: false,
        };
        let cloned = config.clone();
        assert_eq!(config.strict_mode, cloned.strict_mode);
        assert_eq!(config.validate_references, cloned.validate_references);
        assert_eq!(config.date_validation, cloned.date_validation);
        assert_eq!(config.max_file_size, cloned.max_file_size);
        assert_eq!(config.preserve_formatting, cloned.preserve_formatting);
    }

    #[test]
    fn test_builder_max_file_size_exceeded() {
        let large_content = "0 HEAD\n1 GEDC\n2 VERS 5.5\n".to_string()
            + &"0 @I1@ INDI\n1 NAME Test /Person/\n".repeat(100)
            + "0 TRLR";

        let result = GedcomBuilder::new()
            .max_file_size(100) // 100 bytes limit
            .build_from_str(&large_content);

        match result {
            Err(GedcomError::FileSizeLimitExceeded { size, max_size }) => {
                assert!(size > 100);
                assert_eq!(max_size, 100);
            }
            _ => panic!("Expected FileSizeLimitExceeded error"),
        }
    }

    #[test]
    fn test_builder_clone() {
        let builder = GedcomBuilder::new().strict_mode(true);
        let cloned = builder.clone();
        assert!(cloned.config().strict_mode);
    }
}