Skip to main content

azalea_world/
bit_storage.rs

1use std::{
2    error::Error,
3    fmt::{self, Display},
4};
5
6// fast constant division
7#[rustfmt::skip]
8const MAGIC: [(i32, i32, u32); 64] = [
9    // mul, add, shift
10    (1, 0, 0), // divide by 1
11    (1, 0, 1), // divide by 2, etc
12    (0x55555555, 0x55555555, 32),
13    (1, 0, 2),
14    (0x33333333, 0x33333333, 32),
15    (0x2AAAAAAA, 0x2AAAAAAA, 32),
16    (0x24924924, 0x24924924, 32),
17    (1, 0, 3),
18    (0x1C71C71C, 0x1C71C71C, 32),
19    (0x19999999, 0x19999999, 32),
20    (0x1745D174, 0x1745D174, 32),
21    (0x15555555, 0x15555555, 32),
22    (0x13B13B13, 0x13B13B13, 32),
23    (0x12492492, 0x12492492, 32),
24    (0x11111111, 0x11111111, 32),
25    (1, 0, 4),
26    (0xF0F0F0F, 0xF0F0F0F, 32),
27    (0xE38E38E, 0xE38E38E, 32),
28    (0xD79435E, 0xD79435E, 32),
29    (0x7FFFFFF8, 0x7FFFFFF8, 32),
30    (0xC30C30C, 0xC30C30C, 32),
31    (0xBA2E8BA, 0xBA2E8BA, 32),
32    (0xB21642C, 0xB21642C, 32),
33    (0xAAAAAAA, 0xAAAAAAA, 32),
34    (0xA3D70A3, 0xA3D70A3, 32),
35    (0x9D89D89, 0x9D89D89, 32),
36    (0x97B425E, 0x97B425E, 32),
37    (0x9249249, 0x9249249, 32),
38    (0x8D3DCB0, 0x8D3DCB0, 32),
39    (0x8888888, 0x8888888, 32),
40    (0x8421084, 0x8421084, 32),
41    (1, 0, 5),
42    (0x7C1F07C, 0x7C1F07C, 32),
43    (0x7878787, 0x7878787, 32),
44    (0x7507507, 0x7507507, 32),
45    (0x71C71C7, 0x71C71C7, 32),
46    (0x6EB3E45, 0x6EB3E45, 32),
47    (0x6BCA1AF, 0x6BCA1AF, 32),
48    (0x6906906, 0x6906906, 32),
49    (0x6666666, 0x6666666, 32),
50    (0x63E7063, 0x63E7063, 32),
51    (0x6186186, 0x6186186, 32),
52    (0x5F417D0, 0x5F417D0, 32),
53    (0x5D1745D, 0x5D1745D, 32),
54    (0x5B05B05, 0x5B05B05, 32),
55    (0x590B216, 0x590B216, 32),
56    (0x572620A, 0x572620A, 32),
57    (0x5555555, 0x5555555, 32),
58    (0x5397829, 0x5397829, 32),
59    (0x51EB851, 0x51EB851, 32),
60    (0x5050505, 0x5050505, 32),
61    (0x4EC4EC4, 0x4EC4EC4, 32),
62    (0x4D4873E, 0x4D4873E, 32),
63    (0x4BDA12F, 0x4BDA12F, 32),
64    (0x4A7904A, 0x4A7904A, 32),
65    (0x4924924, 0x4924924, 32),
66    (0x47DC11F, 0x47DC11F, 32),
67    (0x469EE58, 0x469EE58, 32),
68    (0x456C797, 0x456C797, 32),
69    (0x4444444, 0x4444444, 32),
70    (0x4325C53, 0x4325C53, 32),
71    (0x4210842, 0x4210842, 32),
72    (0x4104104, 0x4104104, 32),
73    (1, 0, 6),
74];
75
76/// A compact list of integers with the given number of bits per entry.
77#[derive(Clone, Debug, Default, PartialEq)]
78pub struct BitStorage {
79    pub data: Box<[u64]>,
80    bits: usize,
81    mask: u64,
82    size: usize,
83    values_per_long: usize,
84    divide_mul: i32,
85    divide_add: i32,
86    divide_shift: u32,
87}
88
89#[derive(Debug)]
90pub enum BitStorageError {
91    InvalidLength { got: usize, expected: usize },
92}
93impl Display for BitStorageError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        match self {
96            BitStorageError::InvalidLength { got, expected } => write!(
97                f,
98                "Invalid length given for storage, got: {got}, but expected: {expected}",
99            ),
100        }
101    }
102}
103impl Error for BitStorageError {}
104
105impl BitStorage {
106    /// Create a new BitStorage with the given number of bits per entry. `size`
107    /// is the number of entries in the BitStorage.
108    pub fn new(
109        bits: usize,
110        size: usize,
111        data: Option<Box<[u64]>>,
112    ) -> Result<Self, BitStorageError> {
113        if let Some(data) = &data {
114            // 0 bit storage
115            if data.is_empty() {
116                return Ok(BitStorage {
117                    data: Box::new([]),
118                    bits,
119                    size,
120                    ..Default::default()
121                });
122            }
123        }
124
125        debug_assert!((1..=32).contains(&bits));
126
127        let values_per_long = 64 / bits;
128        let magic_index = values_per_long - 1;
129        let (divide_mul, divide_add, divide_shift) = MAGIC[magic_index];
130        let calculated_length = size.div_ceil(values_per_long);
131
132        let mask = (1 << bits) - 1;
133
134        let using_data = if let Some(data) = data {
135            if data.len() != calculated_length {
136                return Err(BitStorageError::InvalidLength {
137                    got: data.len(),
138                    expected: calculated_length,
139                });
140            }
141            data
142        } else {
143            vec![0; calculated_length].into()
144        };
145
146        Ok(BitStorage {
147            data: using_data,
148            bits,
149            mask,
150            size,
151            values_per_long,
152            divide_mul,
153            divide_add,
154            divide_shift,
155        })
156    }
157
158    #[inline]
159    fn cell_index(&self, index: u64) -> usize {
160        let mul = self.divide_mul as u32 as u64;
161        let add = self.divide_add as u32 as u64;
162        let shift = self.divide_shift;
163
164        (((index * mul) + add) >> shift) as usize
165    }
166
167    /// Get the data at the given index.
168    ///
169    /// # Panics
170    ///
171    /// This function will panic if the given index is greater than or equal to
172    /// the size of this storage.
173    #[inline]
174    pub fn get(&self, index: usize) -> u64 {
175        assert!(
176            index < self.size,
177            "Index {index} out of bounds (must be less than {})",
178            self.size
179        );
180
181        // 0 bit storage
182        if self.data.is_empty() {
183            return 0;
184        }
185
186        let cell_index = self.cell_index(index as u64);
187        let cell = &self.data[cell_index];
188        let bit_index = (index - cell_index * self.values_per_long) * self.bits;
189        (cell >> bit_index) & self.mask
190    }
191
192    pub fn get_and_set(&mut self, index: usize, value: u64) -> u64 {
193        // 0 bit storage
194        if self.data.is_empty() {
195            return 0;
196        }
197
198        debug_assert!(index < self.size);
199        debug_assert!(value <= self.mask);
200        let cell_index = self.cell_index(index as u64);
201        let cell = &mut self.data[cell_index];
202        let bit_index = (index - cell_index * self.values_per_long) * self.bits;
203        let old_value = (*cell >> (bit_index as u64)) & self.mask;
204        *cell = (*cell & !(self.mask << bit_index)) | ((value & self.mask) << bit_index);
205        old_value
206    }
207
208    pub fn set(&mut self, index: usize, value: u64) {
209        // 0 bit storage
210        if self.data.is_empty() {
211            return;
212        }
213
214        debug_assert!(index < self.size);
215        debug_assert!(
216            value <= self.mask,
217            "value {value} at {index} was outside of the mask for {self:?}"
218        );
219        let cell_index = self.cell_index(index as u64);
220        let cell = &mut self.data[cell_index];
221        let bit_index = (index - cell_index * self.values_per_long) * self.bits;
222        *cell = (*cell & !(self.mask << bit_index)) | ((value & self.mask) << bit_index);
223    }
224
225    /// The number of entries.
226    #[inline]
227    pub fn size(&self) -> usize {
228        self.size
229    }
230
231    pub fn iter(&self) -> BitStorageIter<'_> {
232        BitStorageIter {
233            storage: self,
234            index: 0,
235        }
236    }
237}
238
239pub struct BitStorageIter<'a> {
240    storage: &'a BitStorage,
241    index: usize,
242}
243
244impl Iterator for BitStorageIter<'_> {
245    type Item = u64;
246
247    fn next(&mut self) -> Option<Self::Item> {
248        if self.index >= self.storage.size {
249            return None;
250        }
251
252        let value = self.storage.get(self.index);
253        self.index += 1;
254        Some(value)
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn test_protocol_wiki_example() {
264        // https://minecraft.wiki/w/Java_Edition_protocol/Chunk_format#Visual_example
265
266        let data = [
267            1, 2, 2, 3, 4, 4, 5, 6, 6, 4, 8, 0, 7, 4, 3, 13, 15, 16, 9, 14, 10, 12, 0, 2,
268        ];
269        let compact_data: [u64; 2] = [0x0020863148418841, 0x01018A7260F68C87];
270        let storage = BitStorage::new(5, data.len(), Some(Box::new(compact_data))).unwrap();
271
272        for (i, expected) in data.iter().enumerate() {
273            assert_eq!(storage.get(i), *expected);
274        }
275    }
276}