Pass byte slice to to_hex (#3307)

Currently we pass a Vec. This requires an extra allocation and copy of all elements if a caller doesn't have a Vec already, which is at least 95% of cases.
Another, a smaller issue, we have a function util::to_hex and some structs implement to_hex() on top of it, so we have a mix of it in the code. This PR introduces a trait and a blanket impl for AsRef<[u8]> which brings a uniform API (obj.to_hex()). One unfortunate case is arrays of size bigger than 32 - Rust doesn't implement AsRef for them so it requires an ugly hack (&array[..]).to_hex().
This commit is contained in:
hashmap
2020-04-24 11:18:26 +02:00
committed by GitHub
parent d8c6eef485
commit 6556dd585d
15 changed files with 98 additions and 86 deletions
+2 -2
View File
@@ -172,7 +172,7 @@ where
#[cfg(test)]
mod tests {
use super::{from_entropy, to_entropy, to_seed};
use crate::util::{from_hex, to_hex};
use crate::util::{from_hex, ToHex};
use rand::{thread_rng, Rng};
struct Test<'a> {
@@ -311,7 +311,7 @@ mod tests {
let tests = tests();
for t in tests.iter() {
assert_eq!(
to_hex(to_seed(t.mnemonic, "TREZOR").unwrap().to_vec()),
(&to_seed(t.mnemonic, "TREZOR").unwrap()[..]).to_hex(),
t.seed.to_string()
);
assert_eq!(
+1 -9
View File
@@ -27,12 +27,12 @@ use crate::blake2::blake2b::blake2b;
use crate::extkey_bip32::{self, ChildNumber};
use serde::{de, ser}; //TODO: Convert errors to use ErrorKind
use crate::util;
use crate::util::secp::constants::SECRET_KEY_SIZE;
use crate::util::secp::key::{PublicKey, SecretKey};
use crate::util::secp::pedersen::Commitment;
use crate::util::secp::{self, Message, Secp256k1, Signature};
use crate::util::static_secp_instance;
use crate::util::ToHex;
use zeroize::Zeroize;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
@@ -195,10 +195,6 @@ impl Identifier {
Ok(Identifier::from_bytes(&bytes))
}
pub fn to_hex(&self) -> String {
util::to_hex(self.0.to_vec())
}
pub fn to_bip_32_string(&self) -> String {
let p = ExtKeychainPath::from_identifier(&self);
let mut retval = String::from("m");
@@ -288,10 +284,6 @@ impl BlindingFactor {
BlindingFactor::from_secret_key(secp::key::ZERO_KEY)
}
pub fn to_hex(&self) -> String {
util::to_hex(self.0.to_vec())
}
pub fn from_hex(hex: &str) -> Result<BlindingFactor, Error> {
let bytes = util::from_hex(hex).unwrap();
Ok(BlindingFactor::from_slice(&bytes))