shape-value 0.1.4

NaN-boxed value representation and heap types for Shape
Documentation
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! TypedBuffer<T>: width-specific buffer with optional null/validity bitmap.
//!
//! Used by typed array HeapValue variants (IntArray, FloatArray, BoolArray,
//! I8Array, I16Array, etc.) to provide a uniform nullable container.
//!
//! The validity bitmap is bit-packed: one bit per element, packed into u64 words.
//! A `1` bit means the element is valid; `0` means null. When `validity` is `None`,
//! all elements are considered valid (no nulls).

use std::fmt;

/// Width-specific buffer with optional null bitmap.
#[derive(Clone)]
pub struct TypedBuffer<T> {
    pub data: Vec<T>,
    /// Bit-packed validity bitmap (1 = valid, 0 = null). `None` means all valid.
    pub validity: Option<Vec<u64>>,
}

impl<T: fmt::Debug> fmt::Debug for TypedBuffer<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TypedBuffer")
            .field("len", &self.data.len())
            .field("has_validity", &self.validity.is_some())
            .finish()
    }
}

impl<T> TypedBuffer<T> {
    /// Create an empty TypedBuffer with no validity bitmap.
    #[inline]
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            validity: None,
        }
    }

    /// Create a TypedBuffer with the given capacity and no validity bitmap.
    #[inline]
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            data: Vec::with_capacity(cap),
            validity: None,
        }
    }

    /// Create a TypedBuffer from an existing Vec, treating all elements as valid.
    #[inline]
    pub fn from_vec(data: Vec<T>) -> Self {
        Self {
            data,
            validity: None,
        }
    }

    /// Number of elements (including nulls).
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Whether the buffer is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.len() == 0
    }

    /// Check if the element at `idx` is valid (not null).
    /// Returns `true` if no validity bitmap exists (all valid).
    #[inline]
    pub fn is_valid(&self, idx: usize) -> bool {
        match &self.validity {
            None => true,
            Some(bitmap) => {
                let word = idx / 64;
                let bit = idx % 64;
                word < bitmap.len() && (bitmap[word] & (1u64 << bit)) != 0
            }
        }
    }

    /// Get a reference to the element at `idx`, or `None` if null or out of bounds.
    #[inline]
    pub fn get(&self, idx: usize) -> Option<&T> {
        if idx >= self.data.len() || !self.is_valid(idx) {
            return None;
        }
        Some(&self.data[idx])
    }

    /// Return a slice over the raw data (ignoring validity).
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Return a mutable slice over the raw data (ignoring validity).
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.data
    }

    /// Return an iterator over the raw data (ignoring validity).
    #[inline]
    pub fn iter(&self) -> std::slice::Iter<'_, T> {
        self.data.iter()
    }

    /// Return the number of null elements.
    pub fn null_count(&self) -> usize {
        match &self.validity {
            None => 0,
            Some(bitmap) => {
                let total_bits = self.data.len();
                let set_bits: usize = bitmap.iter().map(|w| w.count_ones() as usize).sum();
                // Only count bits up to len
                let full_words = total_bits / 64;
                let remainder = total_bits % 64;
                let valid_count = if remainder == 0 {
                    set_bits
                } else {
                    let last_word = bitmap.get(full_words).copied().unwrap_or(0);
                    let mask = (1u64 << remainder) - 1;
                    let full_valid: usize = bitmap[..full_words]
                        .iter()
                        .map(|w| w.count_ones() as usize)
                        .sum();
                    full_valid + (last_word & mask).count_ones() as usize
                };
                total_bits - valid_count
            }
        }
    }
}

impl<T> std::ops::Deref for TypedBuffer<T> {
    type Target = [T];
    #[inline]
    fn deref(&self) -> &[T] {
        &self.data
    }
}

impl<T> std::ops::DerefMut for TypedBuffer<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut [T] {
        &mut self.data
    }
}

impl<T: Default> TypedBuffer<T> {
    /// Push a valid element.
    #[inline]
    pub fn push(&mut self, val: T) {
        let idx = self.data.len();
        self.data.push(val);
        if let Some(ref mut bitmap) = self.validity {
            ensure_bitmap_capacity(bitmap, idx);
            let word = idx / 64;
            let bit = idx % 64;
            bitmap[word] |= 1u64 << bit;
        }
    }

