From 277223da6a70149a27713b9de169c4f498a2bf83 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Thu, 20 Feb 2025 15:35:17 +0100 Subject: [PATCH] Make `Script` and `ScriptBuf` obey sanity rules The newtype sanity rules (a name I came up with): * Newtypes should have at most one constructor that directly references the inner field. * Newtypes should have at most three accessor methods that directly reference the ineer field: one for owned access, the second for borrowed and the third for mutably borrowed. * All other methods should use the methods above to perform operations on the newtype and not directly access the fields. This commit makes `Script` and `ScriptBuf` obey these except for `reserve` and `reserve_exact` since we don't have `as_mut_vec` method. As a side effect it also adds `const` to `ScriptBuf::from_bytes`. --- primitives/src/script/borrowed.rs | 14 +++++++------- primitives/src/script/mod.rs | 12 ++++++------ primitives/src/script/owned.rs | 16 ++++++++-------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/primitives/src/script/borrowed.rs b/primitives/src/script/borrowed.rs index 6e68a6ef6..b16d1c613 100644 --- a/primitives/src/script/borrowed.rs +++ b/primitives/src/script/borrowed.rs @@ -54,7 +54,7 @@ use crate::prelude::{Box, ToOwned, Vec}; /// #[derive(PartialOrd, Ord, PartialEq, Eq, Hash)] #[repr(transparent)] -pub struct Script(pub(in crate::script) [u8]); +pub struct Script([u8]); impl Default for &Script { #[inline] @@ -64,7 +64,7 @@ impl Default for &Script { impl ToOwned for Script { type Owned = ScriptBuf; - fn to_owned(&self) -> Self::Owned { ScriptBuf(self.0.to_owned()) } + fn to_owned(&self) -> Self::Owned { ScriptBuf::from_bytes(self.to_vec()) } } impl Script { @@ -104,7 +104,7 @@ impl Script { /// Returns a copy of the script data. #[inline] - pub fn to_vec(&self) -> Vec { self.0.to_owned() } + pub fn to_vec(&self) -> Vec { self.as_bytes().to_owned() } /// Returns a copy of the script data. #[inline] @@ -113,11 +113,11 @@ impl Script { /// Returns the length in bytes of the script. #[inline] - pub fn len(&self) -> usize { self.0.len() } + pub fn len(&self) -> usize { self.as_bytes().len() } /// Returns whether the script is the empty script. #[inline] - pub fn is_empty(&self) -> bool { self.0.is_empty() } + pub fn is_empty(&self) -> bool { self.as_bytes().is_empty() } /// Converts a [`Box