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
use core::cell::Cell;
use crate::utils;

const ACCESSIBLE_MASK: u16 = 1u16 << (u16::BITS - 1);
const COUNTER_MASK: u16 = !ACCESSIBLE_MASK;
const INITIAL_VALUE: u16 = 0;
const INITIAL_VALUE_ACCESSIBLE: u16 = INITIAL_VALUE | ACCESSIBLE_MASK;

// pub(crate) to make it available in tests
pub(crate) const MAX: u16 = !ACCESSIBLE_MASK; // First 15 bits to 1

/// Internal representation:
/// ```text
/// +-----------+-----------+
/// | A: 1 bits | B: 15 bit |  Total: 16 bits
/// +-----------+-----------+
/// ```
///
/// * `A` is `1` when the `Cc` is accessible, `0` otherwise
/// * `B` is the weak counter
#[derive(Clone, Debug)]
pub(crate) struct WeakMetadata {
    weak_counter: Cell<u16>,
}

pub(crate) struct OverflowError;

impl WeakMetadata {
    #[inline]
    #[must_use]
    pub(crate) fn new(accessible: bool) -> WeakMetadata {
        WeakMetadata {
            weak_counter: Cell::new(if accessible {
                INITIAL_VALUE_ACCESSIBLE
            } else {
                INITIAL_VALUE
            })
        }
    }

    #[inline]
    pub(crate) fn increment_counter(&self) -> Result<(), OverflowError> {
        if self.counter() == MAX {
            utils::cold(); // This branch of the if is rarely taken
            Err(OverflowError)
        } else {
            self.weak_counter.set(self.weak_counter.get() + 1);
            Ok(())
        }
    }

    #[inline]
    pub(crate) fn decrement_counter(&self) -> Result<(), OverflowError> {
        if self.counter() == 0 {
            utils::cold(); // This branch of the if is rarely taken
            Err(OverflowError)
        } else {
            self.weak_counter.set(self.weak_counter.get() - 1);
            Ok(())
        }
    }

    #[inline]
    pub(crate) fn counter(&self) -> u16 {
        self.weak_counter.get() & COUNTER_MASK
    }

    #[inline]
    pub(crate) fn is_accessible(&self) -> bool {
        (self.weak_counter.get() & ACCESSIBLE_MASK) != 0
    }

    #[inline]
    pub(crate) fn set_accessible(&self, accessible: bool) {
        if accessible {
            self.weak_counter.set(self.weak_counter.get() | ACCESSIBLE_MASK);
        } else {
            self.weak_counter.set(self.weak_counter.get() & !ACCESSIBLE_MASK);
        }
    }
}