script: add FromHex and FromStr implementations

This commit is contained in:
Andrew Poelstra 2020-12-28 23:35:38 +00:00 committed by Sebastian
parent 21b2f929c5
commit ffe452ac0b
2 changed files with 19 additions and 3 deletions

View File

@ -25,14 +25,14 @@
//!
use std::default::Default;
use std::{error, fmt, io};
use std::{error, fmt, io, str};
#[cfg(feature = "serde")] use serde;
use hash_types::{PubkeyHash, WPubkeyHash, ScriptHash, WScriptHash};
use blockdata::opcodes;
use consensus::{encode, Decodable, Encodable};
use hashes::Hash;
use hashes::{Hash, hex};
#[cfg(feature="bitcoinconsensus")] use bitcoinconsensus;
#[cfg(feature="bitcoinconsensus")] use std::convert;
#[cfg(feature="bitcoinconsensus")] use OutPoint;
@ -75,6 +75,22 @@ impl fmt::UpperHex for Script {
}
}
impl hex::FromHex for Script {
fn from_byte_iter<I>(iter: I) -> Result<Self, hex::Error>
where I: Iterator<Item=Result<u8, hex::Error>> +
ExactSizeIterator +
DoubleEndedIterator,
{
Vec::from_byte_iter(iter).map(|v| Script(Box::<[u8]>::from(v)))
}
}
impl str::FromStr for Script {
type Err = hex::Error;
fn from_str(s: &str) -> Result<Self, hex::Error> {
hex::FromHex::from_hex(s)
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
/// An object which can be used to construct a script piece by piece
pub struct Builder(Vec<u8>, Option<opcodes::All>);

View File

@ -158,7 +158,7 @@ macro_rules! display_from_debug {
}
#[cfg(test)]
macro_rules! hex_script (($s:expr) => ($crate::blockdata::script::Script::from(<Vec<u8> as $crate::hashes::hex::FromHex>::from_hex($s).unwrap())));
macro_rules! hex_script (($s:expr) => (<$crate::Script as ::std::str::FromStr>::from_str($s).unwrap()));
#[cfg(test)]
macro_rules! hex_hash (($h:ident, $s:expr) => ($h::from_slice(&<Vec<u8> as $crate::hashes::hex::FromHex>::from_hex($s).unwrap()).unwrap()));