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
use std::cmp::PartialEq;

/// [`Tag`] is a four-state `Enum` that can be embedded in a pointer as the two least
/// significant bits of the pointer value.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum Tag {
    /// None tagged.
    None,
    /// The first bit is tagged.
    First,
    /// The second bit is tagged.
    Second,
    /// Both bits are tagged.
    Both,
}

impl Tag {
    /// Interprets the [`Tag`] as an integer.
    #[inline]
    pub(super) const fn value(self) -> usize {
        match self {
            Self::None => 0,
            Self::First => 1,
            Self::Second => 2,
            Self::Both => 3,
        }
    }

    /// Returns the tag embedded in the pointer.
    #[inline]
    pub(super) fn into_tag<P>(ptr: *const P) -> Self {
        match ((ptr as usize & 1) == 1, (ptr as usize & 2) == 2) {
            (false, false) => Tag::None,
            (true, false) => Tag::First,
            (false, true) => Tag::Second,
            _ => Tag::Both,
        }
    }

    /// Sets a tag, overwriting any existing tag in the pointer.
    #[inline]
    pub(super) fn update_tag<P>(ptr: *const P, tag: Tag) -> *const P {
        (((ptr as usize) & (!3)) | tag.value()) as *const P
    }

    /// Returns the pointer with the tag bits erased.
    #[inline]
    pub(super) fn unset_tag<P>(ptr: *const P) -> *const P {
        ((ptr as usize) & (!3)) as *const P
    }
}

impl TryFrom<u8> for Tag {
    type Error = u8;

    #[inline]
    fn try_from(val: u8) -> Result<Self, Self::Error> {
        match val {
            0 => Ok(Tag::None),
            1 => Ok(Tag::First),
            2 => Ok(Tag::Second),
            3 => Ok(Tag::Both),
            _ => Err(val),
        }
    }
}

impl From<Tag> for u8 {
    #[inline]
    fn from(t: Tag) -> Self {
        match t {
            Tag::None => 0,
            Tag::First => 1,
            Tag::Second => 2,
            Tag::Both => 3,
        }
    }
}