frontmatter_gen/
parser.rs

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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! # Front Matter Parser and Serialiser Module
//!
//! This module provides robust functionality for parsing and serialising front matter
//! in various formats (YAML, TOML, and JSON). It focuses on:
//!
//! - Memory efficiency through pre-allocation and string optimisation
//! - Type safety with comprehensive error handling
//! - Performance optimisation with minimal allocations
//! - Validation of input data
//! - Consistent cross-format handling
//!
//! ## Features
//!
//! - Multi-format support (YAML, TOML, JSON)
//! - Zero-copy parsing where possible
//! - Efficient memory management
//! - Comprehensive validation
//! - Rich error context
//!
//! ## Usage Example
//!
//! ```rust
//! use frontmatter_gen::{Format, parser};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let yaml = "title: My Post\ndate: 2025-09-09\n";
//! let front_matter = parser::parse_with_options(
//!     yaml,
//!     Format::Yaml,
//!     None
//! )?;
//! # Ok(())
//! # }
//! ```

use serde::Serialize;
use serde_json::Value as JsonValue;
use serde_yml::Value as YamlValue;
use std::{collections::HashMap, sync::Arc};
use toml::Value as TomlValue;

use crate::{error::Error, types::Frontmatter, Format, Value};

// Constants for optimisation and validation
const SMALL_STRING_SIZE: usize = 24;
const MAX_NESTING_DEPTH: usize = 32;
const MAX_KEYS: usize = 1000;

/// Options for controlling parsing behaviour.
///
/// Provides configuration for maximum allowed nesting depth, maximum number of keys,
/// and whether to perform validation.
#[derive(Debug, Clone, Copy)]
pub struct ParseOptions {
    /// Maximum allowed nesting depth.
    pub max_depth: usize,
    /// Maximum allowed number of keys.
    pub max_keys: usize,
    /// Whether to validate the structure.
    pub validate: bool,
}

impl Default for ParseOptions {
    fn default() -> Self {
        Self {
            max_depth: MAX_NESTING_DEPTH,
            max_keys: MAX_KEYS,
            validate: true,
        }
    }
}

/// Optimises string storage based on length.
///
/// For strings shorter than `SMALL_STRING_SIZE`, uses standard allocation.
/// For longer strings, pre-allocates exact capacity to avoid reallocations.
///
/// # Arguments
///
/// * `s` - The input string slice to optimise.
///
/// # Returns
///
/// An optimised owned `String`.
#[inline]
fn optimise_string(s: &str) -> String {
    if s.len() <= SMALL_STRING_SIZE {
        s.to_string()
    } else {
        let mut string = String::with_capacity(s.len());
        string.push_str(s);
        string
    }
}

/// Parses raw front matter string into a `Frontmatter` object based on the specified format.
///
/// This function attempts to parse the provided string into a structured `Frontmatter`
/// object according to the specified format. It performs validation by default
/// and optimises memory allocation where possible.
///
/// # Arguments
///
/// * `raw_front_matter` - A string slice containing the raw front matter content.
/// * `format` - The `Format` enum specifying the desired format.
/// * `options` - Optional parsing options for controlling validation and limits.
///
/// # Returns
///
/// A `Result` containing either the parsed `Frontmatter` object or a `Error`.
///
/// # Errors
///
/// Returns `Error` if:
/// - The input is not valid in the specified format
/// - The structure exceeds configured limits
/// - The format is unsupported
pub fn parse_with_options(
    raw_front_matter: &str,
    format: Format,
    options: Option<ParseOptions>,
) -> Result<Frontmatter, Error> {
    let options = options.unwrap_or_default();

    // Check for unsupported formats
    if format == Format::Unsupported {
        let err_msg = format!(
            "Unsupported format: {:?}. Supported formats are YAML, TOML, and JSON.",
            format
        );
        log::error!("{}", err_msg);
        return Err(Error::ConversionError(err_msg));
    }

    // Trim the input and validate format assumptions
    let trimmed_content = raw_front_matter.trim();

    // Format-specific validation
    match format {
        Format::Yaml => {
            if !trimmed_content.starts_with("---") {
                log::debug!("YAML front matter validation: Content structure appears non-standard");
            }
        }
        Format::Toml => {
            if !trimmed_content.contains('=') {
                return Err(Error::ConversionError(
                    "Format set to TOML but input does not contain '=' signs.".to_string(),
                ));
            }
        }
        Format::Json => {
            if !trimmed_content.starts_with('{') {
                return Err(Error::ConversionError(
                    "Format set to JSON but input does not start with '{'."
                        .to_string(),
                ));
            }
        }
        Format::Unsupported => unreachable!(), // We've already handled this case above
    };

    let front_matter = match format {
        Format::Yaml => parse_yaml(trimmed_content).map_err(|e| {
            log::error!("YAML parsing failed: {}", e);
            e
        })?,
        Format::Toml => parse_toml(trimmed_content).map_err(|e| {
            log::error!("TOML parsing failed: {}", e);
            e
        })?,
        Format::Json => parse_json(trimmed_content).map_err(|e| {
            log::error!("JSON parsing failed: {}", e);
            e
        })?,
        Format::Unsupported => unreachable!(),
    };

    // Perform validation if specified in options
    if options.validate {
        log::debug!(
            "Validating front matter: maximum allowed nesting depth is {}, maximum allowed number of keys is {}",
            options.max_depth,
            options.max_keys
        );

        validate_frontmatter(
            &front_matter,
            options.max_depth,
            options.max_keys,
        )
        .map_err(|e| {
            log::error!("Front matter validation failed: {}", e);
            e
        })?;
    }

    Ok(front_matter)
}

