From 82f553aada5fd4cd3aa6522f7c8d2a2135cc21d6 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Thu, 20 Feb 2025 16:30:31 +0100 Subject: [PATCH] Expose `ScriptBuf`'s `capacity` There are already several methods referring to capacity but none to retrieve it. Those methods also promise certain behavior that mandates having *a* capacity field inside the struct, so no changes in layout will ever remove it. Thus it's OK to expose the field. Aside from exposing the field, this also fixes up the tests to obey the sanity rules. --- primitives/src/script/owned.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/primitives/src/script/owned.rs b/primitives/src/script/owned.rs index 7d33bc770..53dc6d78b 100644 --- a/primitives/src/script/owned.rs +++ b/primitives/src/script/owned.rs @@ -91,6 +91,14 @@ impl ScriptBuf { /// Panics if the new capacity exceeds `isize::MAX bytes`. #[inline] pub fn reserve_exact(&mut self, additional_len: usize) { self.0.reserve_exact(additional_len); } + + /// Returns the number of **bytes** available for writing without reallocation. + /// + /// It is guaranteed that `script.capacity() >= script.len()` always holds. + #[inline] + pub fn capacity(&self) -> usize { + self.0.capacity() + } } impl Deref for ScriptBuf { @@ -161,20 +169,20 @@ mod tests { #[test] fn script_buf_capacity() { let script = ScriptBuf::with_capacity(10); - assert!(script.0.capacity() >= 10); + assert!(script.capacity() >= 10); } #[test] fn script_buf_reserve() { let mut script = ScriptBuf::new(); script.reserve(10); - assert!(script.0.capacity() >= 10); + assert!(script.capacity() >= 10); } #[test] fn script_buf_reserve_exact() { let mut script = ScriptBuf::new(); script.reserve_exact(10); - assert!(script.0.capacity() >= 10); + assert!(script.capacity() >= 10); } }