Skip to content

Commit

Permalink
Use iter instead of accessing content field
Browse files Browse the repository at this point in the history
We would like to move the `Witness` to `primitives` however in the
`Encodable` implementation we are currently accessing the private
`content` field.

Instead of accessing `content` we can iterate over the witness elements
and write each individually, this has the same result but does a bunch
of additional calls to `Write::write_all` (via `emit_slice`).

This patch effects performance negatively but makes no changes to the
encoding.
  • Loading branch information
tcharding committed Oct 1, 2024
1 parent 6389d1c commit 3f3f30d
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions bitcoin/src/blockdata/witness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use arbitrary::{Arbitrary, Unstructured};
use internals::compact_size;
use io::{BufRead, Write};

use crate::consensus::encode::{Error, ReadExt, MAX_VEC_SIZE};
use crate::consensus::{Decodable, Encodable, WriteExt};
use crate::consensus::encode::{self, Error, MAX_VEC_SIZE, ReadExt, WriteExt};
use crate::consensus::{Decodable, Encodable};
use crate::crypto::ecdsa;
use crate::prelude::Vec;
#[cfg(doc)]
Expand Down Expand Up @@ -230,10 +230,13 @@ fn resize_if_needed(vec: &mut Vec<u8>, required_len: usize) {
impl Encodable for Witness {
// `self.content` includes the varints so encoding here includes them, as expected.
fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let content_with_indices_len = self.content.len();
let indices_size = self.len() * 4;
let content_len = content_with_indices_len - indices_size;
Ok(w.emit_compact_size(self.witness_elements)? + w.emit_slice(&self.content[..content_len])?)
let mut written = w.emit_compact_size(self.len())?;

for element in self.iter() {
written += encode::consensus_encode_with_size(element, w)?
}

Ok(written)
}
}

Expand Down

0 comments on commit 3f3f30d

Please sign in to comment.