@@ -406,15 +406,17 @@ impl Mnemonic {
406406 }
407407
408408 /// Convert the mnemonic back to the entropy used to generate it.
409- #[ cfg( feature = "std" ) ]
410- pub fn to_entropy ( & self ) -> Vec < u8 > {
409+ /// The return value is a byte array and the size.
410+ /// Use [Mnemonic::to_entropy] (needs `std`) to get a [Vec<u8>].
411+ pub fn to_entropy_array ( & self ) -> ( [ u8 ; 33 ] , usize ) {
411412 // We unwrap errors here because this method can only be called on
412413 // values that were already previously validated.
413414
414415 let language = Mnemonic :: language_of_iter ( self . word_iter ( ) ) . unwrap ( ) ;
415416
416417 // Preallocate enough space for the longest possible word list
417- let mut entropy = Vec :: with_capacity ( 33 ) ;
418+ let mut entropy = [ 0 ; 33 ] ;
419+ let mut cursor = 0 ;
418420 let mut offset = 0 ;
419421 let mut remainder = 0 ;
420422
@@ -426,20 +428,26 @@ impl Mnemonic {
426428 offset += 11 ;
427429
428430 while offset >= 8 {
429- entropy. push ( ( remainder >> 24 ) as u8 ) ;
431+ entropy[ cursor] = ( remainder >> 24 ) as u8 ;
432+ cursor += 1 ;
430433 remainder <<= 8 ;
431434 offset -= 8 ;
432435 }
433436 }
434437
435438 if offset != 0 {
436- entropy. push ( ( remainder >> 24 ) as u8 ) ;
439+ entropy[ cursor ] = ( remainder >> 24 ) as u8 ;
437440 }
438441
439- // Truncate to get rid of the byte containing the checksum
440442 let entropy_bytes = ( nb_words / 3 ) * 4 ;
441- entropy. truncate ( entropy_bytes) ;
442- entropy
443+ ( entropy, entropy_bytes)
444+ }
445+
446+ /// Convert the mnemonic back to the entropy used to generate it.
447+ #[ cfg( feature = "std" ) ]
448+ pub fn to_entropy ( & self ) -> Vec < u8 > {
449+ let ( arr, len) = self . to_entropy_array ( ) ;
450+ arr[ 0 ..len] . to_vec ( )
443451 }
444452}
445453
@@ -669,6 +677,8 @@ mod tests {
669677 "failed vector: {}" , mnemonic_str) ;
670678 assert_eq ! ( & entropy, & mnemonic. to_entropy( ) ,
671679 "failed vector: {}" , mnemonic_str) ;
680+ assert_eq ! ( & entropy, & mnemonic. to_entropy_array( ) . 0 [ 0 ..entropy. len( ) ] ,
681+ "failed vector: {}" , mnemonic_str) ;
672682 }
673683 }
674684 }
0 commit comments