bulk_allocator 0.5.2

Implementations of GlobalAlloc holding memory cache.
Documentation
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
// Copyright 2020-2023 Shin Yoshida
//
// "LGPL-3.0-or-later OR Apache-2.0"
//
// This is part of rust-bulk-allocator
//
//  rust-bulk-allocator is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  rust-bulk-allocator is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with rust-bulk-allocator.  If not, see <http://www.gnu.org/licenses/>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::rb_tree::{Color, Direction, RBTree, TreeBucket};
use std::cmp::Ordering;
use std::mem::size_of;
use std::ptr::NonNull;

type Link<T> = Option<NonNull<T>>;
use super::ALIGN;
pub const MIN_CACHE_SIZE: usize = size_of::<Bucket>();

#[cfg(debug_assertions)]
const MSB: usize = 1 << (size_of::<usize>() * 8 - 1);

/// The 4 least significant bits of each pointer is used for the color and the size.
/// This is OK because
/// - Rust does not support pointers that the most significant bit is 1.
/// - The alignment of the pointer is 8 bytes at least, so the 3 least significant bits are 0.
struct Bucket {
    left_order_: usize,
    right_order_: usize,

    left_size_: usize,
    right_size_: usize,
}

impl Bucket {
    fn left_order(&self) -> Link<Self> {
        let ptr = (self.left_order_ >> 1) & !0x07;
        NonNull::new(ptr as *mut Self)
    }

    fn set_left_order(&mut self, ptr: Link<Self>) {
        let ptr = ptr.map_or(0, |ptr| ptr.as_ptr() as usize);
        debug_assert!(ptr & 0x07 == 0);
        debug_assert!(ptr & MSB == 0);

        self.left_order_ &= 0x0f;
        self.left_order_ |= ptr << 1;
    }

    fn right_order(&self) -> Link<Self> {
        let ptr = (self.right_order_ >> 1) & !0x07;
        NonNull::new(ptr as *mut Self)
    }

    fn set_right_order(&mut self, ptr: Link<Self>) {
        let ptr = ptr.map_or(0, |ptr| ptr.as_ptr() as usize);
        debug_assert!(ptr & 0x07 == 0);
        debug_assert!(ptr & MSB == 0);

        self.right_order_ &= 0x0f;
        self.right_order_ |= ptr << 1;
    }

    fn left_size(&self) -> Link<Self> {
        let ptr = (self.left_size_ >> 1) & !0x07;
        NonNull::new(ptr as *mut Self)
    }

    fn set_left_size(&mut self, ptr: Link<Self>) {
        let ptr = ptr.map_or(0, |ptr| ptr.as_ptr() as usize);
        debug_assert!(ptr & 0x07 == 0);
        debug_assert!(ptr & MSB == 0);

        self.left_size_ &= 0x0f;
        self.left_size_ |= ptr << 1;
    }

    fn right_size(&self) -> Link<Self> {
        let ptr = (self.right_size_ >> 1) & !0x07;
        NonNull::new(ptr as *mut Self)
    }

    fn set_right_size(&mut self, ptr: Link<Self>) {
        let ptr = ptr.map_or(0, |ptr| ptr.as_ptr() as usize);
        debug_assert!(ptr & 0x07 == 0);
        debug_assert!(ptr & MSB == 0);

        self.right_size_ &= 0x0f;
        self.right_size_ |= ptr << 1;
    }

    /// Read the 0x04 bit of `self.left_order_`.
    fn order_color(&self) -> Color {
        if self.left_order_ & 0x04 == 0 {
            Color::Black
        } else {
            Color::Red
        }
    }

    /// Update the 0x04 bit of `self.left_order_`.
    fn set_order_color(&mut self, color: Color) {
        match color {
            Color::Black => self.left_order_ &= !0x04,
            Color::Red => self.left_order_ |= 0x04,
        }
    }

    /// Read the 0x02 bit of `self.left_order_`.
    fn size_color(&self) -> Color {
        if self.left_order_ & 0x02 == 0 {
            Color::Black
        } else {
            Color::Red
        }
    }