/// Convenience wrapper around `parse_with_options` using default options.
///
/// # Arguments
///
/// * `raw_front_matter` - A string slice containing the raw front matter content.
/// * `format` - The `Format` enum specifying the desired format.
///
/// # Returns
///
/// A `Result` containing either the parsed `Frontmatter` object or a `Error`.
///
/// # Errors
///
/// Returns an `Error` if:
/// - The format is invalid or unsupported.
/// - Parsing fails due to invalid syntax.
/// - Validation fails if enabled.
pub fn parse(
    raw_front_matter: &str,
    format: Format,
) -> Result<Frontmatter, Error> {
    parse_with_options(raw_front_matter, format, None)
}

/// Converts a `Frontmatter` object to a string representation in the specified format.
///
/// # Arguments
///
/// * `front_matter` - Reference to the `Frontmatter` object to serialise.
/// * `format` - The target format for serialisation.
///
/// # Returns
///
/// A `Result` containing the serialised string or a `Error`.
///
/// # Errors
///
/// Returns `Error` if:
/// - Serialisation fails.
/// - The specified format is unsupported.
pub fn to_string(
    front_matter: &Frontmatter,
    format: Format,
) -> Result<String, Error> {
    match format {
        Format::Yaml => to_yaml(front_matter),
        Format::Toml => to_toml(front_matter),
        Format::Json => to_json_optimised(front_matter),
        Format::Unsupported => Err(Error::ConversionError(
            "Unsupported format".to_string(),
        )),
    }
}

// YAML Implementation
// -------------------

/// Parses a YAML string into a `Frontmatter` object.
///
/// # Arguments
///
/// * `raw` - The raw YAML string.
///
/// # Returns
///
/// A `Result` containing the parsed `Frontmatter` or a `Error`.
fn parse_yaml(raw: &str) -> Result<Frontmatter, Error> {
    // Parse the YAML content into a serde_yml::Value
    let yaml_value: YamlValue = serde_yml::from_str(raw)
        .map_err(|e| Error::YamlParseError { source: e.into() })?;

    // Prepare the front matter container
    let capacity =
        yaml_value.as_mapping().map_or(0, serde_yml::Mapping::len);
    let mut front_matter =
        Frontmatter(HashMap::with_capacity(capacity));

    // Convert the YAML mapping into the front matter structure
    if let YamlValue::Mapping(mapping) = yaml_value {
        for (key, value) in mapping {
            if let YamlValue::String(k) = key {
                let _ = front_matter.insert(k, yaml_to_value(&value));
            } else {
                // Log a warning for non-string keys
                log::warn!("Warning: Non-string key ignored in YAML front matter");
            }
        }
    } else {
        return Err(Error::ParseError(
            "YAML front matter is not a valid mapping".to_string(),
        ));
    }

    Ok(front_matter)
}

