keyfork-mnemonic-util: optimize Default::default() for Wordlist

This commit is contained in:
Ryan Heywood 2024-02-18 18:01:51 -05:00
parent 883e0cdf65
commit 31e51f65a5
Signed by: ryan
GPG Key ID: 8E401478A3FBEF72
1 changed files with 22 additions and 9 deletions

View File

@ -48,10 +48,14 @@ impl Error for MnemonicGenerationError {}
#[derive(Debug, Clone)]
pub struct Wordlist(Vec<String>);
static ENGLISH: OnceLock<Wordlist> = OnceLock::new();
impl Default for Wordlist {
/// Returns the English wordlist in the Bitcoin BIP-0039 specification.
fn default() -> Self {
// TODO: English is the only supported language.
ENGLISH
.get_or_init(|| {
let wordlist_file = include_str!("data/wordlist.txt");
Wordlist(
wordlist_file
@ -61,6 +65,9 @@ impl Default for Wordlist {
.map(|x| x.trim().to_string())
.collect(),
)
.shrank()
})
.clone()
}
}
@ -71,6 +78,12 @@ impl Wordlist {
Arc::new(self)
}
/// Return a shrank version of the Wordlist
pub fn shrank(mut self) -> Self {
self.0.shrink_to_fit();
self
}
/// Determine whether the Wordlist contains a given word.
pub fn contains(&self, word: &str) -> bool {
self.0.iter().any(|w| w.as_str() == word)