From 54a707f86034de787b167a037d06875998ff1b62 Mon Sep 17 00:00:00 2001 From: gered Date: Sun, 16 May 2021 16:31:14 -0400 Subject: [PATCH] add to_array helper method --- psoutils/src/bytes.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/psoutils/src/bytes.rs b/psoutils/src/bytes.rs index 8cac339..041e136 100644 --- a/psoutils/src/bytes.rs +++ b/psoutils/src/bytes.rs @@ -30,19 +30,13 @@ pub trait WriteAsBytes { pub trait FixedLengthByteArrays { fn as_unpadded_slice(&self) -> &[u8]; fn to_fixed_length(&self, length: usize) -> Vec; + fn to_array(&self) -> [u8; N]; } impl + ?Sized> FixedLengthByteArrays for T { fn as_unpadded_slice(&self) -> &[u8] { let end = self.as_ref().iter().take_while(|&b| *b != 0).count(); &self.as_ref()[0..end] - /* - self.as_ref() - .iter() - .take_while(|&b| *b != 0u8) - .map(|b| *b) - .collect() - */ } fn to_fixed_length(&self, length: usize) -> Vec { @@ -52,6 +46,17 @@ impl + ?Sized> FixedLengthByteArrays for T { } result } + + fn to_array(&self) -> [u8; N] { + assert_ne!(N, 0); + let mut array = [0u8; N]; + if N <= self.as_ref().len() { + array.copy_from_slice(&self.as_ref()[0..N]); + } else { + array[0..self.as_ref().len()].copy_from_slice(&self.as_ref()) + } + array + } } #[cfg(test)]