/// Converts a `serde_yml::Value` into a `Value`.
fn yaml_to_value(yaml: &YamlValue) -> Value {
    match yaml {
        YamlValue::Null => Value::Null,
        YamlValue::Bool(b) => Value::Boolean(*b),
        YamlValue::Number(n) => {
            n.as_i64()
                .map_or_else(
                    || {
                        n.as_f64().map_or_else(
                            || {
                                log::warn!(
                                    "Invalid or unsupported number encountered in YAML: {:?}",
                                    n
                                );
                                Value::Number(0.0) // Fallback for invalid numbers
                            },
                            Value::Number,
                        )
                    },
                    |i| {
                        if i.abs() < (1_i64 << 52) {
                            Value::Number(i as f64)
                        } else {
                            log::warn!(
                                "Integer {} exceeds precision of f64. Defaulting to 0.0",
                                i
                            );
                            Value::Number(0.0) // Fallback for large values outside f64 precision
                        }
                    },
                )
        }
        YamlValue::String(s) => Value::String(optimise_string(s)),
        YamlValue::Sequence(seq) => {
            let mut vec = Vec::with_capacity(seq.len());
            vec.extend(seq.iter().map(yaml_to_value));
            Value::Array(vec)
        }
        YamlValue::Mapping(map) => {
            let mut result =
                Frontmatter(HashMap::with_capacity(map.len()));
            for (k, v) in map {
                if let YamlValue::String(key) = k {
                    let _ = result
                        .0
                        .insert(optimise_string(key), yaml_to_value(v));
                } else {
                    log::warn!(
                        "Non-string key in YAML mapping ignored: {:?}",
                        k
                    );
                }
            }
            Value::Object(Box::new(result))
        }
        YamlValue::Tagged(tagged) => Value::Tagged(
            optimise_string(&tagged.tag.to_string()),
            Box::new(yaml_to_value(&tagged.value)),
        ),
    }
}

/// Serialises a `Frontmatter` object into a YAML string.
///
/// # Arguments
///
/// * `front_matter` - The `Frontmatter` object to serialise.
///
/// # Returns
///
/// A `Result` containing the serialised YAML string or a `Error`.
fn to_yaml(front_matter: &Frontmatter) -> Result<String, Error> {
    serde_yml::to_string(&front_matter.0)
        .map_err(|e| Error::ConversionError(e.to_string()))
}

// TOML Implementation
// -------------------

/// Parses a TOML string into a `Frontmatter` object.
///
/// # Arguments
///
/// * `raw` - The raw TOML string.
///
/// # Returns
///
/// A `Result` containing the parsed `Frontmatter` or a `Error`.
fn parse_toml(raw: &str) -> Result<Frontmatter, Error> {
    let toml_value: TomlValue =
        raw.parse().map_err(Error::TomlParseError)?;

    let capacity = match &toml_value {
        TomlValue::Table(table) => table.len(),
        _ => 0,
    };

    let mut front_matter =
        Frontmatter(HashMap::with_capacity(capacity));

    if let TomlValue::Table(table) = toml_value {
        for (key, value) in table {
            let _ = front_matter.0.insert(key, toml_to_value(&value));
        }
    }

    Ok(front_matter)
}

/// Converts a `toml::Value` into a `Value`.
fn toml_to_value(toml: &TomlValue) -> Value {
    match toml {
        TomlValue::String(s) => Value::String(optimise_string(s)),
        TomlValue::Integer(i) => Value::Number(*i as f64),
        TomlValue::Float(f) => Value::Number(*f),
        TomlValue::Boolean(b) => Value::Boolean(*b),
        TomlValue::Array(arr) => {
            let mut vec = Vec::with_capacity(arr.len());
            vec.extend(arr.iter().map(toml_to_value));
            Value::Array(vec)
        }
        TomlValue::Table(table) => {
            let mut result =
                Frontmatter(HashMap::with_capacity(table.len()));
            for (k, v) in table {
                let _ = result
                    .0
                    .insert(optimise_string(k), toml_to_value(v));
            }
            Value::Object(Box::new(result))
        }
        TomlValue::Datetime(dt) => Value::String(dt.to_string()),
    }
}

/// Serialises a `Frontmatter` object into a TOML string.
///
/// # Arguments
///
/// * `front_matter` - The `Frontmatter` object to serialise.
///
/// # Returns
///
/// A `Result` containing the serialised TOML string or a `Error`.
fn to_toml(front_matter: &Frontmatter) -> Result<String, Error> {
    toml::to_string(&front_matter.0)
        .map_err(|e| Error::ConversionError(e.to_string()))
}

