Skip to content

Commit b99461a

Browse files
committed
refactor non_threadsafe_alloc
1 parent 65b3714 commit b99461a

1 file changed

Lines changed: 11 additions & 15 deletions

File tree

src/non_threadsafe_alloc.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,16 @@ impl NonThreadsafeAlloc {
3030
}
3131
}
3232

33-
unsafe fn fetch_fast_alloc<R, F: FnOnce(&mut FastAlloc) -> R>(&self, f: F) -> R {
33+
unsafe fn with_fast_alloc<R, F: FnOnce(&mut FastAlloc) -> R>(&self, f: F) -> R {
3434
let mut inner = self.inner_fast_alloc.borrow_mut();
35-
if inner.is_none() {
36-
inner.replace(FastAlloc::new(self.fast_alloc_param));
37-
}
38-
f(inner.as_mut().expect("nerver"))
35+
let alloc = inner.get_or_insert_with(|| FastAlloc::new(self.fast_alloc_param));
36+
f(alloc)
3937
}
4038

41-
unsafe fn fetch_buddy_alloc<R, F: FnOnce(&mut BuddyAlloc) -> R>(&self, f: F) -> R {
39+
unsafe fn with_buddy_alloc<R, F: FnOnce(&mut BuddyAlloc) -> R>(&self, f: F) -> R {
4240
let mut inner = self.inner_buddy_alloc.borrow_mut();
43-
if inner.is_none() {
44-
inner.replace(BuddyAlloc::new(self.buddy_alloc_param));
45-
}
46-
f(inner.as_mut().expect("nerver"))
41+
let alloc = inner.get_or_insert_with(|| BuddyAlloc::new(self.buddy_alloc_param));
42+
f(alloc)
4743
}
4844
}
4945

@@ -52,18 +48,18 @@ unsafe impl GlobalAlloc for NonThreadsafeAlloc {
5248
let bytes = layout.size();
5349
// use BuddyAlloc if size is larger than MAX_FAST_ALLOC_SIZE
5450
if bytes > MAX_FAST_ALLOC_SIZE {
55-
self.fetch_buddy_alloc(|alloc| alloc.malloc(bytes))
51+
self.with_buddy_alloc(|alloc| alloc.malloc(bytes))
5652
} else {
5753
// try fast alloc, fallback to BuddyAlloc if failed
58-
let mut p = self.fetch_fast_alloc(|alloc| alloc.malloc(bytes));
54+
let mut p = self.with_fast_alloc(|alloc| alloc.malloc(bytes));
5955
if p.is_null() {
60-
p = self.fetch_buddy_alloc(|alloc| alloc.malloc(bytes));
56+
p = self.with_buddy_alloc(|alloc| alloc.malloc(bytes));
6157
}
6258
p
6359
}
6460
}
6561
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
66-
let freed = self.fetch_fast_alloc(|alloc| {
62+
let freed = self.with_fast_alloc(|alloc| {
6763
if alloc.contains_ptr(ptr) {
6864
alloc.free(ptr);
6965
true
@@ -72,7 +68,7 @@ unsafe impl GlobalAlloc for NonThreadsafeAlloc {
7268
}
7369
});
7470
if !freed {
75-
self.fetch_buddy_alloc(|alloc| alloc.free(ptr));
71+
self.with_buddy_alloc(|alloc| alloc.free(ptr));
7672
}
7773
}
7874
}

0 commit comments

Comments
 (0)