smartstring/
marker_byte.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6pub(crate) enum Discriminant {
7    Boxed,
8    Inline,
9}
10
11impl Discriminant {
12    #[inline(always)]
13    pub(crate) const fn from_bit(bit: bool) -> Self {
14        if bit {
15            Self::Inline
16        } else {
17            Self::Boxed
18        }
19    }
20
21    #[inline(always)]
22    const fn bit(self) -> u8 {
23        match self {
24            Self::Boxed => 0,
25            Self::Inline => 1,
26        }
27    }
28}
29
30#[derive(Clone, Copy, Debug)]
31pub(crate) struct Marker(u8);
32
33impl Marker {
34    #[inline(always)]
35    const fn assemble(discriminant: Discriminant, data: u8) -> u8 {
36        data << 1 | discriminant.bit()
37    }
38
39    #[inline(always)]
40    pub(crate) const fn empty() -> Self {
41        Self(Self::assemble(Discriminant::Inline, 0))
42    }
43
44    #[inline(always)]
45    pub(crate) const fn new_inline(data: u8) -> Self {
46        debug_assert!(data < 0x80);
47        Self(Self::assemble(Discriminant::Inline, data))
48    }
49
50    #[inline(always)]
51    pub(crate) const fn discriminant(self) -> Discriminant {
52        Discriminant::from_bit(self.0 & 0x01 != 0)
53    }
54
55    #[inline(always)]
56    pub(crate) const fn data(self) -> u8 {
57        self.0 >> 1
58    }
59
60    #[inline(always)]
61    pub(crate) fn set_data(&mut self, byte: u8) {
62        debug_assert!(byte < 0x80);
63        self.0 = Self::assemble(self.discriminant(), byte);
64    }
65}