// JSON Implementation
// -------------------

/// Parses a JSON string into a `Frontmatter` object.
///
/// # Arguments
///
/// * `raw` - The raw JSON string.
///
/// # Returns
///
/// A `Result` containing the parsed `Frontmatter` or a `Error`.
fn parse_json(raw: &str) -> Result<Frontmatter, Error> {
    let json_value: JsonValue = serde_json::from_str(raw)
        .map_err(|e| Error::JsonParseError(Arc::new(e)))?;

    let capacity = match &json_value {
        JsonValue::Object(obj) => obj.len(),
        _ => 0,
    };

    let mut front_matter =
        Frontmatter(HashMap::with_capacity(capacity));

    if let JsonValue::Object(obj) = json_value {
        for (key, value) in obj {
            let _ = front_matter.0.insert(key, json_to_value(&value));
        }
    }

    Ok(front_matter)
}

/// Converts a `serde_json::Value` into a `Value`.
fn json_to_value(json: &JsonValue) -> Value {
    match json {
        JsonValue::Null => Value::Null,
        JsonValue::Bool(b) => Value::Boolean(*b),
        JsonValue::Number(n) => n.as_i64().map_or_else(
            || {
                if let Some(f) = n.as_f64() {
                    Value::Number(f)
                } else {
                    Value::Number(0.0)
                }
            },
            |i| Value::Number(i as f64),
        ),
        JsonValue::String(s) => Value::String(optimise_string(s)),
        JsonValue::Array(arr) => {
            let mut vec = Vec::with_capacity(arr.len());
            vec.extend(arr.iter().map(json_to_value));
            Value::Array(vec)
        }
        JsonValue::Object(obj) => {
            let mut result =
                Frontmatter(HashMap::with_capacity(obj.len()));
            for (k, v) in obj {
                let _ = result
                    .0
                    .insert(optimise_string(k), json_to_value(v));
            }
            Value::Object(Box::new(result))
        }
    }
}

/// Optimised JSON serialisation with pre-allocated buffer.
///
/// # Arguments
///
/// * `front_matter` - The `Frontmatter` object to serialise.
///
/// # Returns
///
/// A `Result` containing the serialised JSON string or a `Error`.
fn to_json_optimised(
    front_matter: &Frontmatter,
) -> Result<String, Error> {
    let estimated_size = estimate_json_size(front_matter);
    let buf = Vec::with_capacity(estimated_size);
    let formatter = serde_json::ser::CompactFormatter;
    let mut ser =
        serde_json::Serializer::with_formatter(buf, formatter);

    front_matter
        .0
        .serialize(&mut ser)
        .map_err(|e| Error::ConversionError(e.to_string()))?;

    String::from_utf8(ser.into_inner())
        .map_err(|e| Error::ConversionError(e.to_string()))
}

// Validation and Utilities
// ------------------------

/// Validates a front matter structure against configured limits.
///
/// Checks:
/// - Maximum nesting depth.
/// - Maximum number of keys.
/// - Structure validity.
///
/// # Arguments
///
/// * `fm` - Reference to the front matter to validate.
/// * `max_depth` - Maximum allowed nesting depth.
/// * `max_keys` - Maximum allowed number of keys.
///
/// # Returns
///
/// `Ok(())` if validation passes, `Error` otherwise.
///
/// # Errors
///
/// Returns `Error` if:
/// - The number of keys exceeds `max_keys`.
/// - The nesting depth exceeds `max_depth`.
pub fn validate_frontmatter(
    fm: &Frontmatter,
    max_depth: usize,
    max_keys: usize,
) -> Result<(), Error> {
    if fm.0.len() > max_keys {
        return Err(Error::ContentTooLarge {
            size: fm.0.len(),
            max: max_keys,
        });
    }

    // Validate nesting depth
    for value in fm.0.values() {
        check_depth(value, 1, max_depth)?;
    }

    Ok(())
}