    /// Update the 0x02 bit of `self.left_order_`.
    fn set_size_color(&mut self, color: Color) {
        match color {
            Color::Black => self.left_order_ &= !0x02,
            Color::Red => self.left_order_ |= 0x02,
        }
    }

    /// Read the 0x01 bit of `self.left_order_`, 0x0f bit of `self.right_order_`,
    /// 0x0f bit of `self.left_size_` and 0x0f bit of `self.right_size_`.
    fn size(&self) -> usize {
        let a = (self.left_order_ & 0x01) << 15;
        let b = (self.right_order_ & 0x0f) << 11;
        let c = (self.left_size_ & 0x0f) << 7;
        let d = (self.right_size_ & 0x0f) << 3;
        a + b + c + d
    }

    /// Update the 0x01 bit of `self.left_order_`, 0x0f bit of `self.right_order_`,
    /// 0x0f bit of `self.left_size_` and 0x0f bit of `self.right_size_`.
    fn set_size(&mut self, size: usize) {
        debug_assert!(size <= u16::MAX as usize);
        debug_assert!(size & 0x07 == 0);

        self.left_order_ &= !0x01;
        self.left_order_ |= size >> 15;
        self.right_order_ &= !0x0f;
        self.right_order_ |= (size >> 11) & 0x0f;
        self.left_size_ &= !0x0f;
        self.left_size_ |= (size >> 7) & 0x0f;
        self.right_size_ &= !0x0f;
        self.right_size_ |= (size >> 3) & 0x0f;
    }
}

struct SizeBucket(Bucket);

impl SizeBucket {
    pub fn init(ptr: NonNull<u8>, size: usize) {
        debug_assert!(size_of::<Self>() <= size);
        debug_assert!(size <= u16::MAX as usize);
        debug_assert!(size % ALIGN == 0);

        let this: &mut Self = unsafe { ptr.cast().as_mut() };
        this.0.set_size(size);
    }

    pub fn size(&self) -> usize {
        self.0.size()
    }
}

impl PartialEq<Self> for SizeBucket {
    fn eq(&self, other: &Self) -> bool {
        let this: *const SizeBucket = self;
        this == other
    }
}

impl Eq for SizeBucket {}

impl PartialEq<usize> for SizeBucket {
    fn eq(&self, other: &usize) -> bool {
        self.size() == *other
    }
}

#[cfg(test)]
impl PartialEq<Bucket> for SizeBucket {
    fn eq(&self, other: &Bucket) -> bool {
        unsafe { self == std::mem::transmute::<&Bucket, &Self>(other) }
    }
}

impl PartialOrd<Self> for SizeBucket {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self.0.size() == other.0.size() {
            let this: *const SizeBucket = self;
            let other: *const SizeBucket = other;
            this.partial_cmp(&other)
        } else {
            self.0.size().partial_cmp(&other.0.size())
        }
    }
}

impl Ord for SizeBucket {
    fn cmp(&self, other: &Self) -> Ordering {
        if self.0.size() == other.0.size() {
            let this: *const SizeBucket = self;
            let other: *const SizeBucket = other;
            this.cmp(&other)
        } else {
            self.0.size().cmp(&other.0.size())
        }
    }
}

impl PartialOrd<usize> for SizeBucket {
    fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
        self.size().partial_cmp(other)
    }
}

#[cfg(test)]
impl PartialOrd<Bucket> for SizeBucket {
    fn partial_cmp(&self, other: &Bucket) -> Option<Ordering> {
        unsafe { self.partial_cmp(std::mem::transmute::<&Bucket, &SizeBucket>(other)) }
    }
}

impl TreeBucket for SizeBucket {
    fn child(&self, direction: Direction) -> Link<Self> {
        match direction {
            Direction::Left => self.0.left_size().map(NonNull::cast),
            Direction::Right => self.0.right_size().map(NonNull::cast),
        }
    }

