// nixos-config - My current NixOS configuration // // Copyright (C) 2025 Benedikt Peetz // SPDX-License-Identifier: GPL-3.0-or-later // // This file is part of my nixos-config. // // You should have received a copy of the License along with this program. // If not, see . use anyhow::Result; use keymaps::map_tree::{Node, Trie}; use log::{Level, debug, log_enabled, trace}; use map_key::MapKey; pub mod lf_mapping; pub mod map_key; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct MapChild { pub path: String, pub expendable: bool, } impl std::fmt::Display for MapChild { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.path)?; if !self.expendable { f.write_str(" [stop]")?; } Ok(()) } } pub struct MappingsTrie(pub Trie); impl std::fmt::Display for MappingsTrie { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl MappingsTrie { pub fn new() -> Self { Self(Trie::new()) } pub(crate) fn include(&mut self, path: &str) -> Result<()> { let associated_key = MapKey::new_ones_from_path(path, 1); self.insert(&associated_key, path) } pub(crate) fn insert(&mut self, keys: &[MapKey], path: &str) -> Result<()> { let value = Node::new_child(MapChild { path: path.to_owned(), expendable: true, }); self.insert_node(keys, value) } pub(crate) fn insert_node( &mut self, keys: &[MapKey], node: Node, ) -> Result<()> { if let Err(err) = self.0.insert_node(keys, &node) { match err { keymaps::error::TrieInsert::KeyAlreadySet(found_keys) => { // Another node was already inserted with the same key! // So we simple increase the resolution of the other node and this node, until their // keys are no longer equal. // This only includes the last segment of the `MapKey` // // 1. Change both keys, until they are not equal any more // 2. Move the wrongly placed node to the new place. // 3. Insert our node. assert_eq!(keys, found_keys); let mut foreign_keys = vec![found_keys.last().expect("This will exist").clone()]; let mut our_keys = vec![keys.last().expect("This will exist").clone()]; debug!( "'{}' ('{}') and '{}' ('{}') are the same, trying to find a better combination!", MapKey::display(&our_keys), our_keys[0].part_path, MapKey::display(&foreign_keys), foreign_keys[0].part_path, ); our_keys[0].can_tiebreak_with(&foreign_keys[0])?; while our_keys == foreign_keys { our_keys = our_keys[0].increment(our_keys[our_keys.len() - 1].resolution + 1); foreign_keys = foreign_keys[0] .increment(foreign_keys[foreign_keys.len() - 1].resolution + 1); debug!( "Now its: '{}' ('{}') and '{}' ('{}')", MapKey::display(&our_keys), our_keys[0].part_path, MapKey::display(&foreign_keys), foreign_keys[0].part_path, ); } debug!( "Found a better one: '{}' ('{}') and '{}' ('{}')", MapKey::display(&our_keys), our_keys[0].part_path, MapKey::display(&foreign_keys), foreign_keys[0].part_path, ); let parent_keys = &found_keys[..&found_keys.len() - 1]; { if self .0 .get(&found_keys) .expect("This will exist") .value() .is_some() { // This is a child, we must replace it with a parent. let other_node = self .0 .replace_node(&found_keys, Node::new_parent()) .expect("This node exists"); { let mut full_foreign_keys = parent_keys.to_vec(); full_foreign_keys.append(&mut foreign_keys); self.insert_node(&full_foreign_keys, other_node)?; } } } { let mut full_our_keys = parent_keys.to_vec(); full_our_keys.append(&mut our_keys); self.insert_node(&full_our_keys, node)?; } Ok(()) } keymaps::error::TrieInsert::KeyIncludesChild { child_key: key, child_value, } => { // A node that should be a parent was classified // as child before: // // 1. Remove the child node and replace it with a parent one. // 2. Add the child node to the parent node as child, but with a '.' as MapKey. // 3. Add the original node also as child to the parent node. assert_eq!(key, keys); let (fetched_child_value, mut child_key) = self.0.try_get(keys); assert_eq!(fetched_child_value.value(), Some(&child_value)); trace!( "Replacing child ('{}') with a parent, so that we can continue from this point.", MapKey::display(&child_key) ); let child = self .0 .replace_node(&child_key, Node::new_parent()) .expect("Node exists"); assert_eq!(child.value(), Some(&child_value)); child_key.push(MapKey { key: '.', part_path: ".".to_owned(), resolution: 1, }); self.0 .insert_node(&child_key, &child) .expect("We just created a parent here"); // Recursive call, because this key could have hit the previous child directly // (thus it will now trigger the `KeyAlreadySet` error.) self.insert_node(keys, node) } } } else { Ok(()) } } /// Add a new [`MappingsTrie`] at the position `keys` into this Trie. pub(crate) fn add_trie(&mut self, keys: &[MapKey], trie: Self) -> Result<()> { if log_enabled!(Level::Trace) { trace!("Adding mappings under '{}':", MapKey::display(keys)); eprintln!("{trie}"); trace!("Self is:"); eprintln!("{self}"); } let replaced = self .0 .replace_node(keys, trie.0.root_node().to_owned()) .expect("This value exists"); if log_enabled!(Level::Trace) { trace!("After replace adding the new trie"); eprintln!("{self}"); } { let mut new_keys = keys.to_vec(); new_keys.push(MapKey { key: '.', part_path: ".".to_owned(), resolution: 1, }); let mut value = replaced.value().expect("Is a child").clone(); value.expendable = false; trace!("Re-inserting '{}' into self.", MapKey::display(keys)); self.0 .insert_node(&new_keys, &Node::new_child(value)) .expect("This key is not used."); } Ok(()) } }