Skip to content

Commit 8915a40

Browse files
authored
Merge pull request #205 from EddieHouston/refactor/deserialize-hex
Use deserialize_hex to avoid intermediate Vec allocation
2 parents 5852c0c + dd28a12 commit 8915a40

1 file changed

Lines changed: 18 additions & 10 deletions

File tree

src/daemon.rs

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,14 @@ use std::time::Duration;
1010
use std::{env, fs, io};
1111

1212
use base64::prelude::{Engine, BASE64_STANDARD};
13+
#[cfg(feature = "liquid")]
1314
use bitcoin::hex::FromHex;
1415
use error_chain::ChainedError;
1516
use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator};
1617
use serde_json::{from_str, from_value, Value};
1718

1819
#[cfg(not(feature = "liquid"))]
19-
use bitcoin::consensus::encode::{deserialize, serialize_hex};
20+
use bitcoin::consensus::encode::{deserialize_hex, serialize_hex};
2021
#[cfg(feature = "liquid")]
2122
use elements::encode::{deserialize, serialize_hex};
2223

@@ -63,23 +64,30 @@ fn header_from_value(value: Value) -> Result<BlockHeader> {
6364
let header_hex = value
6465
.as_str()
6566
.chain_err(|| format!("non-string header: {}", value))?;
66-
let header_bytes = Vec::from_hex(header_hex).chain_err(|| "non-hex header")?;
67-
Ok(
68-
deserialize(&header_bytes)
69-
.chain_err(|| format!("failed to parse header {}", header_hex))?,
70-
)
67+
deserialize_value(header_hex)
7168
}
7269

7370
fn block_from_value(value: Value) -> Result<Block> {
7471
let block_hex = value.as_str().chain_err(|| "non-string block")?;
75-
let block_bytes = Vec::from_hex(block_hex).chain_err(|| "non-hex block")?;
76-
Ok(deserialize(&block_bytes).chain_err(|| format!("failed to parse block {}", block_hex))?)
72+
deserialize_value(block_hex)
7773
}
7874

7975
fn tx_from_value(value: Value) -> Result<Transaction> {
8076
let tx_hex = value.as_str().chain_err(|| "non-string tx")?;
81-
let tx_bytes = Vec::from_hex(tx_hex).chain_err(|| "non-hex tx")?;
82-
Ok(deserialize(&tx_bytes).chain_err(|| format!("failed to parse tx {}", tx_hex))?)
77+
deserialize_value(tx_hex)
78+
}
79+
80+
#[cfg(not(feature = "liquid"))]
81+
fn deserialize_value<T: bitcoin::consensus::Decodable>(hex: &str) -> Result<T> {
82+
Ok(deserialize_hex(hex)
83+
.chain_err(|| format!("failed to deserialize {}", std::any::type_name::<T>()))?)
84+
}
85+
86+
#[cfg(feature = "liquid")]
87+
fn deserialize_value<T: elements::encode::Decodable>(hex: &str) -> Result<T> {
88+
let bytes = Vec::from_hex(hex).chain_err(|| "invalid hex")?;
89+
Ok(deserialize(&bytes)
90+
.chain_err(|| format!("failed to deserialize {}", std::any::type_name::<T>()))?)
8391
}
8492

8593
/// Parse JSONRPC error code, if exists.

0 commit comments

Comments
 (0)