keymap.rs

 1use smallvec::SmallVec;
 2use std::{any::TypeId, collections::HashMap};
 3
 4use super::Binding;
 5
 6#[derive(Default)]
 7pub struct Keymap {
 8    bindings: Vec<Binding>,
 9    binding_indices_by_action_id: HashMap<TypeId, SmallVec<[usize; 3]>>,
10}
11
12impl Keymap {
13    pub fn new(bindings: Vec<Binding>) -> Self {
14        let mut binding_indices_by_action_id = HashMap::new();
15        for (ix, binding) in bindings.iter().enumerate() {
16            binding_indices_by_action_id
17                .entry(binding.action().id())
18                .or_insert_with(SmallVec::new)
19                .push(ix);
20        }
21
22        Self {
23            binding_indices_by_action_id,
24            bindings,
25        }
26    }
27
28    pub(crate) fn bindings_for_action(
29        &self,
30        action_id: TypeId,
31    ) -> impl Iterator<Item = &'_ Binding> {
32        self.binding_indices_by_action_id
33            .get(&action_id)
34            .map(SmallVec::as_slice)
35            .unwrap_or(&[])
36            .iter()
37            .map(|ix| &self.bindings[*ix])
38    }
39
40    pub(crate) fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
41        for binding in bindings {
42            self.binding_indices_by_action_id
43                .entry(binding.action().id())
44                .or_default()
45                .push(self.bindings.len());
46            self.bindings.push(binding);
47        }
48    }
49
50    pub(crate) fn clear(&mut self) {
51        self.bindings.clear();
52        self.binding_indices_by_action_id.clear();
53    }
54
55    pub fn bindings(&self) -> &Vec<Binding> {
56        &self.bindings
57    }
58}