diff --git a/Cargo.toml b/Cargo.toml index 698f673..a5c5f1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,6 @@ rust-version = "1.36.0" [dependencies] serde = {version = "1", default-features = false } -serde_bytes = { version = "0.11", default-features = false } itoa = {version = "1", default-features = false } [dev-dependencies] @@ -31,9 +30,9 @@ sha1 = "0.10.1" [features] default = ["std"] -std = ["serde/std", "serde_bytes/std"] +std = ["serde/std"] -alloc = ["serde/alloc", "serde_bytes/alloc"] +alloc = ["serde/alloc"] [package.metadata.docs.rs] all-features = true diff --git a/src/bstring.rs b/src/bstring.rs new file mode 100644 index 0000000..179e381 --- /dev/null +++ b/src/bstring.rs @@ -0,0 +1,167 @@ +//! Byte string which helps with the deserialization. + +use core::{ + borrow::{Borrow, BorrowMut}, + cmp, fmt, + ops::{Deref, DerefMut}, +}; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::{string::String, vec::Vec}; +#[cfg(feature = "std")] +use std::{string::String, vec::Vec}; + +use serde::{ + de::{SeqAccess, Visitor}, + Deserialize, Deserializer, +}; + +/// Byte string. +/// +/// Bencoded "strings" are not necessarily UTF-8 encoded values. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BString(Vec); + +impl AsRef<[u8]> for BString { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +impl AsMut<[u8]> for BString { + fn as_mut(&mut self) -> &mut [u8] { + &mut self.0 + } +} + +impl Borrow<[u8]> for BString { + fn borrow(&self) -> &[u8] { + &self.0 + } +} + +impl BorrowMut<[u8]> for BString { + fn borrow_mut(&mut self) -> &mut [u8] { + &mut self.0 + } +} + +impl fmt::Debug for BString { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} + +impl Deref for BString { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for BString { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl<'a> From<&'a [u8]> for BString { + fn from(value: &'a [u8]) -> Self { + Self(Vec::from(value)) + } +} + +impl<'a> From<&'a str> for BString { + fn from(value: &'a str) -> Self { + Self(Vec::from(value)) + } +} + +impl From for BString { + fn from(value: String) -> Self { + Self(Vec::from(value)) + } +} + +impl From> for BString { + fn from(value: Vec) -> Self { + Self(value) + } +} + +impl serde::Serialize for BString { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_bytes(&self.0) + } +} + +struct BStringVisitor; + +impl<'de> Visitor<'de> for BStringVisitor { + type Value = BString; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("byte string") + } + + fn visit_seq(self, mut visitor: V) -> Result + where + V: SeqAccess<'de>, + { + let capacity = cmp::min(visitor.size_hint().unwrap_or_default(), 4096); + let mut bytes = Vec::with_capacity(capacity); + + while let Some(b) = visitor.next_element()? { + bytes.push(b); + } + + Ok(BString::from(bytes)) + } + + fn visit_bytes(self, v: &[u8]) -> Result { + Ok(BString::from(v)) + } + + fn visit_byte_buf(self, v: Vec) -> Result + where + E: serde::de::Error, + { + Ok(BString::from(v)) + } + + fn visit_str(self, v: &str) -> Result + where + E: serde::de::Error, + { + Ok(BString::from(v)) + } + + fn visit_string(self, v: String) -> Result + where + E: serde::de::Error, + { + Ok(BString::from(v)) + } +} + +impl<'de> Deserialize<'de> for BString { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + deserializer.deserialize_byte_buf(BStringVisitor) + } +} + +impl BString { + /// Returns the inner vector. + #[inline] + #[must_use] + pub fn into_vec(self) -> Vec { + self.0 + } +} diff --git a/src/de.rs b/src/de.rs index 3a5e87e..e19751e 100644 --- a/src/de.rs +++ b/src/de.rs @@ -609,8 +609,9 @@ where #[cfg(test)] mod tests { + use crate::BString; + use super::*; - use serde_bytes::ByteBuf; use serde_derive::Deserialize; #[cfg(all(feature = "alloc", not(feature = "std")))] @@ -834,11 +835,11 @@ mod tests { #[test] fn test_deserialize_integer_as_raw_bytes() -> Result<()> { #[derive(Debug, PartialEq, Deserialize)] - struct S(ByteBuf); + struct S(BString); let input = "i-1234e"; let s: S = from_slice(input.as_bytes())?; - let expected = S(ByteBuf::from(input.as_bytes().to_vec())); + let expected = S(BString::from(input.as_bytes().to_vec())); assert_eq!(s, expected); Ok(()) } @@ -846,11 +847,11 @@ mod tests { #[test] fn test_deserialize_list_as_raw_bytes() -> Result<()> { #[derive(Debug, PartialEq, Deserialize)] - struct S(ByteBuf); + struct S(BString); let input = "l4:spam4:eggse"; let s: S = from_slice(input.as_bytes())?; - let expected = S(ByteBuf::from(input.as_bytes().to_vec())); + let expected = S(BString::from(input.as_bytes().to_vec())); assert_eq!(s, expected); Ok(()) } @@ -859,13 +860,13 @@ mod tests { fn test_deserialize_map_value_as_raw_bytes() -> Result<()> { #[derive(Debug, PartialEq, Deserialize)] struct S { - spam: ByteBuf, + spam: BString, } let input = "d4:spamd1:a1:bee"; let s: S = from_slice(input.as_bytes())?; let expected = S { - spam: ByteBuf::from(b"d1:a1:be".to_vec()), + spam: BString::from(b"d1:a1:be".to_vec()), }; assert_eq!(s, expected); Ok(()) @@ -874,11 +875,11 @@ mod tests { #[test] fn test_deserialize_map_as_raw_bytes() -> Result<()> { #[derive(Debug, PartialEq, Deserialize)] - struct S(ByteBuf); + struct S(BString); let input = "d4:spamd1:a1:bee"; let s: S = from_slice(input.as_bytes())?; - let expected = S(ByteBuf::from(input.as_bytes().to_vec())); + let expected = S(BString::from(input.as_bytes().to_vec())); assert_eq!(s, expected); Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index f6fa40b..3d91bf4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -105,6 +105,7 @@ extern crate alloc; #[macro_use] extern crate serde; +mod bstring; mod de; mod error; @@ -114,6 +115,8 @@ pub mod write; mod ser; pub mod value; +#[doc(inline)] +pub use bstring::BString; #[doc(inline)] pub use de::{from_slice, Deserializer}; #[doc(inline)] diff --git a/src/read.rs b/src/read.rs index 03a7df7..3d66f61 100644 --- a/src/read.rs +++ b/src/read.rs @@ -50,7 +50,7 @@ pub trait Read<'a> { /// Returns the next byte but does not consume. /// - /// Repeated peeks (with no [next()][Read::next] call) should return the same byte. + /// Repeated peeks (with no [`next()`][Read::next] call) should return the same byte. fn peek(&mut self) -> Option>; /// Returns the position in the stream of bytes. diff --git a/src/ser.rs b/src/ser.rs index 0f1d459..728d12a 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -636,8 +636,9 @@ impl<'a> ser::Serializer for &'a mut MapKeySerializer { #[cfg(test)] mod tests { + use crate::BString; + use super::*; - use serde_bytes::ByteBuf; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{format, string::String, vec}; @@ -772,7 +773,7 @@ mod tests { #[test] fn test_serialize_bytes() { - let value = ByteBuf::from(String::from("123").into_bytes()); + let value = BString::from(String::from("123").into_bytes()); assert_eq!(to_vec(&&value).unwrap(), String::from("3:123").into_bytes()); } diff --git a/src/value.rs b/src/value.rs index 73d6251..e9f80a4 100644 --- a/src/value.rs +++ b/src/value.rs @@ -1,12 +1,11 @@ //! Represents valid Bencode data. -use crate::error::Error; +use crate::{error::Error, BString}; use core::fmt::Display; use serde::{ de::{Deserialize, DeserializeOwned, MapAccess, SeqAccess, Visitor}, ser::Serialize, }; -use serde_bytes::ByteBuf; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{collections::BTreeMap, fmt, str, str::FromStr, string::String, vec::Vec}; @@ -102,19 +101,19 @@ pub enum Value { /// /// Encoded strings can contain non-UTF-8 bytes, so a byte string is used to represent /// "strings". - ByteStr(ByteBuf), + ByteStr(BString), /// An integer which can be signed or unsigned. Int(Number), /// A list of values. List(Vec), /// A dictionary of values. - Dict(BTreeMap), + Dict(BTreeMap), } impl Value { /// If the value is a byte string, returns a reference to the underlying value. #[must_use] - pub fn as_byte_str(&self) -> Option<&ByteBuf> { + pub fn as_byte_str(&self) -> Option<&BString> { match self { Value::ByteStr(b) => Some(b), _ => None, @@ -123,7 +122,7 @@ impl Value { /// If the value is a byte string, returns a mutable reference to the underlying value. #[must_use] - pub fn as_byte_str_mut(&mut self) -> Option<&mut ByteBuf> { + pub fn as_byte_str_mut(&mut self) -> Option<&mut BString> { match self { Value::ByteStr(ref mut b) => Some(b), _ => None, @@ -195,7 +194,7 @@ impl Value { /// If the value is a dictionary, returns a reference to the underlying value. #[must_use] - pub fn as_dict(&self) -> Option<&BTreeMap> { + pub fn as_dict(&self) -> Option<&BTreeMap> { match self { Value::Dict(d) => Some(d), _ => None, @@ -204,7 +203,7 @@ impl Value { /// If the value is a dictionary, returns a mutable reference to the underlying value. #[must_use] - pub fn as_dict_mut(&mut self) -> Option<&mut BTreeMap> { + pub fn as_dict_mut(&mut self) -> Option<&mut BTreeMap> { match self { Value::Dict(ref mut d) => Some(d), _ => None, @@ -256,7 +255,7 @@ impl Value { impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - struct DebugByteStr<'a>(&'a ByteBuf); + struct DebugByteStr<'a>(&'a BString); impl<'a> fmt::Debug for DebugByteStr<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -272,7 +271,7 @@ impl fmt::Debug for Value { Value::Int(arg0) => f.debug_tuple("Int").field(arg0).finish(), Value::List(arg0) => f.debug_tuple("List").field(arg0).finish(), Value::Dict(arg0) => { - struct DebugDict<'a>(&'a BTreeMap); + struct DebugDict<'a>(&'a BTreeMap); impl<'a> fmt::Debug for DebugDict<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -354,19 +353,19 @@ impl FromStr for Value { type Err = Error; fn from_str(s: &str) -> Result { - Ok(Value::ByteStr(ByteBuf::from(String::from(s)))) + Ok(Value::ByteStr(BString::from(String::from(s)))) } } impl<'a> From<&'a str> for Value { fn from(other: &'a str) -> Value { - Value::ByteStr(ByteBuf::from(other)) + Value::ByteStr(BString::from(other)) } } impl From for Value { fn from(other: String) -> Value { - Value::ByteStr(ByteBuf::from(other)) + Value::ByteStr(BString::from(other)) } } @@ -376,7 +375,7 @@ impl> From> for Value { } } -impl, V: Into> From> for Value { +impl, V: Into> From> for Value { fn from(other: BTreeMap) -> Value { Value::Dict( other @@ -415,22 +414,22 @@ impl<'de> Deserialize<'de> for Value { #[inline] fn visit_str(self, value: &str) -> Result { - Ok(Value::ByteStr(ByteBuf::from(String::from(value)))) + Ok(Value::ByteStr(BString::from(String::from(value)))) } #[inline] fn visit_string(self, value: String) -> Result { - Ok(Value::ByteStr(ByteBuf::from(value))) + Ok(Value::ByteStr(BString::from(value))) } #[inline] fn visit_bytes(self, value: &[u8]) -> Result { - Ok(Value::ByteStr(ByteBuf::from(value))) + Ok(Value::ByteStr(BString::from(value))) } #[inline] fn visit_byte_buf(self, value: Vec) -> Result { - Ok(Value::ByteStr(ByteBuf::from(value))) + Ok(Value::ByteStr(BString::from(value))) } #[inline] @@ -528,7 +527,7 @@ where /// # Errors /// /// Serialization can fail if `T`'s implementation of -/// [Serialize][serde::ser::Serialize] decides to fail, if `T` contains +/// [`Serialize`] decides to fail, if `T` contains /// unsupported types for serialization, or if `T` contains a map with /// non-string keys. #[allow(clippy::module_name_repetitions)] @@ -554,7 +553,7 @@ mod tests { fn test_deserialize_string() -> Result<()> { let input = "4:spam"; let v: Value = crate::de::from_slice(input.as_bytes())?; - assert_eq!(v, Value::ByteStr(ByteBuf::from(String::from("spam")))); + assert_eq!(v, Value::ByteStr(BString::from(String::from("spam")))); Ok(()) } @@ -589,8 +588,8 @@ mod tests { assert_eq!( v, Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("spam"))), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + Value::ByteStr(BString::from(String::from("spam"))), + Value::ByteStr(BString::from(String::from("eggs"))), ]) ); Ok(()) @@ -603,12 +602,12 @@ mod tests { let mut expected = BTreeMap::new(); expected.insert( - ByteBuf::from(String::from("cow")), - Value::ByteStr(ByteBuf::from(String::from("moo"))), + BString::from(String::from("cow")), + Value::ByteStr(BString::from(String::from("moo"))), ); expected.insert( - ByteBuf::from(String::from("spam")), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + BString::from(String::from("spam")), + Value::ByteStr(BString::from(String::from("eggs"))), ); assert_eq!(v, Value::Dict(expected)); Ok(()) @@ -620,10 +619,10 @@ mod tests { let v: Value = crate::de::from_slice(input.as_bytes())?; let mut expected = BTreeMap::new(); expected.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); assert_eq!(v, Value::Dict(expected)); @@ -634,7 +633,7 @@ mod tests { #[cfg(feature = "std")] fn test_serialize_string() -> Result<()> { let expected = "4:spam"; - let v: Vec = crate::ser::to_vec(&Value::ByteStr(ByteBuf::from(String::from("spam"))))?; + let v: Vec = crate::ser::to_vec(&Value::ByteStr(BString::from(String::from("spam"))))?; assert_eq!(v, expected.to_string().into_bytes()); Ok(()) } @@ -671,8 +670,8 @@ mod tests { fn test_serialize_list() -> Result<()> { let expected = "l4:spam4:eggse"; let v: Vec = crate::ser::to_vec(&Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("spam"))), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + Value::ByteStr(BString::from(String::from("spam"))), + Value::ByteStr(BString::from(String::from("eggs"))), ]))?; assert_eq!(v, expected.to_string().into_bytes()); Ok(()) @@ -684,12 +683,12 @@ mod tests { let expected = "d3:cow3:moo4:spam4:eggse"; let mut dict = BTreeMap::new(); dict.insert( - ByteBuf::from(String::from("cow")), - Value::ByteStr(ByteBuf::from(String::from("moo"))), + BString::from(String::from("cow")), + Value::ByteStr(BString::from(String::from("moo"))), ); dict.insert( - ByteBuf::from(String::from("spam")), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + BString::from(String::from("spam")), + Value::ByteStr(BString::from(String::from("eggs"))), ); let v: Vec = crate::ser::to_vec(&Value::Dict(dict))?; assert_eq!(v, expected.to_string().into_bytes()); @@ -702,10 +701,10 @@ mod tests { let expected = "d4:spaml1:a1:bee"; let mut dict = BTreeMap::new(); dict.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); let v: Vec = crate::ser::to_vec(&Value::Dict(dict))?; diff --git a/src/value/de.rs b/src/value/de.rs index ba7ff9d..78be6fb 100644 --- a/src/value/de.rs +++ b/src/value/de.rs @@ -2,9 +2,9 @@ use super::{Number, Value}; use crate::error::Error; +use crate::BString; use serde::de::{DeserializeSeed, IntoDeserializer, MapAccess, SeqAccess, Visitor}; use serde::forward_to_deserialize_any; -use serde_bytes::ByteBuf; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{borrow::Cow, collections::BTreeMap, vec}; @@ -154,7 +154,7 @@ impl<'de> SeqAccess<'de> for ListDeserializer { } struct DictDeserializer { - iter: as IntoIterator>::IntoIter, + iter: as IntoIterator>::IntoIter, value: Option, } @@ -196,7 +196,7 @@ impl<'de> MapAccess<'de> for DictDeserializer { } struct DictKey<'a> { - key: Cow<'a, ByteBuf>, + key: Cow<'a, BString>, } impl<'de> serde::Deserializer<'de> for DictKey<'de> { @@ -373,7 +373,7 @@ impl<'a> SeqAccess<'a> for ListRefDeserializer<'a> { } struct DictRefDeserializer<'a> { - iter: <&'a BTreeMap as IntoIterator>::IntoIter, + iter: <&'a BTreeMap as IntoIterator>::IntoIter, value: Option<&'a Value>, } @@ -426,7 +426,7 @@ mod tests { #[test] fn test_deserialize_string() -> Result<()> { - let v = Value::ByteStr(ByteBuf::from(String::from("spam"))); + let v = Value::ByteStr(BString::from(String::from("spam"))); let s: String = from_value(v)?; assert_eq!("spam", s); Ok(()) @@ -434,9 +434,9 @@ mod tests { #[test] fn test_deserialize_byte_str() -> Result<()> { - let v = Value::ByteStr(ByteBuf::from(String::from("spam"))); - let b: ByteBuf = from_value(v)?; - assert_eq!(ByteBuf::from(String::from("spam")), b); + let v = Value::ByteStr(BString::from(String::from("spam"))); + let b: BString = from_value(v)?; + assert_eq!(BString::from(String::from("spam")), b); Ok(()) } @@ -467,8 +467,8 @@ mod tests { #[test] fn test_deserialize_list() -> Result<()> { let v = Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("spam"))), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + Value::ByteStr(BString::from(String::from("spam"))), + Value::ByteStr(BString::from(String::from("eggs"))), ]); let v: Vec = from_value(v)?; assert_eq!(v, vec!["spam", "eggs"]); @@ -479,12 +479,12 @@ mod tests { fn test_deserialize_dict_1() -> Result<()> { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("cow")), - Value::ByteStr(ByteBuf::from(String::from("moo"))), + BString::from(String::from("cow")), + Value::ByteStr(BString::from(String::from("moo"))), ); m.insert( - ByteBuf::from(String::from("spam")), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + BString::from(String::from("spam")), + Value::ByteStr(BString::from(String::from("eggs"))), ); let d = Value::Dict(m); let d: BTreeMap = from_value(d)?; @@ -502,12 +502,12 @@ mod tests { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("cow")), - Value::ByteStr(ByteBuf::from(String::from("moo"))), + BString::from(String::from("cow")), + Value::ByteStr(BString::from(String::from("moo"))), ); m.insert( - ByteBuf::from(String::from("spam")), - Value::ByteStr(ByteBuf::from(String::from("eggs"))), + BString::from(String::from("spam")), + Value::ByteStr(BString::from(String::from("eggs"))), ); let d = Value::Dict(m); let d = BTreeMap::<&str, &str>::deserialize(&d)?; @@ -523,10 +523,10 @@ mod tests { fn test_deserialize_dict_2() -> Result<()> { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); let d = Value::Dict(m); @@ -547,10 +547,10 @@ mod tests { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); let d = Value::Dict(m); @@ -568,10 +568,10 @@ mod tests { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); let d = Value::Dict(m); @@ -587,10 +587,10 @@ mod tests { fn test_deserialize_dict_3() -> Result<()> { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); let d = Value::Dict(m); @@ -600,8 +600,8 @@ mod tests { expected.insert( String::from("spam"), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); assert_eq!(d, expected); @@ -612,10 +612,10 @@ mod tests { fn test_deserialize_dict_4() -> Result<()> { let mut m = BTreeMap::new(); m.insert( - ByteBuf::from(String::from("spam")), + BString::from(String::from("spam")), Value::List(vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ]), ); let d = Value::Dict(m); @@ -625,8 +625,8 @@ mod tests { expected.insert( String::from("spam"), vec![ - Value::ByteStr(ByteBuf::from(String::from("a"))), - Value::ByteStr(ByteBuf::from(String::from("b"))), + Value::ByteStr(BString::from(String::from("a"))), + Value::ByteStr(BString::from(String::from("b"))), ], ); assert_eq!(d, expected); diff --git a/src/value/index.rs b/src/value/index.rs index 912c91b..cae788c 100644 --- a/src/value/index.rs +++ b/src/value/index.rs @@ -2,7 +2,6 @@ use super::Value; use core::ops; -use serde_bytes::Bytes; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::String; @@ -37,14 +36,14 @@ impl Index for usize { impl Index for str { fn index<'a>(&self, v: &'a Value) -> Option<&'a Value> { match v { - Value::Dict(ref d) => d.get(Bytes::new(self.as_bytes())), + Value::Dict(ref d) => d.get(self.as_bytes()), _ => None, } } fn index_mut<'a>(&self, v: &'a mut Value) -> Option<&'a mut Value> { match v { - Value::Dict(ref mut d) => d.get_mut(Bytes::new(self.as_bytes())), + Value::Dict(ref mut d) => d.get_mut(self.as_bytes()), _ => None, } } diff --git a/src/value/ser.rs b/src/value/ser.rs index 4d31b7a..7b203c0 100644 --- a/src/value/ser.rs +++ b/src/value/ser.rs @@ -1,9 +1,11 @@ //! Serializes into a [Value]. use super::{Number, Value}; -use crate::error::{Error, ErrorKind, Result}; +use crate::{ + error::{Error, ErrorKind, Result}, + BString, +}; use serde::{ser, Serialize}; -use serde_bytes::ByteBuf; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{collections::BTreeMap, vec::Vec}; @@ -87,12 +89,12 @@ impl ser::Serializer for Serializer { #[inline] fn serialize_str(self, value: &str) -> Result { - Ok(Value::ByteStr(ByteBuf::from(value))) + Ok(Value::ByteStr(BString::from(value))) } #[inline] fn serialize_bytes(self, value: &[u8]) -> Result { - Ok(Value::ByteStr(ByteBuf::from(value))) + Ok(Value::ByteStr(BString::from(value))) } #[inline] @@ -235,8 +237,8 @@ impl ser::SerializeSeq for SerializeList { } pub(super) struct SerializeDict { - dict: BTreeMap, - current_key: Option, + dict: BTreeMap, + current_key: Option, } impl ser::SerializeMap for SerializeDict { @@ -299,16 +301,16 @@ impl ser::SerializeStruct for SerializeDict { struct DictKeySerializer; impl ser::Serializer for &mut DictKeySerializer { - type Ok = ByteBuf; + type Ok = BString; type Error = Error; - type SerializeSeq = ser::Impossible; - type SerializeTuple = ser::Impossible; - type SerializeTupleStruct = ser::Impossible; - type SerializeTupleVariant = ser::Impossible; - type SerializeMap = ser::Impossible; - type SerializeStruct = ser::Impossible; - type SerializeStructVariant = ser::Impossible; + type SerializeSeq = ser::Impossible; + type SerializeTuple = ser::Impossible; + type SerializeTupleStruct = ser::Impossible; + type SerializeTupleVariant = ser::Impossible; + type SerializeMap = ser::Impossible; + type SerializeStruct = ser::Impossible; + type SerializeStructVariant = ser::Impossible; fn serialize_bool(self, _value: bool) -> Result { Err(Error::with_kind(ErrorKind::UnsupportedType)) @@ -360,11 +362,11 @@ impl ser::Serializer for &mut DictKeySerializer { } fn serialize_str(self, value: &str) -> Result { - Ok(ByteBuf::from(value)) + Ok(BString::from(value)) } fn serialize_bytes(self, value: &[u8]) -> Result { - Ok(ByteBuf::from(value)) + Ok(BString::from(value)) } fn serialize_unit(self) -> Result { @@ -463,7 +465,6 @@ impl ser::Serializer for &mut DictKeySerializer { mod tests { use super::*; use crate::to_value; - use serde_bytes::ByteBuf; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{string::String, vec}; @@ -583,7 +584,7 @@ mod tests { let value: char = 'a'; assert_eq!( to_value(&value).unwrap(), - Value::ByteStr(ByteBuf::from("a")) + Value::ByteStr(BString::from("a")) ); } @@ -592,7 +593,7 @@ mod tests { let value: &str = "Hello world!"; assert_eq!( to_value(&value).unwrap(), - Value::ByteStr(ByteBuf::from(value)) + Value::ByteStr(BString::from(value)) ); } @@ -601,13 +602,13 @@ mod tests { let value: &str = ""; assert_eq!( to_value(&value).unwrap(), - Value::ByteStr(ByteBuf::from(value)) + Value::ByteStr(BString::from(value)) ); } #[test] fn test_serialize_bytes() { - let value = ByteBuf::from(String::from("123").into_bytes()); + let value = BString::from(String::from("123").into_bytes()); assert_eq!(to_value(&&value).unwrap(), Value::ByteStr(value)); } @@ -729,12 +730,12 @@ mod tests { }; let mut expected = BTreeMap::new(); expected.insert( - ByteBuf::from(String::from("int")), + BString::from(String::from("int")), Value::Int(Number::Unsigned(3)), ); expected.insert( - ByteBuf::from(String::from("s")), - Value::ByteStr(ByteBuf::from(String::from("Hello, World!"))), + BString::from(String::from("s")), + Value::ByteStr(BString::from(String::from("Hello, World!"))), ); assert_eq!(to_value(&test).unwrap(), Value::Dict(expected)); diff --git a/tests/de.rs b/tests/de.rs index 1213298..e1b7a80 100644 --- a/tests/de.rs +++ b/tests/de.rs @@ -1,4 +1,4 @@ -use bt_bencode::{Error, Value}; +use bt_bencode::{BString, Error, Value}; use serde::Deserialize; use serde_derive::Deserialize; @@ -52,7 +52,7 @@ fn test_deserialize_info_hash() -> Result<(), Error> { #[derive(Deserialize)] struct Metainfo { - info: serde_bytes::ByteBuf, + info: BString, } let metainfo: Metainfo = bt_bencode::from_slice(TORRENT_BYTES)?;