cuprate-hinto-janai/net/epee-encoding/src/io.rs
hinto-janai 57af45e01d
epee-encoding: enable workspace lints (#294)
* epee-encoding: enable workspace lints

* fmt

* fixes

* fixes

* fmt
2024-09-20 15:13:55 +01:00

48 lines
988 B
Rust

use bytes::{Buf, BufMut};
use crate::error::*;
#[inline]
pub(crate) fn checked_read_primitive<B: Buf, R: Sized>(
b: &mut B,
read: impl Fn(&mut B) -> R,
) -> Result<R> {
checked_read(b, read, size_of::<R>())
}
#[inline]
pub(crate) fn checked_read<B: Buf, R>(
b: &mut B,
read: impl Fn(&mut B) -> R,
size: usize,
) -> Result<R> {
if b.remaining() < size {
Err(Error::IO("Not enough bytes in buffer to build object."))
} else {
Ok(read(b))
}
}
#[inline]
pub(crate) fn checked_write_primitive<B: BufMut, T: Sized>(
b: &mut B,
write: impl Fn(&mut B, T),
t: T,
) -> Result<()> {
checked_write(b, write, t, size_of::<T>())
}
#[inline]
pub(crate) fn checked_write<B: BufMut, T>(
b: &mut B,
write: impl Fn(&mut B, T),
t: T,
size: usize,
) -> Result<()> {
if b.remaining_mut() < size {
Err(Error::IO("Not enough capacity to write object."))
} else {
write(b, t);
Ok(())
}
}