tries 0.1.0

Rust implementations of Trie
Documentation
use hashbrown::HashMap;

#[derive(Debug, Clone)]
struct Node {
    children: HashMap<char, Node>,
    is_end: bool,
}

impl Node {
    fn new() -> Self {
        Self {
            children: HashMap::new(),
            is_end: false,
        }
    }
}

/// A simple Trie.
///
/// # Example
///
/// ```
/// use tries::Trie;
///
/// let mut trie = Trie::new();
/// trie.insert("happy");
/// trie.insert("happily");
///
/// assert!(trie.search("happy"));
/// assert!(trie.search("happily"));
/// assert!(!trie.search("hello"));
/// ```
#[derive(Debug, Clone)]
pub struct Trie {
    root: Node,
}

impl Trie {
    /// Create a Trie.
    pub fn new() -> Self {
        Self { root: Node::new() }
    }

    /// Insert a word in Trie.
    ///
    /// # Example
    ///
    /// ```
    /// use tries::Trie;
    ///
    /// let mut trie = Trie::new();
    ///
    /// trie.insert("hello");
    /// ```
    pub fn insert<S: AsRef<str>>(&mut self, word: S) {
        let mut current = &mut self.root;
        for c in word.as_ref().chars() {
            current = current.children.entry(c).or_insert(Node::new());
        }
        current.is_end = true;
    }

    /// Search a word in Trie.
    ///
    /// # Example
    ///
    /// ```
    /// use tries::Trie;
    ///
    /// let mut trie = Trie::new();
    ///
    /// trie.insert("hello");
    ///
    /// assert!(trie.search("hello"));
    /// assert!(!trie.search("ok"))
    /// ```
    pub fn search<S: AsRef<str>>(&mut self, word: S) -> bool {
        let mut current = &self.root;
        for c in word.as_ref().chars() {
            if let Some(node) = current.children.get(&c) {
                current = node;
            } else {
                return false;
            }
        }
        current.is_end
    }
}

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