    /// Push a null element (default value in data, validity bit = 0).
    pub fn push_null(&mut self) {
        let idx = self.data.len();
        self.data.push(T::default());
        let bitmap = self.validity.get_or_insert_with(|| {
            // Retroactively create bitmap with all previous elements marked valid
            let words_needed = (idx + 64) / 64;
            let mut bm = vec![!0u64; words_needed];
            // Mask off bits beyond current length for the last word
            if idx % 64 != 0 {
                let last_word = (idx - 1) / 64;
                bm[last_word] = (1u64 << (idx % 64)) - 1;
            }
            bm
        });
        ensure_bitmap_capacity(bitmap, idx);
        // Bit is already 0 from the vec allocation (or was masked)
        let word = idx / 64;
        let bit = idx % 64;
        bitmap[word] &= !(1u64 << bit);
    }
}

impl<T> From<Vec<T>> for TypedBuffer<T> {
    #[inline]
    fn from(data: Vec<T>) -> Self {
        Self::from_vec(data)
    }
}

impl<T: PartialEq> PartialEq for TypedBuffer<T> {
    fn eq(&self, other: &Self) -> bool {
        if self.data.len() != other.data.len() {
            return false;
        }
        // Compare element-by-element, respecting validity
        for i in 0..self.data.len() {
            let a_valid = self.is_valid(i);
            let b_valid = other.is_valid(i);
            if a_valid != b_valid {
                return false;
            }
            if a_valid && self.data[i] != other.data[i] {
                return false;
            }
        }
        true
    }
}

/// Ensure the bitmap has enough words to cover bit `idx`.
#[inline]
fn ensure_bitmap_capacity(bitmap: &mut Vec<u64>, idx: usize) {
    let words_needed = idx / 64 + 1;
    if bitmap.len() < words_needed {
        bitmap.resize(words_needed, 0);
    }
}

// ===== Specialization for AlignedVec<f64> =====

use crate::aligned_vec::AlignedVec;

/// Float-specific typed buffer that uses AlignedVec<f64> for SIMD compatibility.
#[derive(Debug, Clone)]
pub struct AlignedTypedBuffer {
    pub data: AlignedVec<f64>,
    /// Bit-packed validity bitmap (1 = valid, 0 = null). `None` means all valid.
    pub validity: Option<Vec<u64>>,
}

impl AlignedTypedBuffer {
    #[inline]
    pub fn new() -> Self {
        Self {
            data: AlignedVec::new(),
            validity: None,
        }
    }

    #[inline]
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            data: AlignedVec::with_capacity(cap),
            validity: None,
        }
    }

    #[inline]
    pub fn from_aligned(data: AlignedVec<f64>) -> Self {
        Self {
            data,
            validity: None,
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    #[inline]
    pub fn is_valid(&self, idx: usize) -> bool {
        match &self.validity {
            None => true,
            Some(bitmap) => {
                let word = idx / 64;
                let bit = idx % 64;
                word < bitmap.len() && (bitmap[word] & (1u64 << bit)) != 0
            }
        }
    }

    #[inline]
    pub fn get(&self, idx: usize) -> Option<&f64> {
        if idx >= self.data.len() || !self.is_valid(idx) {
            return None;
        }
        self.data.get(idx)
    }

    #[inline]
    pub fn as_slice(&self) -> &[f64] {
        self.data.as_slice()
    }

    #[inline]
    pub fn iter(&self) -> std::slice::Iter<'_, f64> {
        self.data.as_slice().iter()
    }

    pub fn push(&mut self, val: f64) {
        let idx = self.data.len();
        self.data.push(val);
        if let Some(ref mut bitmap) = self.validity {
            ensure_bitmap_capacity(bitmap, idx);
            let word = idx / 64;
            let bit = idx % 64;
            bitmap[word] |= 1u64 << bit;
        }
    }

    pub fn pop(&mut self) -> Option<f64> {
        self.data.pop()
    }

    pub fn push_null(&mut self) {
        let idx = self.data.len();
        self.data.push(0.0);
        let bitmap = self.validity.get_or_insert_with(|| {
            let words_needed = (idx + 64) / 64;
            let mut bm = vec![!0u64; words_needed];
            if idx % 64 != 0 {
                let last_word = (idx - 1) / 64;
                bm[last_word] = (1u64 << (idx % 64)) - 1;
            }
            bm
        });
        ensure_bitmap_capacity(bitmap, idx);
        let word = idx / 64;
        let bit = idx % 64;
        bitmap[word] &= !(1u64 << bit);
    }
}

