From c30d6d12ab64e758c0b69447f4695618777c4350 Mon Sep 17 00:00:00 2001 From: Steven Roose Date: Tue, 3 Dec 2019 22:36:27 +0000 Subject: [PATCH] Implement Encodable for Cow<'static, str> --- src/consensus/encode.rs | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/consensus/encode.rs b/src/consensus/encode.rs index 63a91227..a3cbb320 100644 --- a/src/consensus/encode.rs +++ b/src/consensus/encode.rs @@ -29,11 +29,8 @@ //! big-endian decimals, etc.) //! -use std::{mem, u32}; - -use std::error; -use std::fmt; -use std::io; +use std::{fmt, error, io, mem, u32}; +use std::borrow::Cow; use std::io::{Cursor, Read, Write}; use hashes::hex::ToHex; @@ -518,6 +515,26 @@ impl Decodable for String { } } +// Cow<'static, str> +impl Encodable for Cow<'static, str> { + #[inline] + fn consensus_encode(&self, mut s: S) -> Result { + let b = self.as_bytes(); + let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?; + s.emit_slice(&b)?; + Ok(vi_len + b.len()) + } +} + +impl Decodable for Cow<'static, str> { + #[inline] + fn consensus_decode(d: D) -> Result, Error> { + String::from_utf8(Decodable::consensus_decode(d)?) + .map_err(|_| self::Error::ParseFailed("String was not valid UTF8")) + .map(Cow::Owned) + } +} + // Arrays macro_rules! impl_array { @@ -929,6 +946,10 @@ mod tests { #[test] fn deserialize_strbuf_test() { assert_eq!(deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(), Some("Andrew".to_string())); + assert_eq!( + deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(), + Some(::std::borrow::Cow::Borrowed("Andrew")) + ); } #[test]