Merge pull request 'feat/bintols/split-numbers-to-bytes' (#77) from feat/bintols/split-numbers-to-bytes into devel
cargo devel CI / cargo CI (push) Successful in 1m46s Details

Reviewed-on: #77
This commit is contained in:
Christoph J. Scherr 2024-05-12 17:41:11 +02:00
commit e3ac4c60ba
3 changed files with 94 additions and 0 deletions

View File

@ -25,3 +25,4 @@ pub const YOBI: u128 = 2u128.pow(80);
// use libpt_core;
pub mod datalayout;
pub mod display;
pub mod split_numbers;

View File

@ -0,0 +1,38 @@
//! # Split numbers into bits and bytes
//!
//! Sometimes, you need a large integer in the form of many bytes, so split into [u8].
//! Rust provides
/// Split unsigned integers into a [Vec] of [u8]s
///
/// Say you have the [u32] 1717 (binary: `00000000 00000000 00000110 10110101 `). This number would
/// be splitted to `vec![0b00000110, 0b10110101]`.
///
/// The 0 bytes of the numbers will be discarded (unless the number is 0, then the Vec contains a
/// single Null byte.) and the remaining parts of the numbers are inserted into a Vec as [u8].
///
/// # Examples
///
/// ```
/// # use libpt_bintols::split_numbers::*;
///
/// let x: u32 = 1717;
///
/// assert_eq!(unsigned_to_vec(x), vec![0b00000110, 0b10110101]);
/// ```
pub fn unsigned_to_vec<T>(num: T) -> Vec<u8>
where
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 as u8);
num >>= 8;
}
buf.reverse();
buf
}

View File

@ -0,0 +1,55 @@
use libpt_bintols::split_numbers::*;
#[test]
fn split_u128() {
let source = [
16,
255,
256,
0,
u128::MAX,
u64::MAX as u128,
u64::MAX as u128 + 1,
];
let correct = [
vec![16],
vec![255],
vec![1, 0],
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],
vec![1, 0, 0, 0, 0, 0, 0, 0, 0],
];
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,
0b1_00000001,
0b10011011_10110101_11110000_00110011,
];
let correct = [
vec![16],
vec![255],
vec![1, 0],
vec![0],
vec![255, 255, 255, 255, 255, 255, 255, 255],
vec![255, 255, 255, 255],
vec![1, 1],
vec![0b10011011, 0b10110101, 0b11110000, 0b00110011],
];
for (i, n) in source.iter().enumerate() {
assert_eq!(unsigned_to_vec(*n), correct[i]);
}
}