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,19 +48,26 @@ impl Error for MnemonicGenerationError {}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Wordlist(Vec<String>); pub struct Wordlist(Vec<String>);
static ENGLISH: OnceLock<Wordlist> = OnceLock::new();
impl Default for Wordlist { impl Default for Wordlist {
/// Returns the English wordlist in the Bitcoin BIP-0039 specification. /// Returns the English wordlist in the Bitcoin BIP-0039 specification.
fn default() -> Self { fn default() -> Self {
// TODO: English is the only supported language. // TODO: English is the only supported language.
let wordlist_file = include_str!("data/wordlist.txt"); ENGLISH
Wordlist( .get_or_init(|| {
wordlist_file let wordlist_file = include_str!("data/wordlist.txt");
.lines() Wordlist(
// skip 1: comment at top of file to point to BIP-0039 source. wordlist_file
.skip(1) .lines()
.map(|x| x.trim().to_string()) // skip 1: comment at top of file to point to BIP-0039 source.
.collect(), .skip(1)
) .map(|x| x.trim().to_string())
.collect(),
)
.shrank()
})
.clone()
} }
} }
@ -71,6 +78,12 @@ impl Wordlist {
Arc::new(self) 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. /// Determine whether the Wordlist contains a given word.
pub fn contains(&self, word: &str) -> bool { pub fn contains(&self, word: &str) -> bool {
self.0.iter().any(|w| w.as_str() == word) self.0.iter().any(|w| w.as_str() == word)