/// Recursively checks the nesting depth of a value.
///
/// # Arguments
///
/// * `value` - The `Value` to check.
/// * `current_depth` - The current depth of recursion.
/// * `max_depth` - The maximum allowed depth.
///
/// # Returns
///
/// `Ok(())` if the depth is within limits, `Error` otherwise.
fn check_depth(
    value: &Value,
    current_depth: usize,
    max_depth: usize,
) -> Result<(), Error> {
    if current_depth > max_depth {
        return Err(Error::NestingTooDeep {
            depth: current_depth,
            max: max_depth,
        });
    }

    match value {
        Value::Array(arr) => {
            for item in arr {
                check_depth(item, current_depth + 1, max_depth)?;
            }
        }
        Value::Object(obj) => {
            for v in obj.0.values() {
                check_depth(v, current_depth + 1, max_depth)?;
            }
        }
        _ => {}
    }

    Ok(())
}

/// Estimates the JSON string size for a front matter object.
///
/// Used for pre-allocating buffers in serialisation.
///
/// # Arguments
///
/// * `fm` - The `Frontmatter` object.
///
/// # Returns
///
/// An estimated size in bytes.
fn estimate_json_size(fm: &Frontmatter) -> usize {
    let mut size = 2; // {}
    for (k, v) in &fm.0 {
        size += k.len() + 3; // "key":
        size += estimate_value_size(v);
        size += 1; // ,
    }
    size
}

