refactor: split-numbers generic by converting to u128
cargo devel CI / cargo CI (push) Has been cancelled Details

This commit is contained in:
Christoph J. Scherr 2024-05-12 02:47:40 +02:00
parent ad03279778
commit 41b38a89ff
1 changed files with 4 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]. //! Sometimes, you need a large integer in the form of many bytes, so split into [u8].
//! Rust provides //! Rust provides
use num_traits::Unsigned;
/// split an integer into it's bytes, ignoring those bytes that would be all zero. /// 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. /// 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 where
T: Unsigned, u128: std::convert::From<T>
T: std::ops::ShrAssign<i32>,
T: std::cmp::PartialOrd<i32>,
u8: std::convert::From<T>,
T: Copy,
{ {
let mut num: u128 = num.into();
if num == 0 { if num == 0 {
return vec![0]; return vec![0];
} }
let mut buf: Vec<u8> = Vec::new(); let mut buf: Vec<u8> = Vec::new();
while num > 0 { while num > 0 {
buf.push(num.into()); buf.push(num as u8);
num >>= 8; num >>= 8;
} }
buf buf