Add iterator over word indices.

Signed-off-by: Jean-Pierre De Jesus DIAZ <me@jeandudey.tech>
This commit is contained in:
Jean-Pierre De Jesus DIAZ 2023-03-13 11:56:53 +01:00
parent 73f0c112aa
commit 0b92d8db6c
No known key found for this signature in database
GPG Key ID: 6279AEC20A9524EC
1 changed files with 23 additions and 4 deletions

View File

@ -309,7 +309,7 @@ impl Mnemonic {
self.lang self.lang
} }
/// Returns an iterator over the words of the [`Mnemonic`]. /// Returns an iterator over the words of the [Mnemonic].
/// ///
/// # Examples /// # Examples
/// ///
@ -325,15 +325,34 @@ impl Mnemonic {
/// ``` /// ```
pub fn words(&self) -> impl Iterator<Item = &'static str> + Clone + '_ { pub fn words(&self) -> impl Iterator<Item = &'static str> + Clone + '_ {
let list = self.lang.word_list(); let list = self.lang.word_list();
self.words.iter().take_while(|w| **w != EOF).map(move |w| list[*w as usize]) self.word_indices().map(move |i| list[i])
} }
/// Returns an iterator over the words of the [`Mnemonic`]. /// Returns an iterator over the words of the [Mnemonic].
#[deprecated(note = "Use Mnemonic::words instead")] #[deprecated(note = "Use Mnemonic::words instead")]
pub fn word_iter(&self) -> impl Iterator<Item = &'static str> + Clone + '_ { pub fn word_iter(&self) -> impl Iterator<Item = &'static str> + Clone + '_ {
self.words() self.words()
} }
/// Returns an iterator over [Mnemonic] word indices.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bip39::{Language, Mnemonic};
///
/// let list = Language::English.word_list();
/// let mnemonic = Mnemonic::from_entropy(&[0; 32]).unwrap();
/// for i in mnemonic.word_indices() {
/// println!("{} ({})", list[i], i);
/// }
/// ```
pub fn word_indices(&self) -> impl Iterator<Item = usize> + Clone + '_ {
self.words.iter().take_while(|&&w| w != EOF).map(|w| *w as usize)
}
/// Determine the language of the mnemonic as a word iterator. /// Determine the language of the mnemonic as a word iterator.
/// See documentation on [Mnemonic::language_of] for more info. /// See documentation on [Mnemonic::language_of] for more info.
fn language_of_iter<'a, W: Iterator<Item = &'a str>>(words: W) -> Result<Language, Error> { fn language_of_iter<'a, W: Iterator<Item = &'a str>>(words: W) -> Result<Language, Error> {
@ -514,7 +533,7 @@ impl Mnemonic {
/// Get the number of words in the mnemonic. /// Get the number of words in the mnemonic.
pub fn word_count(&self) -> usize { pub fn word_count(&self) -> usize {
self.words.iter().take_while(|w| **w != EOF).count() self.word_indices().count()
} }
/// Convert to seed bytes with a passphrase in normalized UTF8. /// Convert to seed bytes with a passphrase in normalized UTF8.