Skip to content

Commit

Permalink
Preallocate serialized vector of HashPrefixRow
Browse files Browse the repository at this point in the history
This should save 2 reallocation for row since serialize will allocate without
capacity (should be 4) and every time will double, so it will need other 2
re-allocation for a total of 3. While here is 1.

Do the same for HeaderRow.
  • Loading branch information
RCasatta authored and romanz committed Jul 22, 2023
1 parent cfaed09 commit a1e45f1
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::convert::TryFrom;

use bitcoin::blockdata::block::Header as BlockHeader;
use bitcoin::{
consensus::encode::{deserialize, serialize, Decodable, Encodable},
consensus::encode::{deserialize, Decodable, Encodable},
hashes::{hash_newtype, sha256, Hash},
OutPoint, Script, Txid,
};
Expand Down Expand Up @@ -39,6 +39,7 @@ macro_rules! impl_consensus_encoding {
}

const HASH_PREFIX_LEN: usize = 8;
const HEIGHT_SIZE: usize = 4;

type HashPrefix = [u8; HASH_PREFIX_LEN];
type Height = u32;
Expand All @@ -49,9 +50,14 @@ pub(crate) struct HashPrefixRow {
height: Height, // transaction confirmed height
}

const HASH_PREFIX_ROW_SIZE: usize = HASH_PREFIX_LEN + HEIGHT_SIZE;

impl HashPrefixRow {
pub(crate) fn to_db_row(&self) -> db::Row {
serialize(self).into_boxed_slice()
let mut vec = Vec::with_capacity(HASH_PREFIX_ROW_SIZE);
let len = self.consensus_encode(&mut vec).expect("in-memory writers don't error");
debug_assert_eq!(len, HASH_PREFIX_ROW_SIZE);
vec.into_boxed_slice()
}

pub(crate) fn from_db_row(row: &[u8]) -> Self {
Expand Down Expand Up @@ -159,6 +165,8 @@ pub(crate) struct HeaderRow {
pub(crate) header: BlockHeader,
}

const HEADER_ROW_SIZE: usize = 80;

impl_consensus_encoding!(HeaderRow, header);

impl HeaderRow {
Expand All @@ -167,7 +175,10 @@ impl HeaderRow {
}

pub(crate) fn to_db_row(&self) -> db::Row {
serialize(self).into_boxed_slice()
let mut vec = Vec::with_capacity(HEADER_ROW_SIZE);
let len = self.consensus_encode(&mut vec).expect("in-memory writers don't error");
debug_assert_eq!(len, HEADER_ROW_SIZE);
vec.into_boxed_slice()
}

pub(crate) fn from_db_row(row: &[u8]) -> Self {
Expand Down

0 comments on commit a1e45f1

Please sign in to comment.