From e5ba4490d3a9898ed2eda75cf860a4255aabde1e Mon Sep 17 00:00:00 2001 From: Jaby Date: Tue, 20 Sep 2022 22:10:17 +0200 Subject: [PATCH] Support bit operations --- src/Tools/tool_helper/Cargo.toml | 1 + src/Tools/tool_helper/src/bits.rs | 30 ++++++++++++++++++++++++++++++ src/Tools/tool_helper/src/lib.rs | 2 ++ 3 files changed, 33 insertions(+) create mode 100644 src/Tools/tool_helper/src/bits.rs diff --git a/src/Tools/tool_helper/Cargo.toml b/src/Tools/tool_helper/Cargo.toml index 6b487e97..4c090cb4 100644 --- a/src/Tools/tool_helper/Cargo.toml +++ b/src/Tools/tool_helper/Cargo.toml @@ -6,3 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +paste = "*" \ No newline at end of file diff --git a/src/Tools/tool_helper/src/bits.rs b/src/Tools/tool_helper/src/bits.rs new file mode 100644 index 00000000..2e5b53ee --- /dev/null +++ b/src/Tools/tool_helper/src/bits.rs @@ -0,0 +1,30 @@ +pub struct BitRange { + pub start: usize, + pub len: usize, +} + +impl BitRange { + pub const fn from_to(start: usize, end: usize) -> BitRange { + BitRange{start, len: (end - start + 1)} + } +} + +macro_rules! create_bit_functions { + ($type_val:ty) => { + paste::item! { + fn [< get_mask_ $type_val >](range: &BitRange) -> $type_val { + (1 << range.len) - 1 + } + + pub fn [< clear_value_ $type_val >](dst: $type_val, range: &BitRange) -> $type_val { + dst & !([< get_mask_ $type_val >](range) << (range.start as $type_val)) + } + + pub fn [< set_value_ $type_val >](dst: $type_val, value: $type_val, range: &BitRange) -> $type_val { + [< clear_value_ $type_val >](dst, range) | ((value & [< get_mask_ $type_val >](range)) << range.start) + } + } + }; +} + +create_bit_functions!(u16); \ No newline at end of file diff --git a/src/Tools/tool_helper/src/lib.rs b/src/Tools/tool_helper/src/lib.rs index 73075aa0..687f0386 100644 --- a/src/Tools/tool_helper/src/lib.rs +++ b/src/Tools/tool_helper/src/lib.rs @@ -1,5 +1,7 @@ use std::{boxed::Box, io::{Read, Write}, path::PathBuf}; +pub mod bits; + pub type Output = Box; pub type Input = Box;