    fn set_child(&mut self, child: Link<Self>, direction: Direction) {
        match direction {
            Direction::Left => self.0.set_left_size(child.map(NonNull::cast)),
            Direction::Right => self.0.set_right_size(child.map(NonNull::cast)),
        }
    }

    fn color(&self) -> Color {
        self.0.size_color()
    }

    fn set_color(&mut self, color: Color) {
        self.0.set_size_color(color)
    }
}

struct OrderBucket(Bucket);

impl OrderBucket {
    pub fn init(ptr: NonNull<u8>, _size: usize) {
        debug_assert!(size_of::<Self>() <= _size);
        debug_assert!(_size <= u16::MAX as usize);
        debug_assert!(_size % ALIGN == 0);

        let _this: &Self = unsafe { ptr.cast().as_ref() };
        debug_assert!(_this.size() == _size);
    }

    pub fn size(&self) -> usize {
        self.0.size()
    }
}

impl PartialEq<Self> for OrderBucket {
    fn eq(&self, other: &Self) -> bool {
        self as *const Self == other
    }
}

impl PartialEq<NonNull<u8>> for OrderBucket {
    fn eq(&self, other: &NonNull<u8>) -> bool {
        let begin: *const u8 = (self as *const Self).cast();
        let end: *const u8 = unsafe { begin.add(self.size()) };
        let other: *const u8 = other.as_ptr();
        begin <= other && other < end
    }
}

#[cfg(test)]
impl PartialEq<Bucket> for OrderBucket {
    fn eq(&self, other: &Bucket) -> bool {
        unsafe { self == std::mem::transmute::<&Bucket, &Self>(other) }
    }
}

impl Eq for OrderBucket {}

impl PartialOrd<Self> for OrderBucket {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let this: *const Self = self;
        let other: *const Self = other;
        this.partial_cmp(&other)
    }
}

impl PartialOrd<NonNull<u8>> for OrderBucket {
    fn partial_cmp(&self, other: &NonNull<u8>) -> Option<Ordering> {
        if self == other {
            Some(Ordering::Equal)
        } else {
            let this: *const u8 = (self as *const Self).cast();
            let other: *const u8 = other.as_ptr();
            this.partial_cmp(&other)
        }
    }
}

#[cfg(test)]
impl PartialOrd<Bucket> for OrderBucket {
    fn partial_cmp(&self, other: &Bucket) -> Option<Ordering> {
        unsafe { self.partial_cmp(std::mem::transmute::<&Bucket, &OrderBucket>(other)) }
    }
}

impl Ord for OrderBucket {
    fn cmp(&self, other: &Self) -> Ordering {
        let this: *const Self = self;
        let other: *const Self = other;
        this.cmp(&other)
    }
}

impl TreeBucket for OrderBucket {
    fn child(&self, direction: Direction) -> Link<Self> {
        match direction {
            Direction::Left => self.0.left_order().map(NonNull::cast),
            Direction::Right => self.0.right_order().map(NonNull::cast),
        }
    }

    fn set_child(&mut self, child: Link<Self>, direction: Direction) {
        match direction {
            Direction::Left => self.0.set_left_order(child.map(NonNull::cast)),
            Direction::Right => self.0.set_right_order(child.map(NonNull::cast)),
        }
    }

    fn color(&self) -> Color {
        self.0.order_color()
    }

    fn set_color(&mut self, color: Color) {
        self.0.set_order_color(color)
    }
}

pub struct LargeCache {
    size_tree: RBTree<SizeBucket>,
    order_tree: RBTree<OrderBucket>,
}

impl LargeCache {
    pub const fn new() -> Self {
        Self {
            size_tree: RBTree::new(),
            order_tree: RBTree::new(),
        }
    }

    #[cfg(test)]
    pub fn is_empty(&self) -> bool {
        if self.size_tree.is_empty() {
            assert!(self.order_tree.is_empty());
            true
        } else {
            assert_eq!(self.order_tree.is_empty(), false);
            false
        }
    }

