From 060e4bcd3235adc33bf50c1cda2a5af582895dc0 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Sun, 17 Apr 2016 11:06:59 +0300 Subject: [PATCH] adding docs --- util/src/bytes.rs | 44 ++++++++++++++++++-------------------------- 1 file changed, 18 insertions(+), 26 deletions(-) diff --git a/util/src/bytes.rs b/util/src/bytes.rs index cb54f8f0e..47264db4d 100644 --- a/util/src/bytes.rs +++ b/util/src/bytes.rs @@ -247,7 +247,7 @@ pub trait FromRawBytes : Sized { fn from_bytes(d: &[u8]) -> Result; } -impl FromRawBytes for (T) where T: FixedHash { +impl FromRawBytes for T where T: FixedHash { fn from_bytes(bytes: &[u8]) -> Result { use std::mem; use std::cmp::Ordering; @@ -279,28 +279,20 @@ impl FromRawBytes for u16 { } } -impl FromRawBytes for u8 { - fn from_bytes(bytes: &[u8]) -> Result { - use std::mem; - use std::cmp::Ordering; - - match bytes.len().cmp(&1) { - Ordering::Less => return Err(FromBytesError::NotLongEnough), - Ordering::Greater => return Err(FromBytesError::TooLong), - Ordering::Equal => () - }; - let mut res: Self = unsafe { mem::uninitialized() }; - res.copy_raw(bytes); - Ok(res) - } -} - +/// Value that can be serialized from variable-length byte array pub trait FromRawBytesVariable : Sized { + /// Create value from slice fn from_bytes_var(d: &[u8], len: u64) -> Result; } impl FromRawBytesVariable for T where T: FromRawBytes { - fn from_bytes_var(d: &[u8], _len: u64) -> Result { + fn from_bytes_var(bytes: &[u8], len: u64) -> Result { + match bytes.len().cmp(&len) { + Ordering::Less => return Err(FromBytesError::NotLongEnough), + Ordering::Greater => return Err(FromBytesError::TooLong), + Ordering::Equal => () + }; + T::from_bytes(d) } } @@ -395,18 +387,18 @@ fn raw_bytes_from_tuple() { let tup = (vec![1u16, 1u16, 1u16, 1u16], 10u16); let bytes = vec![ // map - 8u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, + 8u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, // four 1u16 - 0u8, 1u8, - 0u8, 1u8, - 0u8, 1u8, - 0u8, 1u8, + 1u8, 0u8, + 1u8, 0u8, + 1u8, 0u8, + 1u8, 0u8, // 10u16 - 0u8, 10u8]; + 10u8, 0u8]; - type tup = (Vec, u16); + type Tup = (Vec, u16); - let tup_from = tup::from_bytes(&bytes).unwrap(); + let tup_from = Tup::from_bytes(&bytes).unwrap(); assert_eq!(tup, tup_from); }