Use iter instead of accessing content field

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.
This commit is contained in:
Tobin C. Harding 2024-09-24 10:50:43 +10:00
parent 6389d1cbb3
commit 3f3f30d6c7
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 9 additions and 6 deletions

View File

@ -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)]
@ -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)
}
}