bevy_input_sequence/cache/
key.rs

1//! Cache the trie for reuse.
2use crate::{input_sequence::InputSequence, KeyChord};
3use bevy::ecs::prelude::Resource;
4use trie_rs::{
5    inc_search::{IncSearch, Position},
6    map::{Trie, TrieBuilder},
7};
8
9/// Contains the trie for gamepad button sequences.
10#[derive(Resource, Default)]
11pub struct KeySequenceCache {
12    trie: Option<Trie<KeyChord, InputSequence<KeyChord, ()>>>,
13    position: Option<Position>,
14}
15
16impl KeySequenceCache {
17    /// Retrieve the cached trie without iterating through `sequences`. Or if
18    /// the cache has been invalidated, build and cache a new trie using the
19    /// `sequences` iterator.
20    pub fn trie<'a>(
21        &mut self,
22        sequences: impl Iterator<Item = &'a InputSequence<KeyChord, ()>>,
23    ) -> &Trie<KeyChord, InputSequence<KeyChord, ()>> {
24        self.trie.get_or_insert_with(|| {
25            let mut builder: TrieBuilder<KeyChord, InputSequence<KeyChord, ()>> =
26                TrieBuilder::new();
27            for sequence in sequences {
28                builder.insert(sequence.acts.clone(), sequence.clone());
29            }
30            // info!(
31            //     "Building trie for {} input sequences.",
32            //     A::short_type_path()
33            // );
34            builder.build()
35        })
36    }
37
38    /// Store a search.
39    pub fn store(&mut self, position: Position) {
40        self.position = Some(position)
41    }
42
43    /// Recall a search OR create a new search.
44    pub fn recall<'a, 'b>(
45        &'b mut self,
46        sequences: impl Iterator<Item = &'a InputSequence<KeyChord, ()>>,
47    ) -> IncSearch<'a, KeyChord, InputSequence<KeyChord, ()>>
48    where
49        'b: 'a,
50    {
51        let position = self.position;
52        let trie = self.trie(sequences);
53        position
54            .map(move |p| IncSearch::resume(trie, p))
55            .unwrap_or_else(move || trie.inc_search())
56    }
57
58    /// Clears the cache.
59    pub fn reset(&mut self) {
60        self.trie = None;
61        self.position = None;
62    }
63}