From 2e38597a7cc8705414a27bd393a4302670b02108 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 14:56:37 +0200 Subject: [PATCH] feat: add a join module to join arrays into larger integers #79 --- members/libpt-bintols/src/join.rs | 44 +++++++++++++++++++++++++++++++ members/libpt-bintols/src/lib.rs | 1 + 2 files changed, 45 insertions(+) create mode 100644 members/libpt-bintols/src/join.rs diff --git a/members/libpt-bintols/src/join.rs b/members/libpt-bintols/src/join.rs new file mode 100644 index 0000000..35efcd7 --- /dev/null +++ b/members/libpt-bintols/src/join.rs @@ -0,0 +1,44 @@ +//! # Join bits and bytes into numbers +//! +//! Sometimes you have a `[u8]` that is the representation of a larger unsigned integer, such as +//! [u128]. This module helps you join them together. + +use anyhow::anyhow; +use libpt_log::trace; + +/// Join a [Vec] of [u8]s into an unsigned integer +/// +/// Say you have the array `[0b00000110, 0b10110101]` and want to use it as a [u32]. +/// This function sets it together to a integer type of your choosing: +/// 1717 (binary: `00000000 00000000 00000110 10110101`). +/// +/// If the array is not long enough, the number will be padded with null bytes. +/// +/// # Examples +/// +/// ``` +/// # use libpt_bintols::join::*; +/// +/// let x: [u8; 2] = [0b00000110, 0b10110101]; +/// +/// assert_eq!(array_to_unsigned::(&x).unwrap(), 1717); +/// ``` +pub fn array_to_unsigned(parts: &[u8]) -> anyhow::Result +where + u128: std::convert::From, + T: std::str::FromStr, + ::Err: std::fmt::Debug, +{ + trace!("amount of parts: {}", parts.len()); + if parts.len() > (u128::BITS / 8) as usize { + return Err(anyhow!( + "the list is too long to fit into the specified integer type: {}", + std::any::type_name::() + )); + } + let mut ri: u128 = 0; + for (i, e) in parts.iter().rev().enumerate() { + ri += (*e as u128) * 256u128.pow(i as u32); + } + Ok(ri.to_string().parse().unwrap()) +} diff --git a/members/libpt-bintols/src/lib.rs b/members/libpt-bintols/src/lib.rs index 30dec09..1680664 100644 --- a/members/libpt-bintols/src/lib.rs +++ b/members/libpt-bintols/src/lib.rs @@ -26,3 +26,4 @@ pub const YOBI: u128 = 2u128.pow(80); pub mod datalayout; pub mod display; pub mod split; +pub mod join;