1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//! # bitwrap
//!
//! [![docs](https://docs.rs/bitwrap/badge.svg)](https://docs.rs/bitwrap)
//!
//! ## Intro
//!
//! bitwrap is a derive macro and interface to declare a struct data member
//! with explicit size, in bits.

#![cfg_attr(not(feature = "std"), no_std)]


use {
    core::{
        fmt,
        convert::Infallible,
    },
};


pub use {
    bitwrap_derive::BitWrap,
};


#[derive(Debug, PartialEq)]
pub struct BitWrapError;


impl fmt::Display for BitWrapError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "index out of bounds")
    }
}


#[cfg(feature = "std")]
impl std::error::Error for BitWrapError {}


impl From<Infallible> for BitWrapError {
    fn from(x: Infallible) -> BitWrapError {
        match x {}
    }
}


pub trait BitWrapExt {
    /// Build byte array
    fn pack(&self, dst: &mut [u8]) -> Result<usize, BitWrapError>;

    /// Extract object field values from byte array
    fn unpack(&mut self, src: &[u8]) -> Result<usize, BitWrapError>;
}


#[cfg(feature = "std")]
impl BitWrapExt for Vec<u8> {
    #[inline]
    fn pack(&self, dst: &mut [u8]) -> Result<usize, BitWrapError> {
        let len = self.len();
        if dst.len() >= len {
            dst[.. len].clone_from_slice(self.as_slice());
            Ok(len)
        } else {
            Err(BitWrapError)
        }
    }

    #[inline]
    fn unpack(&mut self, src: &[u8]) -> Result<usize, BitWrapError> {
        self.extend_from_slice(src);
        Ok(src.len())
    }
}


#[cfg(feature = "std")]
impl<T: BitWrapExt + Default> BitWrapExt for Vec<T> {
    #[inline]
    fn pack(&self, dst: &mut [u8]) -> Result<usize, BitWrapError> {
        let mut skip = 0;
        for item in self {
            skip += item.pack(&mut dst[skip ..])?;
        }
        Ok(skip)
    }

    #[inline]
    fn unpack(&mut self, src: &[u8]) -> Result<usize, BitWrapError> {
        let mut skip = 0;
        while skip < src.len() {
            let mut item = T::default();
            skip += item.unpack(&src[skip ..])?;
            self.push(item);
        }
        Ok(skip)
    }
}


#[cfg(feature = "std")]
impl BitWrapExt for String {
    #[inline]
    fn pack(&self, dst: &mut [u8]) -> Result<usize, BitWrapError> {
        let s = self.as_bytes();
        let len = s.len();
        if dst.len() >= len {
            dst[.. len].clone_from_slice(s);
            Ok(len)
        } else {
            Err(BitWrapError)
        }
    }

    #[inline]
    fn unpack(&mut self, src: &[u8]) -> Result<usize, BitWrapError> {
        let s = match std::str::from_utf8(src) {
            Ok(v) => v,
            Err(_) => return Err(BitWrapError),
        };

        self.push_str(s);
        Ok(src.len())
    }
}