harper_core/spell/
word_id.rs

1use std::hash::BuildHasher;
2
3use foldhash::fast::FixedState;
4use serde::{Deserialize, Serialize};
5
6use crate::{CharString, CharStringExt};
7
8/// An identifier for a particular word.
9///
10/// It works by hashing the word it represents, normalized to lowercase.
11/// It is meant for situations where you need to refer to a word (or a collection of words),
12/// without storing all of accompanying data (like spelling or metadata).
13#[derive(Hash, Copy, Clone, PartialEq, Eq, PartialOrd, Debug, Serialize, Deserialize)]
14pub struct WordId {
15    hash: u64,
16}
17
18impl WordId {
19    /// Create a Word ID from a character slice.
20    pub fn from_word_chars(chars: impl AsRef<[char]>) -> Self {
21        let normalized = chars.as_ref().normalized();
22        let lower = normalized.to_lower();
23        let hash = FixedState::default().hash_one(lower);
24
25        Self { hash }
26    }
27
28    /// Create a word ID from a string.
29    /// Requires allocation, so use sparingly.
30    pub fn from_word_str(text: impl AsRef<str>) -> Self {
31        let chars: CharString = text.as_ref().chars().collect();
32        Self::from_word_chars(chars)
33    }
34}