From cec05051059f415a1cf4ed1a770380ac62345234 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Sun, 12 May 2024 02:24:23 +0200 Subject: [PATCH] feat: split unsigned numbers into bytes --- members/libpt-bintols/src/lib.rs | 1 + members/libpt-bintols/src/split_numbers.rs | 28 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 members/libpt-bintols/src/split_numbers.rs diff --git a/members/libpt-bintols/src/lib.rs b/members/libpt-bintols/src/lib.rs index ca13f78..54a907f 100644 --- a/members/libpt-bintols/src/lib.rs +++ b/members/libpt-bintols/src/lib.rs @@ -25,3 +25,4 @@ pub const YOBI: u128 = 2u128.pow(80); // use libpt_core; pub mod datalayout; pub mod display; +pub mod split_numbers; diff --git a/members/libpt-bintols/src/split_numbers.rs b/members/libpt-bintols/src/split_numbers.rs new file mode 100644 index 0000000..84a29cb --- /dev/null +++ b/members/libpt-bintols/src/split_numbers.rs @@ -0,0 +1,28 @@ +//! # Split numbers into bits and bytes +//! +//! 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(mut num: T) -> Vec +where + T: Unsigned, + T: std::ops::ShrAssign, + T: std::cmp::PartialOrd, + u8: std::convert::From, + T: Copy, +{ + if num == 0 { + return vec![0]; + } + let mut buf: Vec = Vec::new(); + while num > 0 { + buf.push(num.into()); + num >>= 8; + } + buf +}