diff options
| -rw-r--r-- | src/deserialize.rs | 43 | ||||
| -rw-r--r-- | src/lib.rs | 14 | ||||
| -rw-r--r-- | src/nbt.rs | 172 | ||||
| -rw-r--r-- | src/protocol.rs | 50 | ||||
| -rw-r--r-- | src/serialize.rs | 7 | ||||
| -rw-r--r-- | src/status.rs | 73 | ||||
| -rw-r--r-- | src/test_macros.rs | 27 | ||||
| -rw-r--r-- | src/types.rs | 330 | ||||
| -rw-r--r-- | src/utils.rs | 34 | ||||
| -rw-r--r-- | src/uuid.rs | 70 | ||||
| -rw-r--r-- | src/v1_15_2.rs | 2253 |
11 files changed, 2161 insertions, 912 deletions
diff --git a/src/deserialize.rs b/src/deserialize.rs index 694c6e5..f87cb49 100644 --- a/src/deserialize.rs +++ b/src/deserialize.rs @@ -12,7 +12,7 @@ pub enum DeserializeErr { NbtBadLength(isize), NbtInvalidStartTag(u8), CannotUnderstandValue(String), - FailedJsonDeserialize(String) + FailedJsonDeserialize(String), } impl<'b, R> Into<DeserializeResult<'b, R>> for DeserializeErr { @@ -37,10 +37,7 @@ impl<'b, R> Into<DeserializeResult<'b, R>> for Deserialized<'b, R> { impl<'b, R> Deserialized<'b, R> { #[inline] pub fn create(value: R, data: &'b [u8]) -> Self { - Deserialized { - value, - data, - } + Deserialized { value, data } } #[inline] @@ -50,57 +47,55 @@ impl<'b, R> Deserialized<'b, R> { #[inline] pub fn replace<T>(self, other: T) -> Deserialized<'b, T> { - Deserialized{ + Deserialized { value: other, data: self.data, } } #[inline] - pub fn map<F, T>(self, f: F) -> Deserialized<'b, T> where F: FnOnce(R) -> T { - Deserialized{ + pub fn map<F, T>(self, f: F) -> Deserialized<'b, T> + where + F: FnOnce(R) -> T, + { + Deserialized { value: f(self.value), data: self.data, } } #[inline] - pub fn try_map<F, T>(self, f: F) -> DeserializeResult<'b, T> where - F: FnOnce(R) -> Result<T, DeserializeErr> + pub fn try_map<F, T>(self, f: F) -> DeserializeResult<'b, T> + where + F: FnOnce(R) -> Result<T, DeserializeErr>, { match f(self.value) { - Ok(new_value) => Ok(Deserialized{ + Ok(new_value) => Ok(Deserialized { value: new_value, data: self.data, }), - Err(err) => Err(err) + Err(err) => Err(err), } } #[inline] - pub fn and_then<F, T>(self, f: F) -> DeserializeResult<'b, T> where - F: FnOnce(R, &'b[u8]) -> DeserializeResult<'b, T> + pub fn and_then<F, T>(self, f: F) -> DeserializeResult<'b, T> + where + F: FnOnce(R, &'b [u8]) -> DeserializeResult<'b, T>, { f(self.value, self.data) } } - impl<'b, R> From<(R, &'b [u8])> for Deserialized<'b, R> { fn from(v: (R, &'b [u8])) -> Self { let (value, data) = v; - Deserialized { - value, - data, - } + Deserialized { value, data } } } -pub type DeserializeResult<'b, R> -= Result< - Deserialized<'b, R>, - DeserializeErr>; +pub type DeserializeResult<'b, R> = Result<Deserialized<'b, R>, DeserializeErr>; pub trait Deserialize: Sized { fn mc_deserialize(data: &[u8]) -> DeserializeResult<Self>; -}
\ No newline at end of file +} @@ -5,20 +5,20 @@ #[cfg(test)] extern crate test; -mod serialize; mod deserialize; -pub mod utils; +pub mod nbt; #[macro_export] pub mod protocol; -pub mod uuid; -pub mod nbt; +mod serialize; +pub mod status; pub mod types; +pub mod utils; +pub mod uuid; pub mod v1_15_2; -pub mod status; -pub use serialize::*; pub use deserialize::*; +pub use serialize::*; #[cfg(test)] #[macro_export] -mod test_macros;
\ No newline at end of file +mod test_macros; @@ -1,7 +1,9 @@ -use std::fmt; -use crate::{DeserializeResult, DeserializeErr, Deserialized}; -use crate::utils::{read_short, take, read_int, read_long, read_one_byte, write_long, write_int, write_short}; use crate::protocol::TestRandom; +use crate::utils::{ + read_int, read_long, read_one_byte, read_short, take, write_int, write_long, write_short, +}; +use crate::{DeserializeErr, DeserializeResult, Deserialized}; +use std::fmt; #[derive(Clone, Debug, PartialEq)] pub struct NamedTag { @@ -34,12 +36,15 @@ impl TestRandom for NamedTag { impl fmt::Display for NamedTag { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_fmt(format_args!("TAG_{}('{}'): ", self.payload.tag_type_name(), self.name))?; + f.write_fmt(format_args!( + "TAG_{}('{}'): ", + self.payload.tag_type_name(), + self.name + ))?; self.payload.write_contents(f) } } - #[derive(Clone, Debug, PartialEq)] pub enum Tag { Byte(i8), @@ -140,7 +145,7 @@ impl TestRandom for Tag { 4 => Tag::Float(f32::test_gen_random()), 5 => Tag::Double(f64::test_gen_random()), 6 => Tag::String(String::test_gen_random()), - other => panic!("impossible {}", other) + other => panic!("impossible {}", other), }); } @@ -160,19 +165,34 @@ impl TestRandom for Tag { } #[inline] -fn write_contents<F>(contents: &Vec<F>) -> String where F: fmt::Display { - format!("{} entries\n{{\n{}\n}}", contents.len(), contents.iter() - .flat_map(move |elem| elem.to_string().split("\n").map(String::from).collect::<Vec<String>>()) - .map(move |line| " ".to_owned() + line.as_str()) - .collect::<Vec<String>>() - .join("\n")) +fn write_contents<F>(contents: &Vec<F>) -> String +where + F: fmt::Display, +{ + format!( + "{} entries\n{{\n{}\n}}", + contents.len(), + contents + .iter() + .flat_map(move |elem| elem + .to_string() + .split("\n") + .map(String::from) + .collect::<Vec<String>>()) + .map(move |line| " ".to_owned() + line.as_str()) + .collect::<Vec<String>>() + .join("\n") + ) } // deserialization first // reads from the root level fn read_nbt_data(data: &[u8]) -> DeserializeResult<NamedTag> { - let Deserialized { value: tag_type_id, data: _ } = read_one_byte(data)?; + let Deserialized { + value: tag_type_id, + data: _, + } = read_one_byte(data)?; match tag_type_id { 0x0A => read_named_tag(data), other => Err(DeserializeErr::NbtInvalidStartTag(other)), @@ -182,8 +202,12 @@ fn read_nbt_data(data: &[u8]) -> DeserializeResult<NamedTag> { // reads any named tag: read id -> read name -> read tag with id -> name tag with name #[inline] pub fn read_named_tag(data: &[u8]) -> DeserializeResult<NamedTag> { - let Deserialized { value: tag_type_id, data } = read_one_byte(data)?; - if tag_type_id == 0x00 { // tag end + let Deserialized { + value: tag_type_id, + data, + } = read_one_byte(data)?; + if tag_type_id == 0x00 { + // tag end Deserialized::ok(Tag::End.with_name(""), data) } else { let Deserialized { value: name, data } = read_string(data)?; @@ -244,7 +268,8 @@ fn read_tag_double(data: &[u8]) -> DeserializeResult<Tag> { #[inline] fn read_tag_byte_array(data: &[u8]) -> DeserializeResult<Tag> { - Ok(read_int(data)?.and_then(move |size, rest| take(size as usize)(rest))? + Ok(read_int(data)? + .and_then(move |size, rest| take(size as usize)(rest))? .map(move |arr| Tag::ByteArray(Vec::from(arr)))) } @@ -254,19 +279,28 @@ fn read_tag_string(data: &[u8]) -> DeserializeResult<Tag> { } fn read_tag_list(data: &[u8]) -> DeserializeResult<Tag> { - let Deserialized { value: contents_tag_type_id, data } = read_one_byte(data)?; - let Deserialized { value: list_length, data } = read_int(data)?; + let Deserialized { + value: contents_tag_type_id, + data, + } = read_one_byte(data)?; + let Deserialized { + value: list_length, + data, + } = read_int(data)?; if list_length <= 0 { if contents_tag_type_id != 0x00 { Err(DeserializeErr::NbtBadLength(list_length as isize)) } else { - Deserialized::ok(Tag::List(vec!()), data) + Deserialized::ok(Tag::List(vec![]), data) } } else { let mut out_vec = Vec::with_capacity(list_length as usize); let mut remaining_data = data; for _ in 0..list_length { - let Deserialized { value: element, data: rest } = read_tag(contents_tag_type_id, &remaining_data)?; + let Deserialized { + value: element, + data: rest, + } = read_tag(contents_tag_type_id, &remaining_data)?; out_vec.push(element); remaining_data = rest; } @@ -279,7 +313,10 @@ fn read_tag_compound(data: &[u8]) -> DeserializeResult<Tag> { let mut out = Vec::new(); let mut remaining_data = data; loop { - let Deserialized { value: elem, data: rest } = read_named_tag(remaining_data)?; + let Deserialized { + value: elem, + data: rest, + } = read_named_tag(remaining_data)?; remaining_data = rest; if elem.is_end() { break; @@ -295,7 +332,8 @@ fn read_tag_int_array(data: &[u8]) -> DeserializeResult<Tag> { read_array_tag( data, move |data| Ok(read_int(data)?.map(move |r| r as i32)), - Tag::IntArray) + Tag::IntArray, + ) } #[inline] @@ -303,13 +341,19 @@ fn read_tag_long_array(data: &[u8]) -> DeserializeResult<Tag> { read_array_tag( data, move |data| Ok(read_long(data)?.map(move |r| r as i64)), - Tag::LongArray) + Tag::LongArray, + ) } #[inline] -fn read_array_tag<'a, R, F, M>(data: &'a [u8], parser: F, finalizer: M) -> DeserializeResult<'a, Tag> where +fn read_array_tag<'a, R, F, M>( + data: &'a [u8], + parser: F, + finalizer: M, +) -> DeserializeResult<'a, Tag> +where F: Fn(&'a [u8]) -> DeserializeResult<'a, R>, - M: Fn(Vec<R>) -> Tag + M: Fn(Vec<R>) -> Tag, { let Deserialized { value: count, data } = read_int(data)?.map(move |v| v as i32); if count < 0 { @@ -318,7 +362,10 @@ fn read_array_tag<'a, R, F, M>(data: &'a [u8], parser: F, finalizer: M) -> Deser let mut out = Vec::with_capacity(count as usize); let mut data_remaining = data; for _ in 0..count { - let Deserialized { value: elem, data: rest } = parser(data_remaining)?; + let Deserialized { + value: elem, + data: rest, + } = parser(data_remaining)?; data_remaining = rest; out.push(elem); } @@ -330,12 +377,11 @@ fn read_array_tag<'a, R, F, M>(data: &'a [u8], parser: F, finalizer: M) -> Deser #[inline] fn read_string(data: &[u8]) -> DeserializeResult<String> { read_short(data)? - .and_then(move |length, data| - take(length as usize)(data))? - .try_map(move |bytes| - String::from_utf8(Vec::from(bytes)).map_err(move |err| { - DeserializeErr::BadStringEncoding(err) - })) + .and_then(move |length, data| take(length as usize)(data))? + .try_map(move |bytes| { + String::from_utf8(Vec::from(bytes)) + .map_err(move |err| DeserializeErr::BadStringEncoding(err)) + }) } // serialize @@ -343,12 +389,13 @@ impl NamedTag { pub fn bytes(&self) -> Vec<u8> { let type_id = self.payload.id(); if type_id == 0x00 { - vec!(0x00) + vec![0x00] } else { let payload_bytes = self.payload.bytes(); let name_len = self.name.len(); let name_len_bytes = write_short(name_len as u16); - let mut out = Vec::with_capacity(1 + name_len_bytes.len() + name_len + payload_bytes.len()); + let mut out = + Vec::with_capacity(1 + name_len_bytes.len() + name_len + payload_bytes.len()); out.push(type_id); out.extend_from_slice(&name_len_bytes); out.extend(self.name.bytes()); @@ -379,7 +426,7 @@ impl Tag { pub fn bytes(&self) -> Vec<u8> { match self { - Tag::Byte(b) => vec!(*b as u8), + Tag::Byte(b) => vec![*b as u8], Tag::Short(v) => Vec::from(write_short(*v as u16)), Tag::Int(v) => Vec::from(write_int(*v as u32)), Tag::Long(v) => Vec::from(write_long(*v as u64)), @@ -412,7 +459,9 @@ impl Tag { let elem_id = elem.id(); if let Some(old_id) = id.replace(elem_id) { if old_id != elem_id { - panic!("list contains tags of different types, cannot serialize"); + panic!( + "list contains tags of different types, cannot serialize" + ); } } } @@ -467,9 +516,9 @@ impl Tag { #[cfg(test)] mod tests { use super::*; - use std::io::Read; use flate2::read::GzDecoder; use std::fs::File; + use std::io::Read; #[test] fn test_read_bignbt_example() { @@ -521,29 +570,53 @@ mod tests { let (unzipped, result) = read_bigtest_with_bytes(); let serialized = result.bytes(); assert_eq!(unzipped, serialized); - let Deserialized { value: unserialized, data: _ } = NamedTag::root_compound_tag_from_bytes(serialized.as_slice()).expect("deserialize serialized nbt"); + let Deserialized { + value: unserialized, + data: _, + } = NamedTag::root_compound_tag_from_bytes(serialized.as_slice()) + .expect("deserialize serialized nbt"); assert_eq!(unserialized, result); } #[test] fn test_int_array() { - let original = Tag::Compound(vec!( - Tag::IntArray(vec!(1, 2, -5, 123127, -12373, 0, 0, 4, 2)).with_name("test ints") - )).with_name("test"); + let original = Tag::Compound(vec![Tag::IntArray(vec![ + 1, 2, -5, 123127, -12373, 0, 0, 4, 2, + ]) + .with_name("test ints")]) + .with_name("test"); let bytes = original.bytes(); - let Deserialized { value: unserialized, data: _ } = NamedTag::root_compound_tag_from_bytes(bytes.as_slice()).expect("deserialize int array"); + let Deserialized { + value: unserialized, + data: _, + } = NamedTag::root_compound_tag_from_bytes(bytes.as_slice()) + .expect("deserialize int array"); assert_eq!(original, unserialized); } #[test] fn test_long_array() { - let original = Tag::Compound(vec!( - Tag::LongArray(vec!(1, 2, -5, 123127999999, -1237399999, 0, 0, 4, 2)).with_name("test ints") - )).with_name("test"); + let original = Tag::Compound(vec![Tag::LongArray(vec![ + 1, + 2, + -5, + 123127999999, + -1237399999, + 0, + 0, + 4, + 2, + ]) + .with_name("test ints")]) + .with_name("test"); let bytes = original.bytes(); - let Deserialized { value: unserialized, data: _ } = NamedTag::root_compound_tag_from_bytes(bytes.as_slice()).expect("deserialize int array"); + let Deserialized { + value: unserialized, + data: _, + } = NamedTag::root_compound_tag_from_bytes(bytes.as_slice()) + .expect("deserialize int array"); assert_eq!(original, unserialized); } @@ -559,7 +632,10 @@ mod tests { fn read_bigtest_with_bytes() -> (Vec<u8>, NamedTag) { let unzipped = read_compressed_file("src/testdata/bigtest.nbt").expect("read nbt data"); - let Deserialized { value: result, data: rest } = NamedTag::root_compound_tag_from_bytes(unzipped.as_slice()).expect("deserialize nbt"); + let Deserialized { + value: result, + data: rest, + } = NamedTag::root_compound_tag_from_bytes(unzipped.as_slice()).expect("deserialize nbt"); assert_eq!(rest.len(), 0); (unzipped, result) @@ -586,4 +662,4 @@ mod tests { gz.read_to_end(&mut out)?; Ok(out) } -}
\ No newline at end of file +} diff --git a/src/protocol.rs b/src/protocol.rs index e768fdb..4eb1094 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -1,4 +1,4 @@ -use crate::{Serialize, Deserialize, DeserializeErr}; +use crate::{Deserialize, DeserializeErr, Serialize}; use std::fmt::Debug; #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] @@ -56,7 +56,9 @@ pub trait TestRandom { #[macro_export] macro_rules! as_item { - ($i:item) => { $i }; + ($i:item) => { + $i + }; } #[macro_export] @@ -405,11 +407,17 @@ macro_rules! proto_byte_flag { macro_rules! counted_array_type { ($name: ident, $countert: ty, $tousize_fn: ident, $fromusize_fn: ident) => { #[derive(Debug, Clone, PartialEq)] - pub struct $name<T> where T: Debug + Clone + PartialEq { - pub data: Vec<T> + pub struct $name<T> + where + T: Debug + Clone + PartialEq, + { + pub data: Vec<T>, } - impl<T> Serialize for $name<T> where T: Serialize + Debug + Clone + PartialEq { + impl<T> Serialize for $name<T> + where + T: Serialize + Debug + Clone + PartialEq, + { fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult { let count: $countert = $fromusize_fn(self.data.len()); to.serialize_other(&count)?; @@ -422,14 +430,23 @@ macro_rules! counted_array_type { } } - impl<T> Deserialize for $name<T> where T: Deserialize + Debug + Clone + PartialEq { + impl<T> Deserialize for $name<T> + where + T: Deserialize + Debug + Clone + PartialEq, + { fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> { - let Deserialized{value: raw_count, mut data} = <$countert>::mc_deserialize(data)?; + let Deserialized { + value: raw_count, + mut data, + } = <$countert>::mc_deserialize(data)?; let count: usize = $tousize_fn(raw_count); let mut out = Vec::with_capacity(count); for _ in 0..count { - let Deserialized{value: next, data: rest} = T::mc_deserialize(data)?; + let Deserialized { + value: next, + data: rest, + } = T::mc_deserialize(data)?; data = rest; out.push(next); } @@ -438,20 +455,29 @@ macro_rules! counted_array_type { } } - impl<T> Into<Vec<T>> for $name<T> where T: Debug + Clone + PartialEq { + impl<T> Into<Vec<T>> for $name<T> + where + T: Debug + Clone + PartialEq, + { fn into(self) -> Vec<T> { self.data } } - impl<T> From<Vec<T>> for $name<T> where T: Debug + Clone + PartialEq { + impl<T> From<Vec<T>> for $name<T> + where + T: Debug + Clone + PartialEq, + { fn from(data: Vec<T>) -> Self { Self { data } } } #[cfg(test)] - impl<T> TestRandom for $name<T> where T: TestRandom + Debug + Clone + PartialEq { + impl<T> TestRandom for $name<T> + where + T: TestRandom + Debug + Clone + PartialEq, + { fn test_gen_random() -> Self { let elem_count: usize = rand::random::<usize>() % 32; let mut out = Vec::with_capacity(elem_count); @@ -462,5 +488,5 @@ macro_rules! counted_array_type { Self { data: out } } } - } + }; } diff --git a/src/serialize.rs b/src/serialize.rs index 5eb8f2a..3239b66 100644 --- a/src/serialize.rs +++ b/src/serialize.rs @@ -1,7 +1,7 @@ #[derive(Debug)] pub enum SerializeErr { FailedJsonEncode(String), - InconsistentPlayerActions(String) + InconsistentPlayerActions(String), } pub type SerializeResult = Result<(), SerializeErr>; @@ -11,14 +11,13 @@ pub trait Serialize: Sized { } pub trait Serializer: Sized { - fn serialize_bytes(&mut self, data: &[u8]) -> SerializeResult; fn serialize_byte(&mut self, byte: u8) -> SerializeResult { - self.serialize_bytes(vec!(byte).as_slice()) + self.serialize_bytes(vec![byte].as_slice()) } fn serialize_other<S: Serialize>(&mut self, other: &S) -> SerializeResult { other.mc_serialize(self) } -}
\ No newline at end of file +} diff --git a/src/status.rs b/src/status.rs index 7d254aa..22f75bf 100644 --- a/src/status.rs +++ b/src/status.rs @@ -1,9 +1,12 @@ +use crate::protocol::TestRandom; use crate::types::Chat; -use crate::{SerializeResult, SerializeErr, Serialize as McSerialize, Deserialize as McDeserialize, DeserializeResult, DeserializeErr}; use crate::uuid::UUID4; -use serde::{Serialize, Serializer, Deserialize, Deserializer}; +use crate::{ + Deserialize as McDeserialize, DeserializeErr, DeserializeResult, Serialize as McSerialize, + SerializeErr, SerializeResult, +}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; -use crate::protocol::TestRandom; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct StatusSpec { @@ -16,9 +19,11 @@ pub struct StatusSpec { impl McSerialize for StatusSpec { fn mc_serialize<S: crate::Serializer>(&self, to: &mut S) -> SerializeResult { - serde_json::to_string(self).map_err(move |err| { - SerializeErr::FailedJsonEncode(format!("failed to serialize json status {}", err)) - })?.mc_serialize(to) + serde_json::to_string(self) + .map_err(move |err| { + SerializeErr::FailedJsonEncode(format!("failed to serialize json status {}", err)) + })? + .mc_serialize(to) } } @@ -26,22 +31,24 @@ impl McDeserialize for StatusSpec { fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> { String::mc_deserialize(data)?.try_map(move |v| { serde_json::from_str(v.as_str()).map_err(move |err| { - DeserializeErr::CannotUnderstandValue(format!("failed to deserialize json status {}", err)) + DeserializeErr::CannotUnderstandValue(format!( + "failed to deserialize json status {}", + err + )) }) }) } } - #[cfg(test)] impl TestRandom for StatusSpec { fn test_gen_random() -> Self { Self { - version: StatusVersionSpec{ + version: StatusVersionSpec { protocol: rand::random(), name: String::test_gen_random(), }, - players: StatusPlayersSpec{ + players: StatusPlayersSpec { sample: Vec::default(), max: rand::random(), online: rand::random(), @@ -80,8 +87,9 @@ pub struct StatusFaviconSpec { } impl Serialize for StatusFaviconSpec { - fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where - S: Serializer + fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> + where + S: Serializer, { let data_base64 = base64::encode(self.data.as_slice()); let content = format!("data:{};base64,{}", self.content_type, data_base64); @@ -90,8 +98,9 @@ impl Serialize for StatusFaviconSpec { } impl<'de> Deserialize<'de> for StatusFaviconSpec { - fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where - D: Deserializer<'de> + fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> + where + D: Deserializer<'de>, { struct Visitor; impl serde::de::Visitor<'_> for Visitor { @@ -107,8 +116,8 @@ impl<'de> Deserialize<'de> for StatusFaviconSpec { // regex to parse valid base64 content const PATTERN: &str = r"^data:([A-Za-z/]+);base64,([-A-Za-z0-9+/]*={0,3})$"; lazy_static! { - static ref RE: Regex = Regex::new(PATTERN).expect("regex is valid"); - } + static ref RE: Regex = Regex::new(PATTERN).expect("regex is valid"); + } // try to use regex on the input // RE.captures_iter(v).next() means "try to get the first capture iterator" @@ -117,20 +126,30 @@ impl<'de> Deserialize<'de> for StatusFaviconSpec { // wrap the content_type and parsed data in StatusFaviconSpec // then we convert the option to a result using map and unwrap_or_else let mut captures: regex::CaptureMatches<'_, '_> = RE.captures_iter(v); - captures.next().and_then(move |captures| - captures.get(1).and_then(move |content_type| - captures.get(2).and_then(move |raw_base64| - base64::decode(raw_base64.as_str().as_bytes()).map(move |data| { - StatusFaviconSpec { - content_type: content_type.as_str().to_owned(), - data, - } - }).ok()))) + captures + .next() + .and_then(move |captures| { + captures.get(1).and_then(move |content_type| { + captures.get(2).and_then(move |raw_base64| { + base64::decode(raw_base64.as_str().as_bytes()) + .map(move |data| StatusFaviconSpec { + content_type: content_type.as_str().to_owned(), + data, + }) + .ok() + }) + }) + }) .map(move |result| Ok(result)) - .unwrap_or_else(|| Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &self))) + .unwrap_or_else(|| { + Err(serde::de::Error::invalid_value( + serde::de::Unexpected::Str(v), + &self, + )) + }) } } deserializer.deserialize_str(Visitor {}) } -}
\ No newline at end of file +} diff --git a/src/test_macros.rs b/src/test_macros.rs index cc573a7..d8fc76b 100644 --- a/src/test_macros.rs +++ b/src/test_macros.rs @@ -1,4 +1,4 @@ -use crate::{Serializer, SerializeResult}; +use crate::{SerializeResult, Serializer}; #[cfg(test)] #[macro_export] macro_rules! packet_test_cases { @@ -11,12 +11,13 @@ macro_rules! packet_test_cases { packet.mc_serialize(&mut out).expect("serialize succeeds"); let bytes = out.into_bytes(); - let raw_packet = RawPacket{ + let raw_packet = RawPacket { id: packet.id(), data: bytes, }; - let deserialized = <$pnam>::mc_deserialize(raw_packet).expect("deserialize succeeds"); + let deserialized = + <$pnam>::mc_deserialize(raw_packet).expect("deserialize succeeds"); assert_eq!(packet, deserialized); } } @@ -25,12 +26,16 @@ macro_rules! packet_test_cases { fn $benchnams(b: &mut Bencher) { let packet = $pnam::$varnam($bodnam::test_gen_random()); let mut serializer = BenchSerializer::default(); - packet.mc_serialize(&mut serializer).expect("serialize succeeds"); + packet + .mc_serialize(&mut serializer) + .expect("serialize succeeds"); b.bytes = serializer.len() as u64; serializer.reset(); b.iter(|| { - packet.mc_serialize(&mut serializer).expect("serialize succeeds"); + packet + .mc_serialize(&mut serializer) + .expect("serialize succeeds"); serializer.reset(); }) } @@ -39,11 +44,13 @@ macro_rules! packet_test_cases { fn $benchnamd(b: &mut Bencher) { let packet = $pnam::$varnam($bodnam::test_gen_random()); let mut serializer = BytesSerializer::default(); - packet.mc_serialize(&mut serializer).expect("serialize succeeds"); + packet + .mc_serialize(&mut serializer) + .expect("serialize succeeds"); let bytes = serializer.into_bytes(); b.bytes = bytes.len() as u64; - let raw_packet = RawPacket{ + let raw_packet = RawPacket { id: packet.id(), data: bytes, }; @@ -51,13 +58,13 @@ macro_rules! packet_test_cases { $pnam::mc_deserialize(raw_packet.clone()).expect("deserialize succeeds"); }) } - } + }; } #[cfg(test)] #[derive(Clone, Debug, Default, PartialEq)] pub struct BenchSerializer { - data: Vec<u8> + data: Vec<u8>, } #[cfg(test)] @@ -77,4 +84,4 @@ impl BenchSerializer { pub fn len(&self) -> usize { self.data.len() } -}
\ No newline at end of file +} diff --git a/src/types.rs b/src/types.rs index 9d8f595..2082b56 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,8 +1,8 @@ // ... PRIMITIVE TYPES ... -use crate::*; use crate::utils::*; use crate::uuid::UUID4; +use crate::*; #[cfg(test)] use crate::protocol::TestRandom; @@ -16,12 +16,10 @@ impl Serialize for bool { impl Deserialize for bool { fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> { - read_one_byte(data)?.try_map(move |b| { - match b { - 0x00 => Ok(false), - 0x01 => Ok(true), - other => Err(DeserializeErr::InvalidBool(other)) - } + read_one_byte(data)?.try_map(move |b| match b { + 0x00 => Ok(false), + 0x01 => Ok(true), + other => Err(DeserializeErr::InvalidBool(other)), }) } } @@ -103,7 +101,9 @@ impl Serialize for i16 { impl Deserialize for i16 { fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> { - u16::mc_deserialize(data)?.map(move |other| other as i16).into() + u16::mc_deserialize(data)? + .map(move |other| other as i16) + .into() } } @@ -158,7 +158,6 @@ impl TestRandom for i64 { // float impl Serialize for f32 { - //noinspection ALL fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult { let data = (*self).to_be_bytes(); @@ -168,7 +167,9 @@ impl Serialize for f32 { impl Deserialize for f32 { fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> { - i32::mc_deserialize(data)?.map(move |r| f32::from_bits(r as u32)).into() + i32::mc_deserialize(data)? + .map(move |r| f32::from_bits(r as u32)) + .into() } } @@ -190,7 +191,9 @@ impl Serialize for f64 { impl Deserialize for f64 { fn mc_deserialize(data: &[u8]) -> DeserializeResult<'_, Self> { - i64::mc_deserialize(data)?.map(move |r| f64::from_bits(r as u64)).into() + i64::mc_deserialize(data)? + .map(move |r| f64::from_bits(r as u64)) + .into() } } @@ -205,8 +208,10 @@ impl TestRandom for f64 { const VAR_INT_BYTES: usize = 5; const VAR_LONG_BYTES: usize = 10; -const DESERIALIZE_VAR_INT: impl for<'b> Fn(&'b [u8]) -> DeserializeResult<'b, u64> = deserialize_var_num(VAR_INT_BYTES); -const DESERIALIZE_VAR_LONG: impl for<'b> Fn(&'b [u8]) -> DeserializeResult<'b, u64> = deserialize_var_num(VAR_LONG_BYTES); +const DESERIALIZE_VAR_INT: impl for<'b> Fn(&'b [u8]) -> DeserializeResult<'b, u64> = + deserialize_var_num(VAR_INT_BYTES); +const DESERIALIZE_VAR_LONG: impl for<'b> Fn(&'b [u8]) -> DeserializeResult<'b, u64> = + deserialize_var_num(VAR_LONG_BYTES); #[derive(Copy, Clone, PartialOrd, PartialEq, Debug, Default, Hash, Ord, Eq)] pub struct VarInt(pub i32); @@ -309,7 +314,9 @@ fn serialize_var_num(data: u64, out: &mut [u8]) -> &[u8] { &out[..byte_idx] } -const fn deserialize_var_num(max_bytes: usize) -> impl for<'b> Fn(&'b [u8]) -> DeserializeResult<'b, u64> { +const fn deserialize_var_num( + max_bytes: usize, +) -> impl for<'b> Fn(&'b [u8]) -> DeserializeResult<'b, u64> { move |orig_data| { let mut data = orig_data; let mut v: u64 = 0; @@ -321,7 +328,10 @@ const fn deserialize_var_num(max_bytes: usize) -> impl for<'b> Fn(&'b [u8]) -> D if i == max_bytes { return DeserializeErr::VarNumTooLong(Vec::from(& |
