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