You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
yuurei/src/bytes.rs

109 lines
2.5 KiB

use std::{
fmt,
error,
};
use libc::c_void;
pub unsafe fn refer<'a, T>(src: &'a T) -> &'a [u8]
where T: ?Sized
{
std::slice::from_raw_parts(src as *const T as *const u8, std::mem::size_of_val(src))
}
pub unsafe fn refer_mut<'a, T>(src: &'a mut T) -> &'a mut [u8]
where T: ?Sized
{
std::slice::from_raw_parts_mut(src as *mut T as *mut u8, std::mem::size_of_val(src))
}
pub unsafe fn derefer<'a, T>(src: &'a [u8]) -> &'a T
{
assert!(src.len() >= std::mem::size_of::<T>());
&*(&src[0] as *const u8 as *const T)
}
pub unsafe fn derefer_mut<'a, T>(src: &'a mut [u8]) -> &'a mut T
{
assert!(src.len() >= std::mem::size_of::<T>());
&mut *(&mut src[0] as *mut u8 as *mut T)
}
mod old {
use super::*;
/// Represents a type that can be converted from bytes to itself
pub trait FromBytes: Sized
{
type Error;
fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Self,Self::Error>;
}
/// Represents a type that can be converted into bytes
pub trait IntoBytes:Sized
{
fn into_bytes(self) -> Box<[u8]>;
}
impl<T: Into<Box<[u8]>>> IntoBytes for T
{
#[inline] fn into_bytes(self) -> Box<[u8]>
{
self.into()
}
}
impl FromBytes for Vec<u8>
{
type Error = !;
#[inline] fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Self,Self::Error>
{
Ok(Vec::from(bytes.as_ref()))
}
}
impl FromBytes for Box<[u8]>
{
type Error = !;
#[inline] fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Self,Self::Error>
{
Ok(Vec::from(bytes.as_ref()).into_boxed_slice())
}
}
/// The error used when a `FromBytes` conversion fails because the buffer was not the correct size
#[derive(Debug)]
pub struct SizeError;
impl error::Error for SizeError{}
impl fmt::Display for SizeError
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
write!(f,"buffer was not the correct size")
}
}
}
/// Copy slice of bytes only
///
/// # Notes
/// `dst` and `src` must not overlap. See [move_slice].
pub fn copy_slice(dst: &mut [u8], src: &[u8]) -> usize
{
let sz = std::cmp::min(dst.len(),src.len());
unsafe {
libc::memcpy(&mut dst[0] as *mut u8 as *mut c_void, &src[0] as *const u8 as *const c_void, sz);
}
sz
}
/// Move slice of bytes only
///
/// # Notes
/// `dst` and `src` can overlap.
pub fn move_slice(dst: &mut [u8], src: &[u8]) -> usize
{
let sz = std::cmp::min(dst.len(),src.len());
unsafe {
libc::memmove(&mut dst[0] as *mut u8 as *mut c_void, &src[0] as *const u8 as *const c_void, sz);
}
sz
}