]> git.lizzy.rs Git - rust.git/blob - src/liballoc/raw_vec/tests.rs
Auto merge of #64047 - timvermeulen:cmp_min_max_by, r=cuviper
[rust.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 { fuel: usize }
20     unsafe impl Alloc for BoundedAlloc {
21         unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
22             let size = layout.size();
23             if size > self.fuel {
24                 return Err(AllocErr);
25             }
26             match Global.alloc(layout) {
27                 ok @ Ok(_) => { self.fuel -= size; ok }
28                 err @ Err(_) => err,
29             }
30         }
31         unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
32             Global.dealloc(ptr, layout)
33         }
34     }
35
36     let a = BoundedAlloc { fuel: 500 };
37     let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
38     assert_eq!(v.a.fuel, 450);
39     v.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
40     assert_eq!(v.a.fuel, 250);
41 }
42
43 #[test]
44 fn reserve_does_not_overallocate() {
45     {
46         let mut v: RawVec<u32> = RawVec::new();
47         // First, `reserve` allocates like `reserve_exact`.
48         v.reserve(0, 9);
49         assert_eq!(9, v.capacity());
50     }
51
52     {
53         let mut v: RawVec<u32> = RawVec::new();
54         v.reserve(0, 7);
55         assert_eq!(7, v.capacity());
56         // 97 if more than double of 7, so `reserve` should work
57         // like `reserve_exact`.
58         v.reserve(7, 90);
59         assert_eq!(97, v.capacity());
60     }
61
62     {
63         let mut v: RawVec<u32> = RawVec::new();
64         v.reserve(0, 12);
65         assert_eq!(12, v.capacity());
66         v.reserve(12, 3);
67         // 3 is less than half of 12, so `reserve` must grow
68         // exponentially. At the time of writing this test grow
69         // factor is 2, so new capacity is 24, however, grow factor
70         // of 1.5 is OK too. Hence `>= 18` in assert.
71         assert!(v.capacity() >= 12 + 12 / 2);
72     }
73 }