chore: implement ToBytes/FromBytes for u8 and bool values

This commit is contained in:
zach
2024-08-12 16:59:33 -07:00
parent f0c9640e1e
commit a5679787a0
2 changed files with 33 additions and 0 deletions

View File

@@ -105,6 +105,23 @@ impl FromBytesOwned for String {
}
}
impl FromBytesOwned for u8 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
if data.is_empty() {
anyhow::bail!("not enough bytes, expected 1, got 0");
}
Ok(data[0])
}
}
impl FromBytesOwned for bool {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
let x: u8 = u8::from_bytes_owned(data)?;
Ok(if x == 0 { false } else { true })
}
}
impl FromBytesOwned for f64 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))

View File

@@ -128,6 +128,22 @@ impl<'a> ToBytes<'a> for i32 {
}
}
impl<'a> ToBytes<'a> for u8 {
type Bytes = [u8; 1];
fn to_bytes(&self) -> Result<Self::Bytes, Error> {
Ok([*self])
}
}
impl<'a> ToBytes<'a> for bool {
type Bytes = [u8; 1];
fn to_bytes(&self) -> Result<Self::Bytes, Error> {
Ok([if *self { 1 } else { 0 }])
}
}
impl<'a> ToBytes<'a> for u64 {
type Bytes = [u8; 8];