Looking for feedback on bit manip techniques


pub trait BitManipT {
    fn bit_set(&mut self, lhs: usize, rhs: usize, v: Self);

    fn bit_get(&self, lhs: usize, rhs: usize) -> Self;
}

impl BitManipT for u8 {
    #[inline(always)]
    fn bit_set(&mut self, lhs: usize, rhs: usize, v: u8) {
        let rhs_side = *self >> rhs;
        let lhs_side = (*self << (8 - lhs)) >> (8 - lhs);
        *self = (rhs_side << rhs) + (v << lhs) + lhs_side;}

    #[inline(always)]
    fn bit_get(&self, lhs: usize, rhs: usize) -> u8 {
        (self << (8 - rhs)) >> (8 - rhs + lhs)}}

impl BitManipT for u16 {
    #[inline(always)]
    fn bit_set(&mut self, lhs: usize, rhs: usize, v: u16) {
        let rhs_side = *self >> rhs;
        let lhs_side = (*self << (16 - lhs)) >> (16 - lhs);
        *self = (rhs_side << rhs) + (v << lhs) + lhs_side;}

    #[inline(always)]
    fn bit_get(&self, lhs: usize, rhs: usize) -> u16 {
        (self << (16 - rhs)) >> (16 - rhs + lhs)}}

impl BitManipT for u32 {
    #[inline(always)]
    fn bit_set(&mut self, lhs: usize, rhs: usize, v: u32) {
        let rhs_side = *self >> rhs;
        let lhs_side = (*self << (32 - lhs)) >> (32 - lhs);
        *self = (rhs_side << rhs) + (v << lhs) + lhs_side;}

    #[inline(always)]
    fn bit_get(&self, lhs: usize, rhs: usize) -> u32 {
        (self << (32 - rhs)) >> (32 - rhs + lhs)}}

impl BitManipT for u64 {
    #[inline(always)]
    fn bit_set(&mut self, lhs: usize, rhs: usize, v: u64) {
        let rhs_side = *self >> rhs;
        let lhs_side = (*self << (64 - lhs)) >> (64 - lhs);
        *self = (rhs_side << rhs) + (v << lhs) + lhs_side;}

    #[inline(always)]
    fn bit_get(&self, lhs: usize, rhs: usize) -> u64 {
        (self << (64 - rhs)) >> (64 - rhs + lhs)}}

Motivated by original post at Get last k bits of a uN - #5 by newpavlov .

Looking for critical feedback.

Your rhs and lhs names seem to be mixed up.

Also, missing would be an implementation for u128

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.