]> git.proxmox.com Git - rustc.git/blob - src/liballoc/raw_vec/tests.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / liballoc / raw_vec / tests.rs
1 use super::*;
2
3 #[test]
4 fn allocator_param() {
5 use crate::alloc::AllocErr;
6
7 // Writing a test of integration between third-party
8 // allocators and `RawVec` is a little tricky because the `RawVec`
9 // API does not expose fallible allocation methods, so we
10 // cannot check what happens when allocator is exhausted
11 // (beyond detecting a panic).
12 //
13 // Instead, this just checks that the `RawVec` methods do at
14 // least go through the Allocator API when it reserves
15 // storage.
16
17 // A dumb allocator that consumes a fixed amount of fuel
18 // before allocation attempts start failing.
19 struct BoundedAlloc {
20 fuel: usize,
21 }
22 unsafe impl Alloc for BoundedAlloc {
23 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
24 let size = layout.size();
25 if size > self.fuel {
26 return Err(AllocErr);
27 }
28 match Global.alloc(layout) {
29 ok @ Ok(_) => {
30 self.fuel -= size;
31 ok
32 }
33 err @ Err(_) => err,
34 }
35 }
36 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
37 Global.dealloc(ptr, layout)
38 }
39 }
40
41 let a = BoundedAlloc { fuel: 500 };
42 let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
43 assert_eq!(v.a.fuel, 450);
44 v.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
45 assert_eq!(v.a.fuel, 250);
46 }
47
48 #[test]
49 fn reserve_does_not_overallocate() {
50 {
51 let mut v: RawVec<u32> = RawVec::new();
52 // First, `reserve` allocates like `reserve_exact`.
53 v.reserve(0, 9);
54 assert_eq!(9, v.capacity());
55 }
56
57 {
58 let mut v: RawVec<u32> = RawVec::new();
59 v.reserve(0, 7);
60 assert_eq!(7, v.capacity());
61 // 97 if more than double of 7, so `reserve` should work
62 // like `reserve_exact`.
63 v.reserve(7, 90);
64 assert_eq!(97, v.capacity());
65 }
66
67 {
68 let mut v: RawVec<u32> = RawVec::new();
69 v.reserve(0, 12);
70 assert_eq!(12, v.capacity());
71 v.reserve(12, 3);
72 // 3 is less than half of 12, so `reserve` must grow
73 // exponentially. At the time of writing this test grow
74 // factor is 2, so new capacity is 24, however, grow factor
75 // of 1.5 is OK too. Hence `>= 18` in assert.
76 assert!(v.capacity() >= 12 + 12 / 2);
77 }
78 }