    pub fn alloc(&mut self, size: usize) -> Option<(NonNull<u8>, usize)> {
        debug_assert!(size % ALIGN == 0);
        debug_assert!(0 < size);

        unsafe {
            // Try to find a memory block from size_tree.
            let mut ptr = self.size_tree.remove_lower_bound(&size)?;
            let alloc_size = ptr.as_ref().size();

            // Take the end of ptr as a return value and cache again the rest
            // if the memory block is large enough.
            let rest_size = alloc_size - size;
            if size_of::<Bucket>() <= rest_size {
                // Store into size_tree again.
                let size_bucket = ptr.as_mut();
                SizeBucket::init(ptr.cast(), rest_size);
                self.size_tree.insert(size_bucket);

                // Do nothing for order_tree, because changing size does not matter to it.

                // Return
                let ret = ptr.as_ptr().cast::<u8>().add(rest_size);
                Some((NonNull::new_unchecked(ret), size))
            } else {
                // Return all of the memory block.
                let order_bucket: &mut OrderBucket = ptr.cast().as_mut();
                self.order_tree.remove(order_bucket);

                Some((ptr.cast(), alloc_size))
            }
        }
    }

    pub fn dealloc_without_merge(&mut self, ptr: NonNull<u8>, size: usize) -> bool {
        debug_assert!(ptr.as_ptr() as usize % ALIGN == 0);
        debug_assert!(size % ALIGN == 0);

        if size < size_of::<Bucket>() {
            false
        } else {
            unsafe {
                SizeBucket::init(ptr, size);
                self.size_tree.insert(ptr.cast().as_mut());

                OrderBucket::init(ptr, size);
                self.order_tree.insert(ptr.cast().as_mut());
            }

            true
        }
    }

    /// Does nothing and returns `false` if `layout` is too small to cache; otherwise, caches ptr
    /// and returns `true`.
    pub fn dealloc(&mut self, ptr: NonNull<u8>, size: usize) -> bool {
        debug_assert!(ptr.as_ptr() as usize % ALIGN == 0);
        debug_assert!(size % ALIGN == 0);

        // If the next memory block is cached, pop the block and merge to ptr.
        let size = unsafe {
            let next_ptr = NonNull::new_unchecked(ptr.as_ptr().add(size));
            match self.order_tree.remove(&next_ptr) {
                None => size,
                Some(ptr) => {
                    // The next block was cached.
                    // Remove from the size_tree as well.
                    let size_bucket: &SizeBucket = ptr.cast().as_ref();
                    self.size_tree.remove(size_bucket);

                    size + size_bucket.size()
                }
            }
        };

        // If the previous memory block is cached, enlarge the size to merge to ptr;
        // otherwise, store ptr into the cache.
        unsafe {
            let prev_ptr = NonNull::new_unchecked(ptr.as_ptr().offset(-1));
            match self.order_tree.find(&prev_ptr) {
                None => {
                    // Do nothing and return false if the size is too small.
                    if size < size_of::<Bucket>() {
                        return false;
                    }

                    SizeBucket::init(ptr, size);
                    self.size_tree.insert(ptr.cast().as_mut());

                    OrderBucket::init(ptr, size);
                    self.order_tree.insert(ptr.cast().as_mut());
                }
                Some(prev_ptr) => {
                    let order_bucket = prev_ptr.as_ref();
                    let size = size + order_bucket.size();

                    // Changeng size affect to the size_tree.
                    // Remove from size_tree, change the size, and insert into size_tree again.
                    let size_bucket: &mut SizeBucket = prev_ptr.cast().as_mut();
                    self.size_tree.remove(size_bucket);
                    SizeBucket::init(prev_ptr.cast(), size);
                    self.size_tree.insert(size_bucket);

                    // Do nothing for order_tree, because changing the size does not matter to it.
                }
            }
        }

        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_alloc() {
        let mut cache = LargeCache::new();

        // Make cache to prepare.
        type Block = [usize; 16];
        let mut blocks: Vec<Block> = Vec::with_capacity(1024);
        unsafe { blocks.set_len(1024) };
        for i in 0..blocks.len() {
            if i % 2 == 1 {
                continue;
            } else {
                let size = size_of::<Block>();
                let ptr = NonNull::from(&mut blocks[i]);
                cache.dealloc(ptr.cast(), size);
            }
        }

        // Test to allocate
        for _ in 0..8 {
            let mut pointers = Vec::new();

            for (_, size) in (0..512).zip((ALIGN..=size_of::<Block>()).cycle()) {
                let size = size - (size % ALIGN);
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(ptr.as_ptr() as usize % ALIGN == 0);
                assert!(size <= s);
                assert!(s < size + size_of::<Bucket>());

                unsafe { ptr.as_ptr().write_bytes(0xff, s) };

                // Make sure cache works well.
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };

                pointers.push((ptr, s));
            }

            for (ptr, size) in pointers {
                cache.dealloc(ptr, size);
            }
        }
    }

