nemicosm/src/num.rs

73 lines
1.8 KiB
Rust

use std::{
io::{self, Read, Write},
num::TryFromIntError,
ops::BitAnd,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Vu64(pub(crate) u64);
impl Vu64 {
pub(crate) fn read<R: Read + ?Sized>(r: &mut R) -> io::Result<Self> {
leb128::read::unsigned(r).map_err(leb_err).map(Self)
}
pub(crate) fn write<W: Write + ?Sized>(&self, w: &mut W) -> io::Result<usize> {
leb128::write::unsigned(w, self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Vu32(pub(crate) u32);
impl Vu32 {
pub(crate) fn read<R: Read + ?Sized>(r: &mut R) -> io::Result<Self> {
leb128::read::unsigned(r)
.map_err(leb_err)?
.try_into()
.map(Self)
.map_err(conv_err)
}
pub(crate) fn write<W: Write + ?Sized>(&self, w: &mut W) -> io::Result<usize> {
leb128::write::unsigned(w, self.0.into())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Vi32(pub(crate) i32);
impl Vi32 {
pub(crate) fn read<R: Read + ?Sized>(r: &mut R) -> io::Result<Self> {
leb128::read::signed(r)
.map_err(leb_err)?
.try_into()
.map(Self)
.map_err(conv_err)
}
pub(crate) fn write<W: Write + ?Sized>(&self, w: &mut W) -> io::Result<usize> {
leb128::write::signed(w, self.0.into())
}
}
fn conv_err(e: TryFromIntError) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, e)
}
fn leb_err(e: leb128::read::Error) -> io::Error {
match e {
leb128::read::Error::IoError(e) => e,
leb128::read::Error::Overflow => io::Error::new(io::ErrorKind::InvalidData, e),
}
}
impl BitAnd<u64> for Vu64 {
type Output = u64;
fn bitand(self, rhs: u64) -> Self::Output {
self.0 & rhs
}
}