Merge rust-bitcoin/rust-bitcoin#6767: primitives: Add #[inline] to simple functions
What changed, and why it matters
This commit only adds the Rust compiler hint #[inline] to many small, simple functions in the primitives crate. It does not change any logic, data handling, or security behavior. It is a performance and code-quality change, not a security fix or vulnerability.
No security action needed. Treat as a normal performance/code-quality improvement.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch adds #[inline] attributes to getters, constructors, trait implementations (FromStr, Display, Debug, Error, Arbitrary, Encode), and other small helper functions across primitives. No function bodies, signatures, validation, or control flow were modified. There are no memory-safety, cryptographic, or input-validation changes.
Changed components
primitives/src/block.rsprimitives/src/hash_types/block_hash.rsprimitives/src/hash_types/generic.rsprimitives/src/hash_types/mod.rsprimitives/src/hash_types/script_hash.rsprimitives/src/hash_types/transaction_merkle_node.rsprimitives/src/hash_types/witness_merkle_node.rsprimitives/src/hash_types/witness_script_hash.rsprimitives/src/lib.rsprimitives/src/merkle_tree.rsprimitives/src/opcodes.rsprimitives/src/script/error.rsprimitives/src/script/owned.rsprimitives/src/script/push_bytes.rsprimitives/src/transaction.rsprimitives/src/witness.rsprimitives/src/witness_version.rsInspect captured patch +168 / −0
### primitives/src/block.rs
@@ -306,6 +306,7 @@ impl Block<Unchecked> {
}
/// Checks if Merkle root of header matches Merkle root of the transaction list.
+ #[inline]
pub fn check_merkle_root(&self) -> bool {
match compute_merkle_root(&self.transactions) {
Some(merkle_root) => self.header.merkle_root == merkle_root,
@@ -510,6 +511,7 @@ where
{
type Err = encoding::FromHexError<BlockDecoderError>;
+ #[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> { encoding::decode_from_hex(s) }
}
@@ -709,6 +711,7 @@ impl Header {
/// header.nonce += 1;
/// assert_ne!(header.block_hash(), block_hash);
/// ```
+ #[inline]
pub fn block_hash(&self) -> BlockHash {
let hash = hashes::encode_to_hash::<_, sha256d::HashEngine>(self);
BlockHash::from_byte_array(hash.to_byte_array())
@@ -719,31 +722,36 @@ impl Header {
impl core::str::FromStr for Header {
type Err = encoding::FromHexError<HeaderDecoderError>;
+ #[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> { encoding::decode_from_hex(s) }
}
#[cfg(feature = "hex")]
impl fmt::Display for Header {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&HexPrimitive(self), f)
}
}
#[cfg(feature = "hex")]
impl fmt::LowerHex for Header {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&HexPrimitive(self), f)
}
}
#[cfg(feature = "hex")]
impl fmt::UpperHex for Header {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(&HexPrimitive(self), f)
}
}
impl fmt::Debug for Header {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Header")
.field("block_hash", &self.block_hash())
@@ -760,6 +768,7 @@ impl fmt::Debug for Header {
impl encoding::Encode for Header {
type Encoder<'e> = HeaderEncoder<'e>;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
HeaderEncoder::new(encoding::Encoder6::new(
self.version.encoder(),
@@ -831,6 +840,7 @@ crate::decoder_newtype! {
}
impl HeaderDecoder {
+ #[inline]
fn from_inner(e: <HeaderInnerDecoder as encoding::Decoder>::Error) -> HeaderDecoderError {
match e {
encoding::Decoder6Error::First(e) => HeaderDecoderError::Version(e),
@@ -952,6 +962,7 @@ impl Default for Version {
impl encoding::Encode for Version {
type Encoder<'e> = VersionEncoder<'e>;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
VersionEncoder::new(encoding::ArrayEncoder::without_length_prefix(
self.to_consensus().to_le_bytes(),
@@ -1010,11 +1021,13 @@ pub mod error {
#[cfg(feature = "alloc")]
impl From<Infallible> for BlockDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
#[cfg(feature = "alloc")]
impl fmt::Display for BlockDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "block decoder error"; self.0)
}
@@ -1023,6 +1036,7 @@ pub mod error {
#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
impl std::error::Error for BlockDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
@@ -1043,11 +1057,13 @@ pub mod error {
#[cfg(feature = "alloc")]
impl From<Infallible> for InvalidBlockError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
#[cfg(feature = "alloc")]
impl fmt::Display for InvalidBlockError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::InvalidMerkleRoot =>
@@ -1063,6 +1079,7 @@ pub mod error {
#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
impl std::error::Error for InvalidBlockError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::InvalidMerkleRoot => None,
@@ -1094,10 +1111,12 @@ pub mod error {
}
impl From<Infallible> for HeaderDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for HeaderDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::Version(ref e) => write_err!(f, "header decoder error"; e),
@@ -1112,6 +1131,7 @@ pub mod error {
#[cfg(feature = "std")]
impl std::error::Error for HeaderDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
Self::Version(ref e) => Some(e),
@@ -1131,24 +1151,28 @@ pub mod error {
pub struct VersionDecoderError(pub(super) encoding::UnexpectedEofError);
impl From<Infallible> for VersionDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for VersionDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "version decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for VersionDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
}
#[cfg(feature = "arbitrary")]
#[cfg(feature = "alloc")]
impl<'a> Arbitrary<'a> for Block {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let header = Header::arbitrary(u)?;
let transactions = Vec::<Transaction>::arbitrary(u)?;
@@ -1158,6 +1182,7 @@ impl<'a> Arbitrary<'a> for Block {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Header {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self {
version: Version::arbitrary(u)?,
@@ -1172,6 +1197,7 @@ impl<'a> Arbitrary<'a> for Header {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Version {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
// Equally weight known versions and arbitrary versions
let choice = u.int_in_range(0..=3)?;
### primitives/src/hash_types/block_hash.rs
@@ -69,17 +69,20 @@ crate::decoder_newtype! {
pub struct BlockHashDecoderError(encoding::UnexpectedEofError);
impl From<Infallible> for BlockHashDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for BlockHashDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "block hash decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for BlockHashDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
### primitives/src/hash_types/generic.rs
@@ -13,14 +13,17 @@ const REVERSE: bool = <Inner as hashes::Hash>::DISPLAY_BACKWARD;
impl HashType {
/// Constructs a new type from the underlying byte array.
+ #[inline]
pub const fn from_byte_array(bytes: [u8; LEN]) -> Self {
Self(Inner::from_byte_array(bytes))
}
/// Returns the underlying byte array.
+ #[inline]
pub const fn to_byte_array(self) -> [u8; LEN] { self.0.to_byte_array() }
/// Returns a reference to the underlying byte array.
+ #[inline]
pub const fn as_byte_array(&self) -> &[u8; LEN] { self.0.as_byte_array() }
}
@@ -30,23 +33,27 @@ super::impl_bytelike_traits!(HashType, LEN);
#[cfg(feature = "hex")]
impl fmt::LowerHex for HashType {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
}
#[cfg(feature = "hex")]
impl fmt::UpperHex for HashType {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.0, f) }
}
#[cfg(feature = "hex")]
impl fmt::Display for HashType {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
}
#[cfg(feature = "hex")]
impl str::FromStr for HashType {
type Err = hex::DecodeFixedLengthBytesError;
+ #[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut bytes = crate::hex::decode_to_array(s)?;
@@ -59,6 +66,7 @@ impl str::FromStr for HashType {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for HashType {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let arbitrary_bytes = u.arbitrary()?;
Ok(Self::from_byte_array(arbitrary_bytes))
### primitives/src/hash_types/mod.rs
@@ -58,10 +58,12 @@ macro_rules! impl_bytelike_traits {
}
impl $crate::_export::_core::borrow::Borrow<[u8; { $len }]> for $ty {
+ #[inline]
fn borrow(&self) -> &[u8; { $len }] { self.as_byte_array() }
}
impl $crate::_export::_core::borrow::Borrow<[u8]> for $ty {
+ #[inline]
fn borrow(&self) -> &[u8] { self.as_byte_array() }
}
};
### primitives/src/hash_types/script_hash.rs
@@ -93,6 +93,7 @@ pub struct RedeemScriptSizeError {
#[cfg(feature = "alloc")]
impl RedeemScriptSizeError {
/// Returns the invalid redeem script size.
+ #[inline]
pub fn invalid_size(&self) -> usize { self.size }
}
@@ -112,6 +113,7 @@ impl fmt::Display for RedeemScriptSizeError {
#[cfg(feature = "std")]
impl std::error::Error for RedeemScriptSizeError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
let Self { size: _ } = self;
None
### primitives/src/hash_types/transaction_merkle_node.rs
@@ -30,9 +30,11 @@ include!("./generic.rs");
impl TxMerkleNode {
/// Convert a [`Txid`] hash to a leaf node of the tree.
+ #[inline]
pub fn from_leaf(leaf: Txid) -> Self { MerkleNode::from_leaf(leaf) }
/// Combine two nodes to get a single node. The final node of a tree is called the "root".
+ #[inline]
#[must_use]
pub fn combine(&self, other: &Self) -> Self { MerkleNode::combine(self, other) }
@@ -89,17 +91,20 @@ crate::decoder_newtype! {
pub struct TxMerkleNodeDecoderError(encoding::UnexpectedEofError);
impl From<Infallible> for TxMerkleNodeDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for TxMerkleNodeDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "tx merkle node decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for TxMerkleNodeDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
### primitives/src/hash_types/witness_merkle_node.rs
@@ -30,9 +30,11 @@ include!("./generic.rs");
impl WitnessMerkleNode {
/// Convert a [`Wtxid`] hash to a leaf node of the tree.
+ #[inline]
pub fn from_leaf(leaf: Wtxid) -> Self { MerkleNode::from_leaf(leaf) }
/// Combine two nodes to get a single node. The final node of a tree is called the "root".
+ #[inline]
#[must_use]
pub fn combine(&self, other: &Self) -> Self { MerkleNode::combine(self, other) }
@@ -89,17 +91,20 @@ crate::decoder_newtype! {
pub struct WitnessMerkleNodeDecoderError(encoding::UnexpectedEofError);
impl From<Infallible> for WitnessMerkleNodeDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for WitnessMerkleNodeDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "witness merkle node decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for WitnessMerkleNodeDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
### primitives/src/hash_types/witness_script_hash.rs
@@ -89,6 +89,7 @@ pub struct WitnessScriptSizeError {
#[cfg(feature = "alloc")]
impl WitnessScriptSizeError {
/// Returns the invalid witness script size.
+ #[inline]
pub fn invalid_size(&self) -> usize { self.size }
}
@@ -108,6 +109,7 @@ impl fmt::Display for WitnessScriptSizeError {
#[cfg(feature = "std")]
impl std::error::Error for WitnessScriptSizeError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
let Self { size: _ } = self;
None
### primitives/src/lib.rs
@@ -145,6 +145,7 @@ use encoding::Encoder;
use internals::array_vec::ArrayVec;
// Encode a compact size to a slice without allocating
+#[inline]
#[cfg(feature = "alloc")]
pub(crate) fn compact_size_encode(value: usize) -> ArrayVec<u8, 9> {
let encoder = encoding::CompactSizeEncoder::new(value);
### primitives/src/merkle_tree.rs
@@ -160,8 +160,10 @@ fn calculate_root_batched(mut nodes: Vec<[u8; 32]>) -> Option<[u8; 32]> {
// provided methods in the trait definition.
impl MerkleNode for TxMerkleNode {
type Leaf = Txid;
+ #[inline]
fn from_leaf(leaf: Self::Leaf) -> Self { Self::from_byte_array(leaf.to_byte_array()) }
+ #[inline]
fn combine(&self, other: &Self) -> Self {
let mut encoder = sha256d::Hash::engine();
encoder.input(self.as_byte_array());
@@ -178,8 +180,10 @@ impl MerkleNode for TxMerkleNode {
}
impl MerkleNode for WitnessMerkleNode {
type Leaf = Wtxid;
+ #[inline]
fn from_leaf(leaf: Self::Leaf) -> Self { Self::from_byte_array(leaf.to_byte_array()) }
+ #[inline]
fn combine(&self, other: &Self) -> Self {
let mut encoder = sha256d::Hash::engine();
encoder.input(self.as_byte_array());
### primitives/src/opcodes.rs
@@ -300,6 +300,7 @@ pub(crate) fn fmt_opcode(op: u8, f: &mut fmt::Formatter) -> fmt::Result {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Opcode {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self::from_u8(u8::arbitrary(u)?))
}
### primitives/src/script/error.rs
@@ -19,14 +19,17 @@ pub use super::push_bytes::PushBytesError;
pub struct ScriptBufDecoderError(pub(super) ByteVecDecoderError);
impl From<Infallible> for ScriptBufDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for ScriptBufDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write_err!(f, "decoder error"; self.0) }
}
#[cfg(feature = "std")]
impl std::error::Error for ScriptBufDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
### primitives/src/script/owned.rs
@@ -328,6 +328,7 @@ impl ScriptPubKeyBuf {
/// assert!(script_pubkey.is_p2sh());
/// # Ok::<_, bitcoin_primitives::script::RedeemScriptSizeError>(())
/// ```
+ #[inline]
pub fn new_p2sh(script_hash: ScriptHash) -> Self {
Builder::new()
.push_opcode(OP_HASH160)
@@ -337,6 +338,7 @@ impl ScriptPubKeyBuf {
}
/// Generates pay to anchor output.
+ #[inline]
pub fn new_p2a() -> Self {
super::new_witness_program_unchecked(WitnessVersion::V1, P2A_PROGRAM)
}
### primitives/src/script/push_bytes.rs
@@ -30,9 +30,11 @@ mod primitive {
use super::PushBytesError;
+ #[inline]
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
fn check_limit(_: usize) -> Result<(), PushBytesError> { Ok(()) }
+ #[inline]
#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))]
fn check_limit(len: usize) -> Result<(), PushBytesError> {
if len < 0x1_0000_0000 {
@@ -88,12 +90,15 @@ mod primitive {
impl PushBytes {
/// Constructs an empty `&PushBytes`.
+ #[inline]
pub fn empty() -> &'static Self { Self::from_slice_unchecked(&[]) }
/// Returns the underlying bytes.
+ #[inline]
pub fn as_bytes(&self) -> &[u8] { &self.0 }
/// Returns the underlying mutable bytes.
+ #[inline]
pub fn as_mut_bytes(&mut self) -> &mut [u8] { &mut self.0 }
}
@@ -148,6 +153,7 @@ mod primitive {
impl<'a> TryFrom<&'a [u8]> for &'a PushBytes {
type Error = PushBytesError;
+ #[inline]
fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
check_limit(bytes.len())?;
Ok(PushBytes::from_slice_unchecked(bytes))
@@ -157,6 +163,7 @@ mod primitive {
impl<'a> TryFrom<&'a mut [u8]> for &'a mut PushBytes {
type Error = PushBytesError;
+ #[inline]
fn try_from(bytes: &'a mut [u8]) -> Result<Self, Self::Error> {
check_limit(bytes.len())?;
Ok(PushBytes::from_mut_slice_unchecked(bytes))
@@ -167,6 +174,7 @@ mod primitive {
($($len:literal),* $(,)?) => {
$(
impl<'a> From<&'a [u8; $len]> for &'a PushBytes {
+ #[inline]
fn from(bytes: &'a [u8; $len]) -> Self {
// Check that the macro wasn't called with a wrong number.
const _: () = [(); 1][($len >= 0x100000000u64) as usize];
@@ -175,6 +183,7 @@ mod primitive {
}
impl<'a> From<&'a mut [u8; $len]> for &'a mut PushBytes {
+ #[inline]
fn from(bytes: &'a mut [u8; $len]) -> Self {
// Macro check already above, no need to duplicate.
// We know the size of array statically and we checked macro input.
@@ -183,24 +192,28 @@ mod primitive {
}
impl AsRef<PushBytes> for [u8; $len] {
+ #[inline]
fn as_ref(&self) -> &PushBytes {
self.into()
}
}
impl AsMut<PushBytes> for [u8; $len] {
+ #[inline]
fn as_mut(&mut self) -> &mut PushBytes {
self.into()
}
}
impl From<[u8; $len]> for PushBytesBuf {
+ #[inline]
fn from(bytes: [u8; $len]) -> Self {
PushBytesBuf(Vec::from(&bytes))
}
}
impl<'a> From<&'a [u8; $len]> for PushBytesBuf {
+ #[inline]
fn from(bytes: &'a [u8; $len]) -> Self {
PushBytesBuf(Vec::from(bytes))
}
@@ -241,9 +254,11 @@ mod primitive {
pub const fn new() -> Self { Self(Vec::new()) }
/// Constructs an empty [`PushBytesBuf`] with reserved capacity.
+ #[inline]
pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) }
/// Reserve capacity for `additional_capacity` bytes.
+ #[inline]
pub fn reserve(&mut self, additional_capacity: usize) {
self.0.reserve(additional_capacity);
}
@@ -253,6 +268,7 @@ mod primitive {
/// # Errors
///
/// This method fails if `self` would exceed the limit.
+ #[inline]
#[allow(deprecated)]
pub fn push(&mut self, byte: u8) -> Result<(), PushBytesError> {
// This is OK on 32 bit archs since vec has its own check and this check is pointless.
@@ -266,6 +282,7 @@ mod primitive {
/// # Errors
///
/// This method fails if `self` would exceed the limit.
+ #[inline]
pub fn extend_from_slice(&mut self, bytes: &[u8]) -> Result<(), PushBytesError> {
let len = self.0.len().saturating_add(bytes.len());
check_limit(len)?;
@@ -274,45 +291,54 @@ mod primitive {
}
/// Remove the last byte from buffer if any.
+ #[inline]
pub fn pop(&mut self) -> Option<u8> { self.0.pop() }
/// Remove the byte at `index` and return it.
///
/// # Panics
///
/// This method panics if `index` is out of bounds.
+ #[inline]
#[track_caller]
pub fn remove(&mut self, index: usize) -> u8 { self.0.remove(index) }
/// Remove all bytes from buffer without affecting capacity.
+ #[inline]
pub fn clear(&mut self) { self.0.clear() }
/// Remove bytes from buffer past `len`.
+ #[inline]
pub fn truncate(&mut self, len: usize) { self.0.truncate(len) }
/// Extracts [`PushBytes`] slice
+ #[inline]
pub fn as_push_bytes(&self) -> &PushBytes {
// length guaranteed by our invariant
PushBytes::from_slice_unchecked(&self.0)
}
/// Extracts mutable [`PushBytes`] slice
+ #[inline]
pub fn as_mut_push_bytes(&mut self) -> &mut PushBytes {
// length guaranteed by our invariant
PushBytes::from_mut_slice_unchecked(&mut self.0)
}
/// Accesses inner `Vec` - provided for `super` to impl other methods.
+ #[inline]
pub(super) fn inner(&self) -> &Vec<u8> { &self.0 }
}
impl From<PushBytesBuf> for Vec<u8> {
+ #[inline]
fn from(value: PushBytesBuf) -> Self { value.0 }
}
impl TryFrom<Vec<u8>> for PushBytesBuf {
type Error = PushBytesError;
+ #[inline]
fn try_from(vec: Vec<u8>) -> Result<Self, Self::Error> {
// check len
let _: &PushBytes = vec.as_slice().try_into()?;
@@ -323,6 +349,7 @@ mod primitive {
impl ToOwned for PushBytes {
type Owned = PushBytesBuf;
+ #[inline]
fn to_owned(&self) -> Self::Owned { PushBytesBuf(self.0.to_owned()) }
}
}
@@ -338,62 +365,77 @@ impl Clone for Box<PushBytes> {
impl PushBytes {
/// Returns the number of bytes in buffer.
+ #[inline]
pub fn len(&self) -> usize { self.as_bytes().len() }
/// Returns true if the buffer contains zero bytes.
+ #[inline]
pub fn is_empty(&self) -> bool { self.as_bytes().is_empty() }
}
impl PushBytesBuf {
/// Returns the number of bytes in buffer.
+ #[inline]
pub fn len(&self) -> usize { self.inner().len() }
/// Returns the number of bytes the buffer can contain without reallocating.
+ #[inline]
pub fn capacity(&self) -> usize { self.inner().capacity() }
/// Returns true if the buffer contains zero bytes.
+ #[inline]
pub fn is_empty(&self) -> bool { self.inner().is_empty() }
}
impl AsRef<[u8]> for PushBytes {
+ #[inline]
fn as_ref(&self) -> &[u8] { self.as_bytes() }
}
impl AsMut<[u8]> for PushBytes {
+ #[inline]
fn as_mut(&mut self) -> &mut [u8] { self.as_mut_bytes() }
}
impl Deref for PushBytesBuf {
type Target = PushBytes;
+ #[inline]
fn deref(&self) -> &Self::Target { self.as_push_bytes() }
}
impl DerefMut for PushBytesBuf {
+ #[inline]
fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_push_bytes() }
}
impl AsRef<Self> for PushBytes {
+ #[inline]
fn as_ref(&self) -> &Self { self }
}
impl AsMut<Self> for PushBytes {
+ #[inline]
fn as_mut(&mut self) -> &mut Self { self }
}
impl AsRef<PushBytes> for PushBytesBuf {
+ #[inline]
fn as_ref(&self) -> &PushBytes { self.as_push_bytes() }
}
impl AsMut<PushBytes> for PushBytesBuf {
+ #[inline]
fn as_mut(&mut self) -> &mut PushBytes { self.as_mut_push_bytes() }
}
impl Borrow<PushBytes> for PushBytesBuf {
+ #[inline]
fn borrow(&self) -> &PushBytes { self.as_push_bytes() }
}
impl BorrowMut<PushBytes> for PushBytesBuf {
+ #[inline]
fn borrow_mut(&mut self) -> &mut PushBytes { self.as_mut_push_bytes() }
}
@@ -447,6 +489,7 @@ mod error {
}
impl fmt::Display for PushBytesError {
+ #[inline]
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { match self.never {} }
}
}
@@ -472,6 +515,7 @@ mod error {
}
impl fmt::Display for PushBytesError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
@@ -483,11 +527,13 @@ mod error {
}
impl From<Infallible> for PushBytesError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
#[cfg(feature = "std")]
impl std::error::Error for PushBytesError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
let Self { never: _ } = self;
### primitives/src/transaction.rs
@@ -259,6 +259,7 @@ impl Transaction {
/// transaction. It is impossible to check if the transaction is first in the block, so this
/// function checks the structure of the transaction instead - the previous output must be
/// all-zeros (creates satoshis "out of thin air").
+ #[inline]
#[doc(alias = "is_coin_base")] // method previously had this name
pub fn is_coinbase(&self) -> bool {
self.inputs.len() == 1 && self.inputs[0].previous_output == OutPoint::COINBASE_PREVOUT
@@ -287,12 +288,14 @@ impl cmp::Ord for Transaction {
impl core::str::FromStr for Transaction {
type Err = FromHexError<TransactionDecoderError>;
+ #[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> { encoding::decode_from_hex(s) }
}
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
impl fmt::Display for Transaction {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&HexPrimitive(self), f)
}
@@ -301,6 +304,7 @@ impl fmt::Display for Transaction {
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
impl fmt::LowerHex for Transaction {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&HexPrimitive(self), f)
}
@@ -309,6 +313,7 @@ impl fmt::LowerHex for Transaction {
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
impl fmt::UpperHex for Transaction {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(&HexPrimitive(self), f)
}
@@ -473,13 +478,15 @@ pub struct TransactionDecoder {
#[cfg(feature = "alloc")]
impl TransactionDecoder {
/// Constructs a new [`TransactionDecoder`].
+ #[inline]
pub const fn new() -> Self {
Self { state: TransactionDecoderState::Version(VersionDecoder::new()) }
}
}
#[cfg(feature = "alloc")]
impl Default for TransactionDecoder {
+ #[inline]
fn default() -> Self { Self::new() }
}
@@ -748,6 +755,7 @@ struct WitnessesEncoder<'e> {
#[cfg(feature = "alloc")]
impl<'e> WitnessesEncoder<'e> {
/// Constructs a new encoder for all witnesses in a list of transaction inputs.
+ #[inline]
pub fn new(inputs: &'e [TxIn]) -> Self {
Self { inputs, cur_enc: inputs.first().map(|input| input.witness.encoder()) }
}
@@ -853,6 +861,7 @@ impl encoding::Encode for TxIn {
where
Self: 'e;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
TxInEncoder::new(Encoder3::new(
self.previous_output.encoder(),
@@ -924,6 +933,7 @@ impl encoding::Encode for TxOut {
where
Self: 'e;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
TxOutEncoder::new(Encoder2::new(self.amount.encoder(), self.script_pubkey.encoder()))
}
@@ -1041,6 +1051,7 @@ impl encoding::Encode for OutPoint {
where
Self: 'e;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
OutPointEncoder::new(Encoder2::new(
BytesEncoder::without_length_prefix(self.txid.as_byte_array()),
@@ -1271,6 +1282,7 @@ impl From<Version> for u32 {
impl encoding::Encode for Version {
type Encoder<'e> = VersionEncoder<'e>;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
VersionEncoder::new(encoding::ArrayEncoder::without_length_prefix(
self.to_u32().to_le_bytes(),
@@ -1363,6 +1375,7 @@ pub mod error {
#[cfg(feature = "alloc")]
impl From<Infallible> for TransactionDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
@@ -1400,6 +1413,7 @@ pub mod error {
#[cfg(feature = "std")]
#[cfg(feature = "alloc")]
impl std::error::Error for TransactionDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use TransactionDecoderErrorInner as E;
@@ -1431,11 +1445,13 @@ pub mod error {
#[cfg(feature = "alloc")]
impl From<Infallible> for TxInDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
#[cfg(feature = "alloc")]
impl fmt::Display for TxInDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "txin decoder error"; self.0)
}
@@ -1444,6 +1460,7 @@ pub mod error {
#[cfg(feature = "alloc")]
#[cfg(feature = "std")]
impl std::error::Error for TxInDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
@@ -1456,18 +1473,21 @@ pub mod error {
#[cfg(feature = "alloc")]
impl From<Infallible> for TxOutDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
#[cfg(feature = "alloc")]
impl fmt::Display for TxOutDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "txout decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for TxOutDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
@@ -1476,17 +1496,20 @@ pub mod error {
pub struct OutPointDecoderError(pub(super) encoding::UnexpectedEofError);
impl From<Infallible> for OutPointDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl core::fmt::Display for OutPointDecoderError {
+ #[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write_err!(f, "out point decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for OutPointDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
@@ -1518,6 +1541,7 @@ pub mod error {
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
impl fmt::Display for ParseOutPointError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::Txid(ref e) => write_err!(f, "error parsing TXID"; e),
@@ -1532,6 +1556,7 @@ pub mod error {
#[cfg(feature = "std")]
#[cfg(feature = "hex")]
impl std::error::Error for ParseOutPointError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Txid(e) => Some(e),
@@ -1548,17 +1573,20 @@ pub mod error {
pub struct VersionDecoderError(pub(super) encoding::UnexpectedEofError);
impl From<Infallible> for VersionDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for VersionDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_err!(f, "version decoder error"; self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for VersionDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
}
}
@@ -1604,6 +1632,7 @@ impl<'a> Arbitrary<'a> for Transaction {
#[cfg(feature = "arbitrary")]
#[cfg(feature = "alloc")]
impl<'a> Arbitrary<'a> for TxIn {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self {
previous_output: OutPoint::arbitrary(u)?,
@@ -1617,20 +1646,23 @@ impl<'a> Arbitrary<'a> for TxIn {
#[cfg(feature = "arbitrary")]
#[cfg(feature = "alloc")]
impl<'a> Arbitrary<'a> for TxOut {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self { amount: Amount::arbitrary(u)?, script_pubkey: ScriptPubKeyBuf::arbitrary(u)? })
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for OutPoint {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self { txid: Txid::arbitrary(u)?, vout: u32::arbitrary(u)? })
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Version {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
// Equally weight the case of normal version numbers
let choice = u.int_in_range(0..=3)?;
### primitives/src/witness.rs
@@ -293,6 +293,7 @@ impl Witness {
/// assert_eq!(witness.get_back(3), Some(b"A".as_slice()));
/// assert_eq!(witness.get_back(4), None);
/// ```
+ #[inline]
pub fn get_back(&self, index: usize) -> Option<&[u8]> {
if self.witness_elements <= index {
None
@@ -369,6 +370,7 @@ impl encoding::Encode for Witness {
where
Self: 'e;
+ #[inline]
fn encoder(&self) -> Self::Encoder<'_> {
let num_elements = CompactSizeEncoder::new(self.len());
let witness_elements =
@@ -411,6 +413,7 @@ pub struct WitnessDecoder {
impl WitnessDecoder {
/// Constructs a new witness decoder.
+ #[inline]
pub const fn new() -> Self {
Self {
content: Vec::new(),
@@ -424,6 +427,7 @@ impl WitnessDecoder {
}
impl Default for WitnessDecoder {
+ #[inline]
fn default() -> Self { Self::new() }
}
@@ -698,13 +702,15 @@ impl fmt::Debug for Witness {
/// prefixed with its compact size encoded length.
#[cfg(feature = "hex")]
impl fmt::LowerHex for Witness {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&HexPrimitive(self), f)
}
}
#[cfg(feature = "hex")]
impl fmt::UpperHex for Witness {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(&HexPrimitive(self), f)
}
@@ -902,6 +908,7 @@ impl Default for Witness {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Witness {
+ #[inline]
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let arbitrary_bytes = Vec::<Vec<u8>>::arbitrary(u)?;
Ok(Self::from_slice(&arbitrary_bytes))
@@ -918,6 +925,7 @@ impl<'a> Arbitrary<'a> for Witness {
///
/// The compact size may be bigger than what can be represented in a `usize` on a 16-bit machine but
/// this shouldn't happen if we created the witness because one would get an OOM error before that.
+#[inline]
fn cast_to_usize_if_valid(n: u64) -> Option<usize> {
/// Maximum size, in bytes, of a vector we are allowed to decode.
const MAX_VEC_SIZE: u64 = 4_000_000;
@@ -1033,10 +1041,12 @@ pub mod error {
}
impl From<Infallible> for WitnessDecoderError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for WitnessDecoderError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use WitnessDecoderErrorInner as E;
@@ -1049,6 +1059,7 @@ pub mod error {
#[cfg(feature = "std")]
impl std::error::Error for WitnessDecoderError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use WitnessDecoderErrorInner as E;
@@ -1067,17 +1078,20 @@ pub mod error {
}
impl From<Infallible> for UnexpectedEofError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for UnexpectedEofError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "not enough witness elements for decoder, missing {}", self.missing_elements)
}
}
#[cfg(feature = "std")]
impl std::error::Error for UnexpectedEofError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
let Self { missing_elements: _ } = self;
None
### primitives/src/witness_version.rs
@@ -103,11 +103,13 @@ impl WitnessVersion {
/// NB: this is not the same as an integer representation of the opcode signifying witness
/// version in Bitcoin script. Thus, there is no function to directly convert witness version
/// into a byte since the conversion requires context (Bitcoin script or just a version number).
+ #[inline]
pub fn to_num(self) -> u8 { self as u8 }
}
/// Prints [`WitnessVersion`] number (from 0 to 16) as integer, without any prefix or suffix.
impl fmt::Display for WitnessVersion {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", *self as u8) }
}
@@ -134,6 +136,7 @@ impl fmt::Binary for WitnessVersion {
impl FromStr for WitnessVersion {
type Err = ParseWitnessVersionError;
+ #[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
let version: u8 =
parse_int::int_from_str(s).map_err(ParseWitnessVersionError::Unparsable)?;
@@ -144,6 +147,7 @@ impl FromStr for WitnessVersion {
impl TryFrom<u8> for WitnessVersion {
type Error = InvalidWitnessVersionError;
+ #[inline]
fn try_from(no: u8) -> Result<Self, Self::Error> {
Ok(match no {
0 => Self::V0,
@@ -171,6 +175,7 @@ impl TryFrom<u8> for WitnessVersion {
impl TryFrom<Opcode> for WitnessVersion {
type Error = InvalidWitnessVersionError;
+ #[inline]
fn try_from(opcode: Opcode) -> Result<Self, Self::Error> {
match opcode.to_u8() {
0 => Ok(Self::V0),
@@ -182,6 +187,7 @@ impl TryFrom<Opcode> for WitnessVersion {
}
impl From<WitnessVersion> for Opcode {
+ #[inline]
fn from(version: WitnessVersion) -> Self {
match version {
WitnessVersion::V0 => OP_PUSHBYTES_0,
@@ -241,10 +247,12 @@ pub mod error {
}
impl From<Infallible> for ParseWitnessVersionError {
+ #[inline]
fn from(never: Infallible) -> Self { match never {} }
}
impl fmt::Display for ParseWitnessVersionError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::Unparsable(ref e) => write_err!(f, "integer parse error"; e),
@@ -255,6 +263,7 @@ pub mod error {
#[cfg(feature = "std")]
impl std::error::Error for ParseWitnessVersionError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
Self::Unparsable(ref e) => Some(e),
@@ -273,17 +282,20 @@ pub mod error {
impl InvalidWitnessVersionError {
/// Returns the invalid non-witness version integer.
+ #[inline]
pub fn invalid_version(&self) -> u8 { self.invalid }
}
impl fmt::Display for InvalidWitnessVersionError {
+ #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "invalid witness script version: {}", self.invalid)
}
}
#[cfg(feature = "std")]
impl std::error::Error for InvalidWitnessVersionError {
+ #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
let Self { invalid: _ } = self;
NoneWhy this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.