use super::util::encode_u32;
use core::convert::From;
use core::ops::Deref;
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, Ord, PartialOrd)]
pub struct MsgToken {
len: u8,
bytes: [u8; 8],
}
impl MsgToken {
pub const EMPTY: MsgToken = MsgToken {
len: 0u8,
bytes: [0; 8],
};
pub fn new(x: &[u8]) -> MsgToken {
MsgToken::from(x)
}
pub fn len(&self) -> usize {
self.len as usize
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len as usize]
}
}
impl std::fmt::Display for MsgToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for b in self.as_bytes() {
write!(f, "{:02X}", b)?;
}
Ok(())
}
}
impl Default for MsgToken {
fn default() -> Self {
MsgToken::EMPTY
}
}
impl Deref for MsgToken {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_bytes()
}
}
impl core::cmp::PartialEq<[u8]> for MsgToken {
fn eq(&self, other: &[u8]) -> bool {
self.as_bytes() == other
}
}
impl core::convert::From<u32> for MsgToken {
fn from(x: u32) -> Self {
let mut bytes = [0u8; 8];
let len = encode_u32(x, &mut bytes).len();
MsgToken {
len: len as u8,
bytes,
}
}
}
impl core::convert::From<i32> for MsgToken {
fn from(x: i32) -> Self {
core::convert::Into::into(x as u32)
}
}
impl core::convert::From<u16> for MsgToken {
fn from(x: u16) -> Self {
core::convert::Into::into(x as u32)
}
}
impl core::convert::From<&[u8]> for MsgToken {
fn from(x: &[u8]) -> Self {
let mut bytes = [0u8; 8];
let len = x.len();
bytes[..len].copy_from_slice(x);
MsgToken {
len: len as u8,
bytes,
}
}
}