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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use super::{Bitmap, BitmapView};
use crate::serialization::{Frozen, Native, Portable};

use std::ffi::{c_char, c_void};

/// Trait for different formats of bitmap serialization
pub trait Serializer {
    /// Serialize a bitmap into bytes, using the provided vec buffer to store the serialized data
    ///
    /// Note that some serializers ([Frozen]) may require that the bitmap is aligned specially,
    /// this method will ensure that the returned slice of bytes is aligned correctly, by adding
    /// additional padding before the serialized data if required.
    ///
    /// The contents of the provided vec buffer will not be overwritten: only new data will be
    /// appended to the end of the buffer. If the buffer has enough capacity, and the current
    /// end of the buffer is correctly aligned, then no additional allocations will be performed.
    fn serialize_into<'a>(bitmap: &Bitmap, dst: &'a mut Vec<u8>) -> &'a [u8];
    /// Get the number of bytes required to serialize this bitmap
    ///
    /// This does not include any additional padding which may be required to align the bitmap
    fn get_serialized_size_in_bytes(bitmap: &Bitmap) -> usize;
}

/// Trait for different formats of bitmap deserialization
pub trait Deserializer {
    /// Try to deserialize a bitmap from the beginning of the provided buffer
    ///
    /// The [`Bitmap::try_deserialize`] method should usually be used instead of this method
    /// directly.
    ///
    /// If the buffer starts with the serialized representation of a bitmap, then
    /// this method will return a new bitmap containing the deserialized data.
    ///
    /// If the buffer does not start with a serialized bitmap (or contains an invalidly
    /// truncated bitmap), then this method will return `None`.
    ///
    /// To determine how many bytes were consumed from the buffer, use the
    /// [`Serializer::get_serialized_size_in_bytes`] method on the returned bitmap.
    fn try_deserialize(buffer: &[u8]) -> Option<Bitmap>;

    /// Deserialize a bitmap from the beginning of the provided buffer
    ///
    /// # Safety
    ///
    /// Unlike its safe counterpart ([`Self::try_deserialize`]) this function assumes the data is
    /// valid, passing data which does not contain/start with a bitmap serialized with this format
    /// will result in undefined behavior.
    unsafe fn try_deserialize_unchecked(buffer: &[u8]) -> Bitmap;
}

/// Trait for different formats of bitmap deserialization into a view without copying
pub trait ViewDeserializer {
    /// Create a bitmap view using the passed data
    ///
    /// # Safety
    /// * `data` must be the result of serializing a roaring bitmap in this format.
    /// * Its beginning must be aligned properly for this format.
    /// * data.len() must be equal exactly to the size of the serialized bitmap.
    ///
    /// See [`BitmapView::deserialize`] for examples.
    unsafe fn deserialize_view(data: &[u8]) -> BitmapView<'_>;
}

impl Serializer for Portable {
    /// Serializes a bitmap to a slice of bytes in portable format.
    /// See [`Bitmap::serialize_into`] for examples.
    #[doc(alias = "roaring_bitmap_portable_serialize")]
    fn serialize_into<'a>(bitmap: &Bitmap, dst: &'a mut Vec<u8>) -> &'a [u8] {
        let len = Self::get_serialized_size_in_bytes(bitmap);

        dst.reserve(len);
        let offset = dst.len();
        let total_len = offset.checked_add(len).unwrap();

        unsafe {
            ffi::roaring_bitmap_portable_serialize(
                &bitmap.bitmap,
                dst.spare_capacity_mut().as_mut_ptr().cast::<c_char>(),
            );
            dst.set_len(total_len);
        }

        &dst[offset..]
    }

    /// Computes the serialized size in bytes of the Bitmap in portable format.
    /// See [`Bitmap::get_serialized_size_in_bytes`] for examples.
    #[doc(alias = "roaring_bitmap_portable_size_in_bytes")]
    fn get_serialized_size_in_bytes(bitmap: &Bitmap) -> usize {
        unsafe { ffi::roaring_bitmap_portable_size_in_bytes(&bitmap.bitmap) }
    }
}

impl Deserializer for Portable {
    /// Given a serialized bitmap as slice of bytes in portable format, returns a `Bitmap` instance.
    /// See [`Bitmap::try_deserialize`] for examples.
    #[doc(alias = "roaring_bitmap_portable_deserialize_safe")]
    fn try_deserialize(buffer: &[u8]) -> Option<Bitmap> {
        unsafe {
            let bitmap = ffi::roaring_bitmap_portable_deserialize_safe(
                buffer.as_ptr().cast::<c_char>(),
                buffer.len(),
            );

            if bitmap.is_null() {
                return None;
            }

            let bitmap = Bitmap::take_heap(bitmap);
            if bitmap.internal_validate().is_ok() {
                Some(bitmap)
            } else {
                None
            }
        }
    }

    #[doc(alias = "roaring_bitmap_portable_deserialize")]
    unsafe fn try_deserialize_unchecked(buffer: &[u8]) -> Bitmap {
        let bitmap = ffi::roaring_bitmap_portable_deserialize(buffer.as_ptr().cast::<c_char>());
        Bitmap::take_heap(bitmap)
    }
}

