Compare commits

...

2 commits

Author SHA1 Message Date
41b38a89ff refactor: split-numbers generic by converting to u128
Some checks failed
cargo devel CI / cargo CI (push) Has been cancelled
2024-05-12 02:47:40 +02:00
ad03279778 test: split-numbers
Some checks failed
cargo devel CI / cargo CI (push) Has been cancelled
test if splitting of numbers into Vec<u8> works correctly
2024-05-12 02:47:12 +02:00
2 changed files with 39 additions and 9 deletions

View file

@ -3,25 +3,20 @@
//! Sometimes, you need a large integer in the form of many bytes, so split into [u8].
//! Rust provides
use num_traits::Unsigned;
/// split an integer into it's bytes, ignoring those bytes that would be all zero.
///
/// If the integer is zero, the Vec contains a single null byte.
pub fn unsigned_to_vec<T>(mut num: T) -> Vec<u8>
pub fn unsigned_to_vec<T>(num: T) -> Vec<u8>
where
T: Unsigned,
T: std::ops::ShrAssign<i32>,
T: std::cmp::PartialOrd<i32>,
u8: std::convert::From<T>,
T: Copy,
u128: std::convert::From<T>
{
let mut num: u128 = num.into();
if num == 0 {
return vec![0];
}
let mut buf: Vec<u8> = Vec::new();
while num > 0 {
buf.push(num.into());
buf.push(num as u8);
num >>= 8;
}
buf

View file

@ -0,0 +1,35 @@
use libpt_bintols::split_numbers::*;
#[test]
fn split_u128() {
let source = [16, 255, 256, 0, u128::MAX, u64::MAX as u128];
let correct = [
vec![16],
vec![255],
vec![255, 1],
vec![0],
vec![
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
],
vec![255, 255, 255, 255, 255, 255, 255, 255],
];
for (i, n) in source.iter().enumerate() {
assert_eq!(unsigned_to_vec(*n), correct[i]);
}
}
#[test]
fn split_u64() {
let source = [16, 255, 256, 0, u64::MAX, u32::MAX as u64];
let correct = [
vec![16],
vec![255],
vec![255, 1],
vec![0],
vec![255, 255, 255, 255, 255, 255, 255, 255],
vec![255, 255, 255, 255],
];
for (i, n) in source.iter().enumerate() {
assert_eq!(unsigned_to_vec(*n), correct[i]);
}
}