-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbytes.rs
44 lines (35 loc) · 900 Bytes
/
bytes.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
use std::mem::size_of_val;
use std::slice::from_raw_parts_mut;
pub trait Bytes {
// Because this trait is intended to provide zero-copy raw access, it would be racy if it
// accepted non-mut refs.
fn bytes<'a>(&'a mut self) -> &'a mut [u8];
}
pub trait DefaultBytes {}
impl<T: DefaultBytes> Bytes for T {
fn bytes<'a>(&'a mut self) -> &'a mut [u8] {
unsafe {
from_raw_parts_mut(self as *mut T as *mut u8, size_of_val(self))
}
}
}
impl DefaultBytes for () {}
impl DefaultBytes for i64 {}
impl DefaultBytes for usize {}
impl<S: DefaultBytes, T: DefaultBytes> DefaultBytes for (S, T) {}
#[test]
fn unit() {
assert_eq!(0, ().bytes().len());
}
impl Bytes for String {
fn bytes<'a>(&'a mut self) -> &'a mut [u8] {
unsafe {
self.as_bytes_mut()
}
}
}
#[test]
fn string() {
let msg = "The quick brown fox jumps over the lazy hen.";
assert_eq!(msg.len(), msg.bytes().len());
}