-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathcache_aligned.rs
More file actions
75 lines (67 loc) · 1.83 KB
/
cache_aligned.rs
File metadata and controls
75 lines (67 loc) · 1.83 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::alloc::{self, Alloc, Global, Layout};
use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique, NonNull};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
alloc::Global.alloc_zeroed(Layout::from_size_align(size, CACHE_LINE_SIZE).unwrap())
.unwrap().as_ptr() as *mut u8
}
pub struct CacheAligned<T: Sized> {
ptr: Unique<T>,
}
impl<T: Sized> Drop for CacheAligned<T> {
fn drop(&mut self) {
unsafe {
alloc::Global.dealloc(
NonNull::<u8>::new_unchecked(self.ptr.as_ptr() as *mut u8),
Layout::from_size_align(size_of::<T>(), CACHE_LINE_SIZE).unwrap(),
);
}
}
}
impl<T: Sized> Deref for CacheAligned<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
impl<T: Sized> DerefMut for CacheAligned<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.ptr.as_mut() }
}
}
impl<T: Sized> CacheAligned<T> {
pub fn allocate(src: T) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::write(alloc, src);
CacheAligned {
ptr: Unique::new(alloc).unwrap(),
}
}
}
}
impl<T: Sized> Clone for CacheAligned<T>
where
T: Clone,
{
fn clone(&self) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::copy(self.ptr.as_ptr() as *const T, alloc, 1);
CacheAligned {
ptr: Unique::new(alloc).unwrap(),
}
}
}
}
impl<T: Sized> fmt::Display for CacheAligned<T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
T::fmt(&*self, f)
}
}