impl From<AlignedVec<f64>> for AlignedTypedBuffer {
    #[inline]
    fn from(data: AlignedVec<f64>) -> Self {
        Self::from_aligned(data)
    }
}

impl std::ops::Deref for AlignedTypedBuffer {
    type Target = [f64];
    #[inline]
    fn deref(&self) -> &[f64] {
        self.data.as_slice()
    }
}

impl std::ops::DerefMut for AlignedTypedBuffer {
    #[inline]
    fn deref_mut(&mut self) -> &mut [f64] {
        self.data.as_mut_slice()
    }
}

impl PartialEq for AlignedTypedBuffer {
    fn eq(&self, other: &Self) -> bool {
        if self.data.len() != other.data.len() {
            return false;
        }
        for i in 0..self.data.len() {
            let a_valid = self.is_valid(i);
            let b_valid = other.is_valid(i);
            if a_valid != b_valid {
                return false;
            }
            if a_valid && self.data.as_slice()[i] != other.data.as_slice()[i] {
                return false;
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_typed_buffer_basic() {
        let mut buf = TypedBuffer::<i64>::new();
        buf.push(10);
        buf.push(20);
        buf.push(30);
        assert_eq!(buf.len(), 3);
        assert_eq!(buf.get(0), Some(&10));
        assert_eq!(buf.get(1), Some(&20));
        assert_eq!(buf.get(2), Some(&30));
        assert_eq!(buf.get(3), None);
        assert!(buf.is_valid(0));
        assert!(buf.is_valid(1));
        assert!(buf.is_valid(2));
        assert_eq!(buf.null_count(), 0);
    }

    #[test]
    fn test_typed_buffer_with_nulls() {
        let mut buf = TypedBuffer::<i64>::new();
        buf.push(10);
        buf.push_null();
        buf.push(30);
        assert_eq!(buf.len(), 3);
        assert!(buf.is_valid(0));
        assert!(!buf.is_valid(1));
        assert!(buf.is_valid(2));
        assert_eq!(buf.get(0), Some(&10));
        assert_eq!(buf.get(1), None); // null
        assert_eq!(buf.get(2), Some(&30));
        assert_eq!(buf.null_count(), 1);
    }

    #[test]
    fn test_typed_buffer_from_vec() {
        let buf = TypedBuffer::from_vec(vec![1i32, 2, 3, 4]);
        assert_eq!(buf.len(), 4);
        assert!(buf.is_valid(0));
        assert_eq!(buf.get(2), Some(&3));
        assert_eq!(buf.null_count(), 0);
    }

    #[test]
    fn test_typed_buffer_equality() {
        let a = TypedBuffer::from_vec(vec![1i64, 2, 3]);
        let b = TypedBuffer::from_vec(vec![1i64, 2, 3]);
        let c = TypedBuffer::from_vec(vec![1i64, 2, 4]);
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_typed_buffer_equality_with_nulls() {
        let mut a = TypedBuffer::<i64>::new();
        a.push(1);
        a.push_null();
        let mut b = TypedBuffer::<i64>::new();
        b.push(1);
        b.push_null();
        assert_eq!(a, b);
    }

    #[test]
    fn test_aligned_typed_buffer_basic() {
        let mut buf = AlignedTypedBuffer::new();
        buf.push(1.0);
        buf.push(2.0);
        buf.push(3.0);
        assert_eq!(buf.len(), 3);
        assert_eq!(buf.get(0), Some(&1.0));
        assert_eq!(buf.get(1), Some(&2.0));
        assert!(buf.is_valid(0));
        assert_eq!(buf.as_slice(), &[1.0, 2.0, 3.0]);
    }

    #[test]
    fn test_aligned_typed_buffer_with_nulls() {
        let mut buf = AlignedTypedBuffer::new();
        buf.push(1.0);
        buf.push_null();
        buf.push(3.0);
        assert!(buf.is_valid(0));
        assert!(!buf.is_valid(1));
        assert!(buf.is_valid(2));
        assert_eq!(buf.get(1), None);
    }

    #[test]
    fn test_many_elements_bitmap() {
        let mut buf = TypedBuffer::<i32>::new();
        for i in 0..200 {
            if i % 10 == 0 {
                buf.push_null();
            } else {
                buf.push(i);
            }
        }
        assert_eq!(buf.len(), 200);
        assert_eq!(buf.null_count(), 20);
        assert!(!buf.is_valid(0));
        assert!(buf.is_valid(1));
        assert!(!buf.is_valid(10));
        assert!(buf.is_valid(11));
    }
}