-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem_read.rs
48 lines (40 loc) · 1.33 KB
/
mem_read.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::io::{Error, Read};
use std::mem::*;
use std::slice::*;
pub trait MemType {}
impl MemType for u8 {}
impl MemType for u16 {}
impl MemType for u32 {}
impl MemType for u64 {}
impl MemType for i8 {}
impl MemType for i16 {}
impl MemType for i32 {}
impl MemType for i64 {}
pub trait MemRead {
fn get<U>(&mut self) -> Result<U, Error>;
fn get_str(&mut self) -> Result<String, Error>;
fn get_str_sized(&mut self, size: usize) -> Result<String, Error>;
fn skip(&mut self, count: u64);
}
impl<T: Read> MemRead for T {
fn get<U>(&mut self) -> Result<U, Error> {
unsafe {
let mut x: U = uninitialized();
let slice = from_raw_parts_mut(&mut x as *mut U as *mut u8, size_of::<U>());
self.read_exact(slice).map(|_| x)
}
}
fn get_str(&mut self) -> Result<String, Error> {
let size = self.get::<u16>()?;
self::MemRead::get_str_sized(self, size as _)
}
fn get_str_sized(&mut self, size: usize) -> Result<String, Error> {
let mut buffer: Vec<u8> = Vec::with_capacity(size);
self.take(size as u64)
.read_to_end(&mut buffer)
.map(|_| String::from_utf8_lossy(&buffer).into())
}
fn skip(&mut self, count: u64) {
std::io::copy(&mut self.take(count), &mut std::io::sink()).expect("could not skip bytes");
}
}