Make deleting on LinkedList aware of the allocator · model-checking/verify-rust-std@fbb5246 (original) (raw)

2 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -1705,7 +1705,7 @@ impl<'a, T, A: Allocator> CursorMut<'a, T, A> {
1705 1705 unsafe {
1706 1706 self.current = unlinked_node.as_ref().next;
1707 1707 self.list.unlink_node(unlinked_node);
1708 -let unlinked_node = Box::from_raw(unlinked_node.as_ptr());
1708 +let unlinked_node = Box::from_raw_in(unlinked_node.as_ptr(), &self.list.alloc);
1709 1709 Some(unlinked_node.element)
1710 1710 }
1711 1711 }
@@ -1946,7 +1946,7 @@ where
1946 1946 if (self.pred)(&mut node.as_mut().element) {
1947 1947 // `unlink_node` is okay with aliasing `element` references.
1948 1948 self.list.unlink_node(node);
1949 -return Some(Box::from_raw(node.as_ptr()).element);
1949 +return Some(Box::from_raw_in(node.as_ptr(), &self.list.alloc).element);
1950 1950 }
1951 1951 }
1952 1952 }
Original file line number Diff line number Diff line change
@@ -1164,3 +1164,42 @@ fn test_drop_panic() {
1164 1164
1165 1165 assert_eq!(unsafe { DROPS }, 8);
1166 1166 }
1167 +
1168 +#[test]
1169 +fn test_allocator() {
1170 +use core::alloc::AllocError;
1171 +use core::alloc::Allocator;
1172 +use core::alloc::Layout;
1173 +use core::cell::Cell;
1174 +
1175 +struct A {
1176 +has_allocated: Cell<bool>,
1177 +has_deallocated: Cell<bool>,
1178 +}
1179 +
1180 +unsafe impl Allocator for A {
1181 +fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
1182 +assert!(!self.has_allocated.get());
1183 +self.has_allocated.set(true);
1184 +
1185 +Global.allocate(layout)
1186 +}
1187 +
1188 +unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
1189 +assert!(!self.has_deallocated.get());
1190 +self.has_deallocated.set(true);
1191 +
1192 +unsafe { Global.deallocate(ptr, layout) }
1193 +}
1194 +}
1195 +
1196 +let alloc = &A { has_allocated: Cell::new(false), has_deallocated: Cell::new(false) };
1197 +{
1198 +let mut list = LinkedList::new_in(alloc);
1199 + list.push_back(5u32);
1200 + list.remove(0);
1201 +}
1202 +
1203 +assert!(alloc.has_allocated.get());
1204 +assert!(alloc.has_deallocated.get());
1205 +}