From 1c1721b86184cbe4c1d445cf3c1da12d86a85c21 Mon Sep 17 00:00:00 2001 From: Jon Janzen Date: Tue, 10 Nov 2020 15:43:38 -0700 Subject: [PATCH] binary_loader use slices --- binary_loader/src/lib.rs | 43 ++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/binary_loader/src/lib.rs b/binary_loader/src/lib.rs index 1ebe380..dd1b6ef 100644 --- a/binary_loader/src/lib.rs +++ b/binary_loader/src/lib.rs @@ -1,28 +1,26 @@ -pub fn load_high_u4(raw: u8) -> u8 { +pub fn load_high_u4(raw: &u8) -> u8 { (raw & 0xF0) >> 4 } -pub fn load_low_u4(raw: u8) -> u8 { +pub fn load_low_u4(raw: &u8) -> u8 { raw & 0x0F } -pub fn load_u8(raw: u8) -> u8 { - raw +pub fn load_u8(raw: &u8) -> u8 { + raw & 0xFF } -pub fn load_u16(raw: [u16; 2]) -> u16 { - let mut value: u16 = 0; +pub fn load_u16(raw: &[u8]) -> u16 { let temp: u16 = raw[0].into(); - value = temp << 8; + let mut value: u16 = temp << 8; let temp: u16 = raw[1].into(); value |= temp; value } -pub fn load_u32(raw: [u8; 4]) -> u32 { - let mut value: u32 = 0; +pub fn load_u32(raw: &[u8]) -> u32 { let temp: u32 = raw[0].into(); - value = temp << 24; + let mut value: u32 = temp << 24; let temp: u32 = raw[1].into(); value |= temp << 16; let temp: u32 = raw[2].into(); @@ -38,56 +36,59 @@ mod tests { #[test] fn load_0() { - assert_eq!(0, load_u32([0, 0, 0, 0])); + assert_eq!(0, load_u32(&[0, 0, 0, 0])); } #[test] fn load_1() { - assert_eq!(1, load_u32([0, 0, 0, 1])); + assert_eq!(1, load_u32(&[0, 0, 0, 1])); } #[test] fn load_big() { - assert_eq!(0x01000000, load_u32([1, 0, 0, 0])); + let my_arr = [1, 0, 0, 2, 1, 1]; + let slice = &my_arr[0..4]; + assert_eq!(0x01000002, load_u32(&slice)); } #[test] fn test_load_low_u4() { - assert_eq!(0x07, load_low_u4(0x07)); + assert_eq!(0x07, load_low_u4(&0x07)); } #[test] fn load_low_u4_with_high_data() { - assert_eq!(0x03, load_low_u4(0x13)); + assert_eq!(0x03, load_low_u4(&0x13)); } #[test] fn load_low_u4_with_only_high_data() { - assert_eq!(0x00, load_low_u4(0x30)); + assert_eq!(0x00, load_low_u4(&0x30)); } #[test] fn test_load_high_u4() { - assert_eq!(0x07, load_high_u4(0x70)); + assert_eq!(0x07, load_high_u4(&0x70)); } #[test] fn load_high_u4_with_low_data() { - assert_eq!(0x01, load_high_u4(0x13)); + assert_eq!(0x01, load_high_u4(&0x13)); } #[test] fn load_high_u4_with_only_low_data() { - assert_eq!(0x00, load_high_u4(0x03)); + assert_eq!(0x00, load_high_u4(&0x03)); } #[test] fn test_load_u8() { - assert_eq!(0x43, load_u8(0x43)); + assert_eq!(0x43, load_u8(&0x43)); } #[test] fn test_load_u16() { - assert_eq!(0x3423, load_u16([0x34, 0x23])); + let my_arr = [0x34, 0x23]; + assert_eq!(0x3423, load_u16(&my_arr)); } }