/// Estimates the serialised size of a value.
///
/// # Arguments
///
/// * `value` - The `Value` to estimate.
///
/// # Returns
///
/// An estimated size in bytes.
fn estimate_value_size(value: &Value) -> usize {
    match value {
        Value::Null => 4,                // null
        Value::String(s) => s.len() + 2, // "string"
        Value::Number(_) => 8,           // average number length
        Value::Boolean(_) => 5,          // false/true
        Value::Array(arr) => {
            2 + arr.iter().map(estimate_value_size).sum::<usize>() // []
        }
        Value::Object(obj) => estimate_json_size(obj),
        Value::Tagged(tag, val) => {
            tag.len() + 2 + estimate_value_size(val)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::f64::consts::PI;

    // Helper for creating a test `Frontmatter`
    fn create_test_frontmatter() -> Frontmatter {
        let mut fm = Frontmatter::new();
        let _ = fm.insert(
            "title".to_string(),
            Value::String("Test".to_string()),
        );
        let _ = fm.insert("number".to_string(), Value::Number(PI));
        let _ = fm.insert("boolean".to_string(), Value::Boolean(true));
        let _ = fm.insert(
            "array".to_string(),
            Value::Array(vec![
                Value::Number(1.0),
                Value::Number(2.0),
                Value::Number(3.0),
            ]),
        );
        fm
    }

    /// Tests for `ParseOptions::default`.
    mod parse_options_tests {
        use super::*;

        #[test]
        fn test_parse_options_default() {
            let default_options = ParseOptions::default();
            assert_eq!(default_options.max_depth, MAX_NESTING_DEPTH);
            assert_eq!(default_options.max_keys, MAX_KEYS);
            assert!(default_options.validate);
        }
    }

    /// Tests for `optimise_string`.
    mod optimise_string_tests {
        use super::*;

        #[test]
        fn test_optimise_string_short() {
            let short_string = "short";
            let optimised = optimise_string(short_string);
            assert_eq!(optimised, short_string);
            assert_eq!(optimised.capacity(), short_string.len());
        }

        #[test]
        fn test_optimise_string_long() {
            let long_string = "a".repeat(SMALL_STRING_SIZE + 1);
            let optimised = optimise_string(&long_string);
            assert_eq!(optimised, long_string);
            assert!(optimised.capacity() >= long_string.len());
        }
    }

    /// Tests for parsing functions.
    mod parsing_tests {
        use super::*;

        #[test]
        fn test_parse_yaml() {
            let yaml = "key: value";
            let result = parse_yaml(yaml);
            assert!(result.is_ok());
            let fm = result.unwrap();
            assert_eq!(
                fm.0.get("key"),
                Some(&Value::String("value".to_string()))
            );
        }

        #[test]
        fn test_parse_toml() {
            let toml = "key = \"value\"";
            let result = parse_toml(toml);
            assert!(result.is_ok());
            let fm = result.unwrap();
            assert_eq!(
                fm.0.get("key"),
                Some(&Value::String("value".to_string()))
            );
        }

        #[test]
        fn test_parse_json() {
            let json = r#"{"key": "value"}"#;
            let result = parse_json(json);
            assert!(result.is_ok());
            let fm = result.unwrap();
            assert_eq!(
                fm.0.get("key"),
                Some(&Value::String("value".to_string()))
            );
        }

        #[test]
        fn test_parse_with_options() {
            let yaml = "key: value";
            let result = parse_with_options(yaml, Format::Yaml, None);
            assert!(result.is_ok());
            let fm = result.unwrap();
            assert_eq!(
                fm.0.get("key"),
                Some(&Value::String("value".to_string()))
            );
        }

        #[test]
        fn test_parse_with_invalid_format() {
            let yaml = "key: value";
            let result =
                parse_with_options(yaml, Format::Unsupported, None);
            assert!(matches!(result, Err(Error::ConversionError(_))));
        }
    }

    /// Tests for serialization functions.
    mod serialization_tests {
        use super::*;

        #[test]
        fn test_to_yaml() {
            let fm = create_test_frontmatter();
            let yaml = to_yaml(&fm).unwrap();
            assert!(yaml.contains("title:"));
            assert!(yaml.contains("Test"));
        }

        #[test]
        fn test_to_toml() {
            let fm = create_test_frontmatter();
            let toml = to_toml(&fm).unwrap();
            assert!(toml.contains("title = \"Test\""));
        }

        #[test]
        fn test_to_json_optimised() {
            let fm = create_test_frontmatter();
            let json = to_json_optimised(&fm).unwrap();
            assert!(json.contains("\"title\":\"Test\""));
        }

        #[test]
        fn test_to_string() {
            let fm = create_test_frontmatter();

            // Test YAML format
            let yaml = to_string(&fm, Format::Yaml).unwrap();
            assert!(yaml.contains("title: Test"));

            // Test TOML format
            let toml = to_string(&fm, Format::Toml).unwrap();
            assert!(toml.contains("title = \"Test\""));

            // Test JSON format
            let json = to_string(&fm, Format::Json).unwrap();
            assert!(json.contains("\"title\":\"Test\""));
        }
    }

    /// Tests for validation functions.
    mod validation_tests {
        use super::*;

        #[test]
        fn test_validate_frontmatter_valid() {
            let fm = create_test_frontmatter();
            assert!(validate_frontmatter(
                &fm,
                MAX_NESTING_DEPTH,
                MAX_KEYS
            )
            .is_ok());
        }

        #[test]
        fn test_validate_frontmatter_exceeds_keys() {
            let mut fm = Frontmatter::new();
            for i in 0..MAX_KEYS + 1 {
                let _ = fm.insert(
                    i.to_string(),
                    Value::String("value".to_string()),
                );
            }
            let result =
                validate_frontmatter(&fm, MAX_NESTING_DEPTH, MAX_KEYS);
            assert!(matches!(
                result,
                Err(Error::ContentTooLarge { .. })
            ));
        }

        #[test]
        fn test_validate_frontmatter_exceeds_depth() {
            let mut current = Value::Null;
            for _ in 0..MAX_NESTING_DEPTH + 1 {
                current = Value::Object(Box::new(Frontmatter(
                    [("nested".to_string(), current)]
                        .into_iter()
                        .collect(),
                )));
            }
            let mut fm = Frontmatter::new();
            let _ = fm.insert("deep".to_string(), current);
            let result =
                validate_frontmatter(&fm, MAX_NESTING_DEPTH, MAX_KEYS);
            assert!(matches!(
                result,
                Err(Error::NestingTooDeep { .. })
            ));
        }
    }

    /// Tests for utility functions.
    mod utility_tests {
        use super::*;

        #[test]
        fn test_estimate_json_size() {
            let fm = create_test_frontmatter();
            let estimated_size = estimate_json_size(&fm);
            let actual_json = to_string(&fm, Format::Json).unwrap();
            assert!(estimated_size >= actual_json.len());
        }

        #[test]
        fn test_check_depth_valid() {
            let value =
                Value::Object(Box::new(create_test_frontmatter()));
            assert!(check_depth(&value, 1, MAX_NESTING_DEPTH).is_ok());
        }

        #[test]
        fn test_check_depth_exceeds() {
            let mut current = Value::Null;
            for _ in 0..MAX_NESTING_DEPTH + 1 {
                current = Value::Object(Box::new(Frontmatter(
                    [("nested".to_string(), current)]
                        .into_iter()
                        .collect(),
                )));
            }
            let result = check_depth(&current, 1, MAX_NESTING_DEPTH);
            assert!(matches!(
                result,
                Err(Error::NestingTooDeep { .. })
            ));
        }
    }
}