rsmarisa 0.4.0

Pure Rust port of marisa-trie: a static and space-efficient trie data structure
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
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
926
927
928
929
930
931
932
933
934
935
936
937
//! Trie data structure.
//!
//! Ported from: include/marisa/trie.h and lib/marisa/trie.cc
//!
//! This module provides the main Trie structure, which is a wrapper around
//! the internal LoudsTrie implementation. It provides a safe and convenient
//! public API for trie operations.

use crate::agent::Agent;
use crate::base::{NodeOrder, TailMode};
use crate::grimoire::io::{Reader, Writer};
use crate::grimoire::trie::louds_trie::LoudsTrie;
use crate::keyset::Keyset;

/// Main trie data structure.
///
/// Trie is a static and space-efficient trie implementation that supports:
/// - **Lookup**: Check if a string exists in the trie
/// - **Reverse lookup**: Restore a key from its ID
/// - **Common prefix search**: Find all keys that are prefixes of a query
/// - **Predictive search**: Find all keys that start with a query prefix
///
/// # Examples
///
/// ```
/// use rsmarisa::{Trie, Keyset};
///
/// // Build a trie
/// let mut keyset = Keyset::new();
/// keyset.push_back_str("apple");
/// keyset.push_back_str("application");
/// keyset.push_back_str("apply");
///
/// let mut trie = Trie::new();
/// trie.build(&mut keyset, 0);
///
/// assert_eq!(trie.num_keys(), 3);
/// ```
pub struct Trie {
    /// Internal LOUDS trie implementation.
    trie: Option<Box<LoudsTrie>>,
}

impl Default for Trie {
    fn default() -> Self {
        Self::new()
    }
}

impl Trie {
    /// Creates a new empty trie.
    pub fn new() -> Self {
        Trie { trie: None }
    }

    /// Builds a trie from a keyset.
    ///
    /// # Arguments
    ///
    /// * `keyset` - Keyset containing strings to build the trie from
    /// * `config_flags` - Configuration flags (default: 0)
    ///
    /// # Examples
    ///
    /// ```
    /// use rsmarisa::{Trie, Keyset};
    ///
    /// let mut keyset = Keyset::new();
    /// keyset.push_back_str("hello");
    /// keyset.push_back_str("world");
    ///
    /// let mut trie = Trie::new();
    /// trie.build(&mut keyset, 0);
    /// ```
    pub fn build(&mut self, keyset: &mut Keyset, config_flags: i32) {
        let mut temp = Box::new(LoudsTrie::new());
        temp.build(keyset, config_flags);
        self.trie = Some(temp);
    }

    /// Memory-maps a trie from a file.
    ///
    /// This method uses memory-mapped I/O for efficient loading of large tries.
    /// The file is mapped into memory, and the trie data structures reference
    /// the mapped memory directly, avoiding the need to copy data.
    ///
    /// # Arguments
    ///
    /// * `filename` - Path to the trie file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened/mapped or contains invalid data.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rsmarisa::Trie;
    ///
    /// let mut trie = Trie::new();
    /// trie.mmap("dictionary.marisa").unwrap();
    /// ```
    pub fn mmap(&mut self, filename: &str) -> std::io::Result<()> {
        let mut temp = Box::new(LoudsTrie::new());
        temp.mmap(filename)?;
        self.trie = Some(temp);
        Ok(())
    }

    /// Maps a trie from static memory.
    ///
    /// This method maps a trie from a byte slice that must have static lifetime.
    /// Useful for embedding trie data in the binary or loading from a custom source.
    ///
    /// # Arguments
    ///
    /// * `data` - Static byte slice containing the trie data
    ///
    /// # Errors
    ///
    /// Returns an error if the data is invalid.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use rsmarisa::Trie;
    ///
    /// static TRIE_DATA: &[u8] = include_bytes!("dictionary.marisa");
    ///
    /// let mut trie = Trie::new();
    /// trie.map(TRIE_DATA).unwrap();
    /// ```
    pub fn map(&mut self, data: &'static [u8]) -> std::io::Result<()> {
        let mut temp = Box::new(LoudsTrie::new());
        temp.map(data)?;
        self.trie = Some(temp);
        Ok(())
    }