impl ViewDeserializer for Portable {
    /// Read bitmap from a serialized buffer
    ///
    /// This is meant to be compatible with the Java and Go versions
    ///
    /// # Safety
    /// * `data` must be the result of serializing a roaring bitmap in portable mode
    ///   (following `https://github.com/RoaringBitmap/RoaringFormatSpec`), for example, with
    ///   [`Bitmap::serialize`]
    /// * Using this function (or the returned bitmap in any way) may execute unaligned memory accesses
    ///
    #[doc(alias = "roaring_bitmap_portable_deserialize_frozen")]
    unsafe fn deserialize_view(data: &[u8]) -> BitmapView<'_> {
        // portable_deserialize_size does some amount of checks, and returns zero if data cannot be valid
        debug_assert_ne!(
            ffi::roaring_bitmap_portable_deserialize_size(data.as_ptr().cast(), data.len()),
            0,
        );
        let roaring = ffi::roaring_bitmap_portable_deserialize_frozen(data.as_ptr().cast());
        BitmapView::take_heap(roaring)
    }
}

impl Serializer for Native {
    /// Serializes a bitmap to a slice of bytes in native format.
    /// See [`Bitmap::serialize_into`] for examples.
    #[doc(alias = "roaring_bitmap_serialize")]
    fn serialize_into<'a>(bitmap: &Bitmap, dst: &'a mut Vec<u8>) -> &'a [u8] {
        let len = Self::get_serialized_size_in_bytes(bitmap);

        dst.reserve(len);
        let offset = dst.len();
        let total_len = offset.checked_add(len).unwrap();

        unsafe {
            ffi::roaring_bitmap_serialize(
                &bitmap.bitmap,
                dst.spare_capacity_mut().as_mut_ptr().cast::<c_char>(),
            );
            dst.set_len(total_len);
        }

        &dst[offset..]
    }

    /// Computes the serialized size in bytes of the Bitmap in native format.
    /// See [`Bitmap::get_serialized_size_in_bytes`] for examples.
    #[doc(alias = "roaring_bitmap_size_in_bytes")]
    fn get_serialized_size_in_bytes(bitmap: &Bitmap) -> usize {
        unsafe { ffi::roaring_bitmap_size_in_bytes(&bitmap.bitmap) }
    }
}

impl Deserializer for Native {
    /// Given a serialized bitmap as slice of bytes in native format, returns a `Bitmap` instance.
    /// See [`Bitmap::try_deserialize`] for examples.
    #[doc(alias = "roaring_bitmap_deserialize_safe")]
    fn try_deserialize(buffer: &[u8]) -> Option<Bitmap> {
        unsafe {
            let bitmap = ffi::roaring_bitmap_deserialize_safe(
                buffer.as_ptr().cast::<c_void>(),
                buffer.len(),
            );

            if bitmap.is_null() {
                return None;
            }
            let bitmap = Bitmap::take_heap(bitmap);
            if bitmap.internal_validate().is_ok() {
                Some(bitmap)
            } else {
                None
            }
        }
    }

    #[doc(alias = "roaring_bitmap_deserialize")]
    unsafe fn try_deserialize_unchecked(buffer: &[u8]) -> Bitmap {
        let bitmap = ffi::roaring_bitmap_deserialize(buffer.as_ptr().cast::<c_void>());
        Bitmap::take_heap(bitmap)
    }
}

impl Serializer for Frozen {
    /// Serializes a bitmap to a slice of bytes in "frozen" format.
    ///
    /// This has an odd API because it always returns a slice which is aligned to 32 bytes:
    /// This means the returned slice may not start exactly at the beginning of the passed `Vec`
    /// See [`Bitmap::serialize_into`] for examples.
    #[doc(alias = "roaring_bitmap_frozen_serialize")]
    fn serialize_into<'a>(bitmap: &Bitmap, dst: &'a mut Vec<u8>) -> &'a [u8] {
        let len = Self::get_serialized_size_in_bytes(bitmap);

        let mut offset = dst.len();
        if dst.capacity() < dst.len() + len
            || Self::required_padding(dst.as_ptr_range().end as usize) != 0
        {
            dst.reserve(len.checked_add(Self::MAX_PADDING).unwrap());
            let extra_offset = Self::required_padding(dst.as_ptr_range().end as usize);
            offset = offset.checked_add(extra_offset).unwrap();
            // we must initialize up to offset
            dst.resize(offset, 0);
        }
        let total_len = offset.checked_add(len).unwrap();
        debug_assert!(dst.capacity() >= total_len);

        unsafe {
            ffi::roaring_bitmap_frozen_serialize(
                &bitmap.bitmap,
                dst.as_mut_ptr().add(offset).cast::<c_char>(),
            );
            dst.set_len(total_len);
        }

        &dst[offset..total_len]
    }

    /// Computes the serialized size in bytes of the Bitmap in frozen format.
    /// See [`Bitmap::get_serialized_size_in_bytes`] for examples.
    #[doc(alias = "roaring_bitmap_frozen_size_in_bytes")]
    fn get_serialized_size_in_bytes(bitmap: &Bitmap) -> usize {
        unsafe { ffi::roaring_bitmap_frozen_size_in_bytes(&bitmap.bitmap) }
    }
}

impl ViewDeserializer for Frozen {
    /// Create a frozen bitmap view using the passed data
    ///
    /// # Safety
    /// * `data` must be the result of serializing a roaring bitmap in frozen mode
    ///   (in c with `roaring_bitmap_frozen_serialize`, or via [`Bitmap::serialize_into::<Frozen>`]).
    /// * Its beginning must be aligned by 32 bytes.
    /// * data.len() must be equal exactly to the size of the frozen bitmap.
    ///
    /// See [`BitmapView::deserialize`] for examples.
    unsafe fn deserialize_view(data: &[u8]) -> BitmapView<'_> {
        assert_eq!(data.as_ptr() as usize % Self::REQUIRED_ALIGNMENT, 0);

        let roaring = ffi::roaring_bitmap_frozen_view(data.as_ptr().cast(), data.len());
        BitmapView::take_heap(roaring)
    }
}