From 6ef280e7ceb50d05fd54ebe299a05e7d32800791 Mon Sep 17 00:00:00 2001 From: Edgar Luque Date: Sat, 12 Nov 2022 17:14:51 +0100 Subject: [PATCH] add trait --- src/lib.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 1746a88..f83bfa6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -109,6 +109,20 @@ impl PackTwInt for i32 { } } +/// Trait implemented by buffers holding a teeworlds variable int. +/// +/// This trait is more of a convenience to allow writing `let data = buff.unpack()?;` +pub trait UnpPackTwInt: Read { + /// Unpack this reader holding a teeworlds variable int to a i32. + fn unpack(&mut self) -> Result; +} + +impl UnpPackTwInt for T { + fn unpack(&mut self) -> Result { + unpack(self) + } +} + #[cfg(test)] mod tests { use std::io::Cursor; @@ -240,4 +254,11 @@ mod tests { assert_eq!(buff[0], 0b1000_0000); assert_eq!(buff[1], 0b0000_0001); } + + #[test] + pub fn unpack_64_trait() { + let mut buff = Cursor::new([0b1000_0000, 0b0000_0001]); + let result = buff.unpack().unwrap(); + assert_eq!(result, 64); + } }