summaryrefslogtreecommitdiffstats
path: root/vendor/sharded-slab/src/tests/custom_config.rs
blob: 77f7259356f586f6a90bc3246f418bf6d2fdb61b (plain)
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
//! Ensures that a custom config behaves as the default config, until limits are reached.
//! Prevents regression after #80.

use crate::{cfg::CfgPrivate, Config, Slab};

struct CustomConfig;

#[cfg(target_pointer_width = "64")]
impl Config for CustomConfig {
    const INITIAL_PAGE_SIZE: usize = 32;
    const MAX_PAGES: usize = 15;
    const MAX_THREADS: usize = 256;
    const RESERVED_BITS: usize = 24;
}

#[cfg(not(target_pointer_width = "64"))]
impl Config for CustomConfig {
    const INITIAL_PAGE_SIZE: usize = 16;
    const MAX_PAGES: usize = 6;
    const MAX_THREADS: usize = 128;
    const RESERVED_BITS: usize = 12;
}

// We should repeat actions several times to detect invalid lifecycle changes.
const ITERS: u64 = 5;

#[track_caller]
fn slab_eq(mut lhs: Slab<u64, impl Config>, mut rhs: Slab<u64, impl Config>) {
    let mut lhs_vec = lhs.unique_iter().collect::<Vec<_>>();
    lhs_vec.sort_unstable();
    let mut rhs_vec = rhs.unique_iter().collect::<Vec<_>>();
    rhs_vec.sort_unstable();
    assert_eq!(lhs_vec, rhs_vec);
}

/// Calls `insert(); remove()` multiple times to detect invalid releasing.
/// Initially, it revealed bugs in the `Slot::release_with()` implementation.
#[test]
fn insert_remove() {
    eprintln!("bits={}; config={:#?}", usize::BITS, CustomConfig::debug());

    let default_slab = Slab::<u64, _>::new();
    let custom_slab = Slab::<u64, _>::new_with_config::<CustomConfig>();

    for i in 0..=ITERS {
        let idx = default_slab.insert(i).unwrap();
        assert!(default_slab.remove(idx));

        let idx = custom_slab.insert(i).unwrap();
        assert!(custom_slab.remove(idx));
    }

    slab_eq(custom_slab, default_slab);
}

/// Calls `get()` multiple times to detect invalid ref counting.
/// Initially, it revealed bugs in the `Slot::get()` implementation.
#[test]
fn double_get() {
    eprintln!("bits={}; config={:#?}", usize::BITS, CustomConfig::debug());

    let default_slab = Slab::<u64, _>::new();
    let custom_slab = Slab::<u64, _>::new_with_config::<CustomConfig>();

    for i in 0..=ITERS {
        let idx = default_slab.insert(i).unwrap();
        assert!(default_slab.get(idx).is_some());
        assert!(default_slab.get(idx).is_some());
        assert!(default_slab.remove(idx));

        let idx = custom_slab.insert(i).unwrap();
        assert!(custom_slab.get(idx).is_some());
        assert!(custom_slab.get(idx).is_some());
        assert!(custom_slab.remove(idx));
    }

    slab_eq(custom_slab, default_slab);
}