    /// Loads a trie from a file.
    ///
    /// # Arguments
    ///
    /// * `filename` - Path to the file
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails or file is invalid
    pub fn load(&mut self, filename: &str) -> std::io::Result<()> {
        let mut reader = Reader::open(filename)?;
        self.read(&mut reader)
    }

    /// Reads a trie from a reader.
    ///
    /// # Arguments
    ///
    /// * `reader` - Reader to read from
    ///
    /// # Errors
    ///
    /// Returns an error if reading fails
    pub fn read(&mut self, reader: &mut Reader) -> std::io::Result<()> {
        let mut temp = Box::new(LoudsTrie::new());
        temp.read(reader)?;
        self.trie = Some(temp);
        Ok(())
    }

    /// Saves a trie to a file.
    ///
    /// # Arguments
    ///
    /// * `filename` - Path to the file
    ///
    /// # Errors
    ///
    /// Returns an error if saving fails or trie is empty
    pub fn save(&self, filename: &str) -> std::io::Result<()> {
        if self.trie.is_none() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Cannot save empty trie (not built)",
            ));
        }
        let mut writer = Writer::open(filename)?;
        self.write(&mut writer)
    }

    /// Writes a trie to a writer.
    ///
    /// # Arguments
    ///
    /// * `writer` - Writer to write to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails or trie is empty
    pub fn write(&self, writer: &mut Writer) -> std::io::Result<()> {
        match self.trie.as_ref() {
            Some(trie) => trie.write(writer),
            None => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Cannot write empty trie (not built)",
            )),
        }
    }

    /// Looks up a key in the trie.
    ///
    /// Returns true if the query string exists as a complete key in the trie.
    ///
    /// # Arguments
    ///
    /// * `agent` - Agent with query set
    ///
    /// # Returns
    ///
    /// true if the key exists, false otherwise
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    ///
    /// # Examples
    ///
    /// ```
    /// use rsmarisa::{Trie, Keyset, Agent};
    ///
    /// let mut keyset = Keyset::new();
    /// keyset.push_back_str("apple");
    ///
    /// let mut trie = Trie::new();
    /// trie.build(&mut keyset, 0);
    ///
    /// let mut agent = Agent::new();
    /// agent.set_query_str("apple");
    /// assert!(trie.lookup(&mut agent));
    ///
    /// agent.set_query_str("orange");
    /// assert!(!trie.lookup(&mut agent));
    /// ```
    pub fn lookup(&self, agent: &mut Agent) -> bool {
        let trie = self.trie.as_ref().expect("Trie not built");
        if !agent.has_state() {
            agent
                .init_state()
                .expect("Failed to initialize agent state");
        }
        trie.lookup(agent)
    }

    /// Performs reverse lookup: finds the key corresponding to a key ID.
    ///
    /// # Arguments
    ///
    /// * `agent` - Agent with query ID set
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built) or if the key ID is out of range
    ///
    /// # Examples
    ///
    /// ```
    /// use rsmarisa::{Trie, Keyset, Agent};
    ///
    /// let mut keyset = Keyset::new();
    /// keyset.push_back_str("apple");
    /// keyset.push_back_str("banana");
    ///
    /// let mut trie = Trie::new();
    /// trie.build(&mut keyset, 0);
    ///
    /// let mut agent = Agent::new();
    /// agent.set_query_id(0);
    /// trie.reverse_lookup(&mut agent);
    /// // agent.key() now contains the key for ID 0
    /// ```
    pub fn reverse_lookup(&self, agent: &mut Agent) {
        let trie = self.trie.as_ref().expect("Trie not built");
        if !agent.has_state() {
            agent
                .init_state()
                .expect("Failed to initialize agent state");
        }
        trie.reverse_lookup(agent);
    }

    /// Performs common prefix search.
    ///
    /// Finds keys that are prefixes of the query string.
    /// Call repeatedly to get all matching prefixes.
    ///
    /// # Arguments
    ///
    /// * `agent` - Agent with query set
    ///
    /// # Returns
    ///
    /// true if a match was found, false if no more matches
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    ///
    /// # Examples
    ///
    /// ```
    /// use rsmarisa::{Trie, Keyset, Agent};
    ///
    /// let mut keyset = Keyset::new();
    /// keyset.push_back_str("app");
    /// keyset.push_back_str("apple");
    ///
    /// let mut trie = Trie::new();
    /// trie.build(&mut keyset, 0);
    ///
    /// let mut agent = Agent::new();
    /// agent.set_query_str("application");
    ///
    /// // Find all prefixes - only "app" is a prefix of "application"
    /// // Note: "apple" is NOT a prefix of "application"
    /// assert!(trie.common_prefix_search(&mut agent));
    /// assert_eq!(std::str::from_utf8(agent.key().as_bytes()).unwrap(), "app");
    /// assert!(!trie.common_prefix_search(&mut agent)); // No more matches
    /// ```
    pub fn common_prefix_search(&self, agent: &mut Agent) -> bool {
        let trie = self.trie.as_ref().expect("Trie not built");
        if !agent.has_state() {
            agent
                .init_state()
                .expect("Failed to initialize agent state");
        }
        trie.common_prefix_search(agent)
    }

    /// Performs predictive search.
    ///
    /// Finds keys that start with the query string.
    /// Call repeatedly to get all matching keys.
    ///
    /// # Arguments
    ///
    /// * `agent` - Agent with query set
    ///
    /// # Returns
    ///
    /// true if a match was found, false if no more matches
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    ///
    /// # Examples
    ///
    /// ```
    /// use rsmarisa::{Trie, Keyset, Agent};
    ///
    /// let mut keyset = Keyset::new();
    /// keyset.push_back_str("apple");
    /// keyset.push_back_str("application");
    ///
    /// let mut trie = Trie::new();
    /// trie.build(&mut keyset, 0);
    ///
    /// let mut agent = Agent::new();
    /// agent.set_query_str("app");
    ///
    /// // Find all keys starting with "app"
    /// let mut count = 0;
    /// while trie.predictive_search(&mut agent) {
    ///     count += 1;
    /// }
    /// assert_eq!(count, 2);
    /// ```
    pub fn predictive_search(&self, agent: &mut Agent) -> bool {
        let trie = self.trie.as_ref().expect("Trie not built");
        if !agent.has_state() {
            agent
                .init_state()
                .expect("Failed to initialize agent state");
        }
        trie.predictive_search(agent)
    }

    /// Returns the number of trie levels.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn num_tries(&self) -> usize {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.num_tries()
    }

    /// Returns the number of keys in the trie.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn num_keys(&self) -> usize {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.num_keys()
    }

    /// Returns the number of nodes in the trie.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn num_nodes(&self) -> usize {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.num_nodes()
    }

    /// Returns the tail storage mode.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn tail_mode(&self) -> TailMode {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.tail_mode()
    }

    /// Returns the node ordering mode.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn node_order(&self) -> NodeOrder {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.node_order()
    }

    /// Checks if the trie is empty.
    ///
    /// # Panics
    ///
    /// Panics if the trie is not built
    pub fn empty(&self) -> bool {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.empty()
    }

    /// Returns the number of keys (same as num_keys).
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn size(&self) -> usize {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.size()
    }

    /// Returns the total memory size in bytes.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn total_size(&self) -> usize {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.total_size()
    }

    /// Returns the I/O size for serialization.
    ///
    /// # Panics
    ///
    /// Panics if the trie is empty (not built)
    pub fn io_size(&self) -> usize {
        let trie = self.trie.as_ref().expect("Trie not built");
        trie.io_size()
    }

    /// Clears the trie.
    pub fn clear(&mut self) {
        self.trie = None;
    }

    /// Swaps with another trie.
    pub fn swap(&mut self, other: &mut Trie) {
        std::mem::swap(&mut self.trie, &mut other.trie);
    }
}

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

    #[test]
    fn test_trie_new() {
        // Rust-specific: Test Trie::new() initialization
        let trie = Trie::new();
        assert!(trie.trie.is_none());
    }

    #[test]
    fn test_trie_build() {
        // Rust-specific: Test basic trie building
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("apple");
        let _ = keyset.push_back_str("banana");
        let _ = keyset.push_back_str("cherry");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        assert_eq!(trie.num_keys(), 3);
    }

    #[test]
    fn test_trie_lookup() {
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("app");
        let _ = keyset.push_back_str("apple");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        let mut agent = Agent::new();
        agent.set_query_str("app");
        assert!(trie.lookup(&mut agent), "Should find 'app'");
        println!(
            "Found app: id={}, str={:?}",
            agent.key().id(),
            String::from_utf8_lossy(agent.key().as_bytes())
        );

        agent.set_query_str("apple");
        assert!(trie.lookup(&mut agent), "Should find 'apple'");
        println!(
            "Found apple: id={}, str={:?}",
            agent.key().id(),
            String::from_utf8_lossy(agent.key().as_bytes())
        );

        agent.set_query_str("banana");
        assert!(!trie.lookup(&mut agent), "Should not find 'banana'");
    }

    #[test]
    fn test_trie_reverse_lookup() {
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("a");
        let _ = keyset.push_back_str("b");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        let mut agent = Agent::new();
        agent.set_query_id(0);
        trie.reverse_lookup(&mut agent);
        // Key should be set in agent
        assert!(agent.key().length() > 0);
    }

    #[test]
    fn test_trie_common_prefix_search() {
        // Rust-specific: Test basic common prefix search functionality
        // Test 1: Single-character increments
        {
            let mut keyset = Keyset::new();
            let _ = keyset.push_back_str("a");
            let _ = keyset.push_back_str("ab");
            let _ = keyset.push_back_str("abc");

            let mut trie = Trie::new();
            trie.build(&mut keyset, 0);

            let mut agent = Agent::new();
            agent.set_query_str("abc");

            let mut count = 0;
            while trie.common_prefix_search(&mut agent) {
                count += 1;
                if count > 10 {
                    break;
                }
            }
            assert_eq!(
                count, 3,
                "Expected 3 matches (a, ab, abc) but got {}",
                count
            );
        }

        // Rust-specific: Verify behavior matches C++ marisa with multi-char keys
        // Test 2: Verify "app" and "apple" behavior matches C++ marisa
        // Only "app" should be found as a prefix of "application"
        // ("apple" is NOT a prefix of "application")
        {
            let mut keyset = Keyset::new();
            let _ = keyset.push_back_str("app");
            let _ = keyset.push_back_str("apple");

            let mut trie = Trie::new();
            trie.build(&mut keyset, 0);

            let mut agent = Agent::new();
            agent.set_query_str("application");

            // Should find "app"
            assert!(trie.common_prefix_search(&mut agent));
            assert_eq!(std::str::from_utf8(agent.key().as_bytes()).unwrap(), "app");

            // Should NOT find "apple" (it's not a prefix of "application")
            assert!(!trie.common_prefix_search(&mut agent));
        }
    }

    #[test]
    fn test_trie_predictive_search() {
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("a");
        let _ = keyset.push_back_str("ab");
        let _ = keyset.push_back_str("ac");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        let mut agent = Agent::new();
        agent.set_query_str("a");

        // Note: Full predictive search requires tail support
        // For now, just test that it doesn't crash
        let mut count = 0;
        while trie.predictive_search(&mut agent) {
            count += 1;
            if count > 10 {
                break;
            } // Safety limit
        }
        // Without tail support, we may not get all matches
        assert!(count <= 3);
    }

    #[test]
    fn test_trie_clear() {
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("test");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        trie.clear();
        assert!(trie.trie.is_none());
    }

    #[test]
    fn test_trie_swap() {
        let mut keyset1 = Keyset::new();
        let _ = keyset1.push_back_str("apple");

        let mut trie1 = Trie::new();
        trie1.build(&mut keyset1, 0);

        let mut keyset2 = Keyset::new();
        let _ = keyset2.push_back_str("banana");
        let _ = keyset2.push_back_str("cherry");

        let mut trie2 = Trie::new();
        trie2.build(&mut keyset2, 0);

        trie1.swap(&mut trie2);

        assert_eq!(trie1.num_keys(), 2);
        assert_eq!(trie2.num_keys(), 1);
    }

    #[test]
    fn test_trie_empty() {
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("test");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        assert!(!trie.empty());
    }

    #[test]
    fn test_trie_sizes() {
        let mut keyset = Keyset::new();
        let _ = keyset.push_back_str("test");

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        assert!(trie.total_size() > 0);
        assert!(trie.io_size() > 0);
    }

    #[test]
    fn test_trie_write_read() {
        // Rust-specific: Test Trie serialization with Reader/Writer
        use crate::grimoire::io::{Reader, Writer};

        // Build a trie
        let mut keyset = Keyset::new();
        keyset.push_back_str("app").unwrap();
        keyset.push_back_str("apple").unwrap();
        keyset.push_back_str("application").unwrap();

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        // Write to buffer
        let mut writer = Writer::from_vec(Vec::new());
        trie.write(&mut writer).unwrap();

        let data = writer.into_inner().unwrap();

        // Read back
        let mut reader = Reader::from_bytes(&data);
        let mut trie2 = Trie::new();
        trie2.read(&mut reader).unwrap();

        // Verify structure preserved
        assert_eq!(trie2.num_keys(), 3);
        assert_eq!(trie2.num_nodes(), trie.num_nodes());

        // Verify lookup works
        let mut agent = Agent::new();
        agent.init_state().unwrap();

        agent.set_query_str("app");
        assert!(trie2.lookup(&mut agent));

        agent.set_query_str("apple");
        assert!(trie2.lookup(&mut agent));

        agent.set_query_str("application");
        assert!(trie2.lookup(&mut agent));
    }

    #[test]
    fn test_trie_save_load() {
        // Rust-specific: Test Trie save/load to file
        use std::fs;
        use tempfile::NamedTempFile;

        // Build a trie
        let mut keyset = Keyset::new();
        keyset.push_back_str("hello").unwrap();
        keyset.push_back_str("world").unwrap();

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        // Save to file
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        trie.save(path).unwrap();

        // Verify file exists and has content
        let metadata = fs::metadata(path).unwrap();
        assert!(metadata.len() > 0);

        // Load from file
        let mut trie2 = Trie::new();
        trie2.load(path).unwrap();

        // Verify
        assert_eq!(trie2.num_keys(), 2);

        let mut agent = Agent::new();
        agent.init_state().unwrap();

        agent.set_query_str("hello");
        assert!(trie2.lookup(&mut agent));

        agent.set_query_str("world");
        assert!(trie2.lookup(&mut agent));
    }

    #[test]
    fn test_trie_write_empty_error() {
        // Rust-specific: Test that writing empty trie returns error
        use crate::grimoire::io::Writer;

        let trie = Trie::new();
        let mut writer = Writer::from_vec(Vec::new());
        let result = trie.write(&mut writer);

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidInput);
    }

    #[test]
    fn test_trie_save_empty_error() {
        // Rust-specific: Test that saving empty trie returns error
        use tempfile::NamedTempFile;

        let trie = Trie::new();
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        let result = trie.save(path);

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidInput);
    }

    #[test]
    fn test_trie_read_invalid_header() {
        // Rust-specific: Test that reading invalid header returns error
        use crate::grimoire::io::Reader;

        let invalid_data = vec![0u8; 100]; // Not a valid MARISA file
        let mut reader = Reader::from_bytes(&invalid_data);
        let mut trie = Trie::new();
        let result = trie.read(&mut reader);

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_trie_mmap() {
        // Rust-specific: Test memory-mapped file loading
        use tempfile::NamedTempFile;

        // Build and save a trie
        let mut keyset = Keyset::new();
        keyset.push_back_str("apple").unwrap();
        keyset.push_back_str("application").unwrap();
        keyset.push_back_str("apply").unwrap();

        let mut trie1 = Trie::new();
        trie1.build(&mut keyset, 0);

        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        trie1.save(path).unwrap();

        // Load with mmap
        let mut trie2 = Trie::new();
        trie2.mmap(path).unwrap();

        // Verify structure
        assert_eq!(trie2.num_keys(), 3);
        assert_eq!(trie2.num_nodes(), trie1.num_nodes());

        // Verify lookup works
        let mut agent = Agent::new();
        agent.set_query_str("apple");
        assert!(trie2.lookup(&mut agent));
        assert_eq!(
            std::str::from_utf8(agent.key().as_bytes()).unwrap(),
            "apple"
        );

        agent.set_query_str("application");
        assert!(trie2.lookup(&mut agent));
        assert_eq!(
            std::str::from_utf8(agent.key().as_bytes()).unwrap(),
            "application"
        );

        agent.set_query_str("apply");
        assert!(trie2.lookup(&mut agent));

        agent.set_query_str("banana");
        assert!(!trie2.lookup(&mut agent));
    }

    #[test]
    fn test_trie_mmap_vs_load_equivalence() {
        // Rust-specific: Verify that mmap() and load() produce identical behavior
        use tempfile::NamedTempFile;

        // Build and save a trie
        let mut keyset = Keyset::new();
        keyset.push_back_str("test1").unwrap();
        keyset.push_back_str("test2").unwrap();
        keyset.push_back_str("test3").unwrap();

        let mut trie = Trie::new();
        trie.build(&mut keyset, 0);

        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        trie.save(path).unwrap();

        // Load via read
        let mut trie_load = Trie::new();
        trie_load.load(path).unwrap();

        // Load via mmap
        let mut trie_mmap = Trie::new();
        trie_mmap.mmap(path).unwrap();

        // Verify identical structure
        assert_eq!(trie_load.num_keys(), trie_mmap.num_keys());
        assert_eq!(trie_load.num_nodes(), trie_mmap.num_nodes());

        // Verify identical lookup behavior
        let test_keys = ["test1", "test2", "test3", "nonexistent"];
        for key in &test_keys {
            let mut agent1 = Agent::new();
            let mut agent2 = Agent::new();

            agent1.set_query_str(key);
            agent2.set_query_str(key);

            let result1 = trie_load.lookup(&mut agent1);
            let result2 = trie_mmap.lookup(&mut agent2);

            assert_eq!(result1, result2, "Lookup result mismatch for key: {}", key);
            if result1 {
                assert_eq!(
                    agent1.key().as_bytes(),
                    agent2.key().as_bytes(),
                    "Key bytes mismatch for key: {}",
                    key
                );
                assert_eq!(
                    agent1.key().id(),
                    agent2.key().id(),
                    "Key ID mismatch for key: {}",
                    key
                );
            }
        }
    }

    #[test]
    fn test_trie_mmap_file_not_found() {
        // Rust-specific: Test that mmap with non-existent file returns error
        let mut trie = Trie::new();
        let result = trie.mmap("/nonexistent/file.marisa");

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::NotFound);
    }
}