From e492f94289887b50d0c10f976830d4fbf48d5866 Mon Sep 17 00:00:00 2001 From: Daniel Roberts Date: Sat, 10 May 2025 19:17:50 -0500 Subject: [PATCH 1/2] Update `ScriptBuf::with_capacity` docs Document that `ScriptBuf::with_capacity` may overallocate. --- primitives/src/script/owned.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/src/script/owned.rs b/primitives/src/script/owned.rs index 1732845e0..dc4cd2967 100644 --- a/primitives/src/script/owned.rs +++ b/primitives/src/script/owned.rs @@ -62,7 +62,7 @@ impl ScriptBuf { Script::from_boxed_bytes(self.into_bytes().into_boxed_slice()) } - /// Constructs a new empty script with pre-allocated capacity. + /// Constructs a new empty script with at least the specified capacity. #[inline] pub fn with_capacity(capacity: usize) -> Self { ScriptBuf::from_bytes(Vec::with_capacity(capacity)) From d003d4859251abb01929ccab6009a02e0c96b0cd Mon Sep 17 00:00:00 2001 From: Daniel Roberts Date: Sun, 6 Apr 2025 21:06:17 -0500 Subject: [PATCH 2/2] Add `Builder::with_capacity()` --- bitcoin/src/blockdata/script/builder.rs | 4 ++++ bitcoin/src/blockdata/script/tests.rs | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/bitcoin/src/blockdata/script/builder.rs b/bitcoin/src/blockdata/script/builder.rs index 855d04c61..ec842f7c9 100644 --- a/bitcoin/src/blockdata/script/builder.rs +++ b/bitcoin/src/blockdata/script/builder.rs @@ -21,6 +21,10 @@ impl Builder { #[inline] pub const fn new() -> Self { Builder(ScriptBuf::new(), None) } + /// Constructs a new empty script builder with at least the specified capacity. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { Builder(ScriptBuf::with_capacity(capacity), None) } + /// Returns the length in bytes of the script. pub fn len(&self) -> usize { self.0.len() } diff --git a/bitcoin/src/blockdata/script/tests.rs b/bitcoin/src/blockdata/script/tests.rs index 51d24b25b..8fae24288 100644 --- a/bitcoin/src/blockdata/script/tests.rs +++ b/bitcoin/src/blockdata/script/tests.rs @@ -209,6 +209,13 @@ fn script_builder() { ); } +#[test] +fn script_builder_with_capacity() { + let script = Builder::with_capacity(42); + + assert!(script.into_script().capacity() >= 42); +} + #[test] fn script_generators() { let pubkey = "0234e6a79c5359c613762d537e0e19d86c77c1666d8c9ab050f23acd198e97f93e"