    #[test]
    fn test_alloc_fraction() {
        let mut buckets: Vec<Bucket> = Vec::with_capacity(3);
        unsafe { buckets.set_len(3) };

        // Cache 1 bucket, and allocate 1 byte.
        {
            let mut cache = LargeCache::new();

            // Cache 1 bucket
            {
                let ptr = NonNull::from(&mut buckets[0]);
                let size = size_of::<Bucket>();
                cache.dealloc(ptr.cast(), size);
            }

            // Alloc the minimum size
            {
                let size = ALIGN;
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(size <= s);
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };
            }

            // Make sure no cache is left.
            assert!(cache.is_empty());
        }

        // Cache a series of buckets, and allocate 1 byte and size_of::<Bucket>()
        {
            let mut cache = LargeCache::new();

            // Cache 2 buckets
            {
                let size = 2 * size_of::<Bucket>();
                let ptr = NonNull::from(&mut buckets[0]);
                cache.dealloc(ptr.cast(), size);
            }

            // Alloc the minimum bytes.
            {
                let size = ALIGN;
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(size <= s);
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };
            }

            // Alloc size_of::<Bucket>()
            {
                let size = size_of::<Bucket>();
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(size <= s);
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };
            }

            // Make sure no cache is left.
            assert!(cache.is_empty());
        }

        // Cache a series of buckets, and allocate size_of::<Bucket>() and 1 byte
        {
            let mut cache = LargeCache::new();

            // Cache 2 buckets
            {
                let size = 2 * size_of::<Bucket>();
                let ptr = NonNull::from(&mut buckets[0]);
                cache.dealloc(ptr.cast(), size);
            }

            // Alloc size_of::<Bucket>()
            {
                let size = size_of::<Bucket>();
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(size <= s);
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };
            }

            // Alloc the minimum bytes.
            {
                let size = ALIGN;
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(size <= s);
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };
            }

            // Make sure no cache is left.
            assert!(cache.is_empty());
        }

        // Cache a separated of buckets, and allocate 1 byte twice.
        {
            let mut cache = LargeCache::new();

            // Cache 2 buckets
            {
                let size = size_of::<Bucket>();
                let ptr = NonNull::from(&mut buckets[0]);
                cache.dealloc(ptr.cast(), size);

                let ptr = NonNull::from(&mut buckets[2]);
                cache.dealloc(ptr.cast(), size);
            }

            // Alloc the minimum bytes twice.
            for _ in 0..2 {
                let size = ALIGN;
                let allocated = cache.alloc(size);

                assert!(allocated.is_some());

                let (ptr, s) = allocated.unwrap();
                assert!(size <= s);
                unsafe { ptr.as_ptr().write_bytes(0xff, s) };
            }

            // Make sure no cache is left.
            assert!(cache.is_empty());
        }
    }

    #[test]
    fn test_dealloc_merge() {
        unsafe {
            let mut buckets: Vec<Bucket> = Vec::with_capacity(5);
            buckets.set_len(5);

            let mut cache = LargeCache::new();
            let size = size_of::<Bucket>();

            // dealloc the first block
            {
                cache.dealloc(NonNull::from(&mut buckets[0]).cast(), size);

                let size_ptr = cache.size_tree.find(&buckets[0]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[0]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                for i in 1..5 {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // dealloc the last block
            {
                cache.dealloc(NonNull::from(&mut buckets[4]).cast(), size);

                let size_ptr = cache.size_tree.find(&buckets[0]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[0]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                let size_ptr = cache.size_tree.find(&buckets[4]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[4]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                for i in 1..4 {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // dealloc the 2nd block
            // The 1st and the 2nd blocks are merged.
            {
                cache.dealloc(NonNull::from(&mut buckets[1]).cast(), size);

                let size_ptr = cache.size_tree.find(&buckets[0]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == 2 * size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[0]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == 2 * size_of::<Bucket>());

                let size_ptr = cache.size_tree.find(&buckets[4]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[4]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                for i in 2..4 {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // dealloc the 4th block
            // The 4th and the last blocks are merged.
            {
                cache.dealloc(NonNull::from(&mut buckets[3]).cast(), size);

                let size_ptr = cache.size_tree.find(&buckets[0]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == 2 * size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[0]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == 2 * size_of::<Bucket>());

                let size_ptr = cache.size_tree.find(&buckets[3]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == 2 * size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[3]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == 2 * size_of::<Bucket>());

                for i in 2..3 {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // dealloc the 3rd block
            // All the blocks are merged.
            {
                cache.dealloc(NonNull::from(&mut buckets[2]).cast(), size);

                let size_ptr = cache.size_tree.find(&buckets[0]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == 5 * size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[0]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == 5 * size_of::<Bucket>());

                for i in 1..5 {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }
        }
    }

    #[test]
    fn test_dealloc_small_merge() {
        unsafe {
            let mut buckets: Vec<Bucket> = Vec::with_capacity(3);
            buckets.set_len(3);

            let mut cache = LargeCache::new();
            let size = size_of::<Bucket>();

            // dealloc the 2nd block
            {
                assert!(cache.dealloc(NonNull::from(&mut buckets[1]).cast(), size));

                let size_ptr = cache.size_tree.find(&buckets[1]);
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                let order_ptr = cache.order_tree.find(&buckets[1]);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>());

                for i in [0, 2] {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // Try to dealloc the first ALIGN bytes and fail.
            {
                assert!(cache.dealloc(NonNull::from(&mut buckets[0]).cast(), ALIGN) == false);

                for i in [0, 2] {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // Dealloc the last ALIGN bytes of buckets[0]
            {
                let ptr: *mut u8 = (&mut buckets[1] as *mut Bucket).cast();
                let ptr = NonNull::new(ptr.offset(-1 * ALIGN as isize)).unwrap();
                assert!(cache.dealloc(ptr, ALIGN) == true);

                let size_ptr = cache.size_tree.find(&(size_of::<Bucket>() + ALIGN));
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>() + ALIGN);

                let order_ptr = cache.order_tree.find(&ptr);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>() + ALIGN);

                for i in [0, 2] {
                    assert!(cache.size_tree.find(&buckets[i]).is_none());
                    assert!(cache.order_tree.find(&buckets[i]).is_none());
                }
            }

            // Dealloc the first ALIGN bytes of buckets[2]
            {
                assert!(cache.dealloc(NonNull::from(&mut buckets[2]).cast(), ALIGN) == true);

                let size_ptr = cache.size_tree.find(&(size_of::<Bucket>() + 2 * ALIGN));
                assert!(size_ptr.is_some());
                assert!(size_ptr.unwrap().as_ref().size() == size_of::<Bucket>() + 2 * ALIGN);

                let ptr: *mut u8 = (&mut buckets[1] as *mut Bucket).cast();
                let ptr = NonNull::new(ptr.offset(-1 * ALIGN as isize)).unwrap();
                let order_ptr = cache.order_tree.find(&ptr);
                assert!(order_ptr.is_some());
                assert!(order_ptr.unwrap().as_ref().size() == size_of::<Bucket>() + 2 * ALIGN);
            }
        }
    }
}