akar-common 0.1.2

Shared types and utilities for the Akar embedded graph database
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! LegacyValueVector — typed columnar data array used throughout the query engine.

use crate::types::{PhysicalTypeID, Value};

/// A vector of values of the same physical type.
/// This is the fundamental columnar data unit in Akar's query execution.
#[derive(Debug, Clone)]
pub struct LegacyValueVector {
    physical_type: PhysicalTypeID,
    /// The actual data buffer (type-erased byte buffer).
    data: Vec<u8>,
    /// Nullability mask (true = not null).
    null_mask: Vec<bool>,
    /// Number of elements currently in the vector.
    size: usize,
    /// Capacity of the vector (number of elements, not bytes).
    capacity: usize,
}

impl LegacyValueVector {
    pub fn new(physical_type: PhysicalTypeID, capacity: usize) -> Self {
        let type_size = physical_type_size(physical_type);
        Self {
            physical_type,
            data: vec![0u8; capacity * type_size],
            null_mask: vec![true; capacity],
            size: 0,
            capacity,
        }
    }

    #[inline(always)]
    pub fn physical_type(&self) -> PhysicalTypeID {
        self.physical_type
    }

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

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

    #[inline(always)]
    pub fn is_null(&self, idx: usize) -> bool {
        !self.null_mask[idx]
    }

    #[inline(always)]
    pub fn set_null(&mut self, idx: usize, is_null: bool) {
        self.null_mask[idx] = !is_null;
    }

    #[inline(always)]
    pub fn resize(&mut self, new_size: usize) {
        assert!(new_size <= self.capacity);
        self.size = new_size;
    }

    /// Get a reference to the raw data buffer.
    #[inline(always)]
    pub fn data(&self) -> &[u8] {
        &self.data[..self.size * physical_type_size(self.physical_type)]
    }

    #[inline]
    pub fn data_mut(&mut self) -> &mut [u8] {
        let type_size = physical_type_size(self.physical_type);
        &mut self.data[..self.size * type_size]
    }
}

/// Returns the byte size of a given physical type.
pub const fn physical_type_size(t: PhysicalTypeID) -> usize {
    match t {
        PhysicalTypeID::Bool => 1,
        PhysicalTypeID::Int8 | PhysicalTypeID::UInt8 => 1,
        PhysicalTypeID::Int16 | PhysicalTypeID::UInt16 => 2,
        PhysicalTypeID::Int32 | PhysicalTypeID::UInt32 | PhysicalTypeID::Float => 4,
        PhysicalTypeID::Int64 | PhysicalTypeID::UInt64 | PhysicalTypeID::Double | PhysicalTypeID::Interval => 8,
        PhysicalTypeID::Int128 => 16,
        PhysicalTypeID::String => 256, // inline string up to 255 chars for prototype
        PhysicalTypeID::Struct => 8,   // pointer to struct data
        PhysicalTypeID::List | PhysicalTypeID::Array => 16, // list header
        PhysicalTypeID::Blob => 256,
        PhysicalTypeID::Any => 1,
    }
}

// --- Typed getters/setters ---

impl LegacyValueVector {
    /// Get an i64 value at index.
    #[inline]
    pub fn get_i64(&self, idx: usize) -> Option<i64> {
        if self.is_null(idx) {
            return None;
        }
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        let mut buf = [0u8; 8];
        buf.copy_from_slice(&self.data[offset..offset + 8]);
        Some(i64::from_le_bytes(buf))
    }

    /// Set an i64 value at index.
    #[inline]
    pub fn set_i64(&mut self, idx: usize, val: i64) {
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        self.data[offset..offset + 8].copy_from_slice(&val.to_le_bytes());
        self.null_mask[idx] = true;
        if idx >= self.size {
            self.size = idx + 1;
        }
    }

    /// Get an i32 value at index.
    #[inline]
    pub fn get_i32(&self, idx: usize) -> Option<i32> {
        if self.is_null(idx) {
            return None;
        }
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        let mut buf = [0u8; 4];
        buf.copy_from_slice(&self.data[offset..offset + 4]);
        Some(i32::from_le_bytes(buf))
    }

    /// Set an i32 value at index.
    #[inline]
    pub fn set_i32(&mut self, idx: usize, val: i32) {
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        self.data[offset..offset + 4].copy_from_slice(&val.to_le_bytes());
        self.null_mask[idx] = true;
        if idx >= self.size {
            self.size = idx + 1;
        }
    }

    /// Get an f64 (double) value at index.
    #[inline]
    pub fn get_double(&self, idx: usize) -> Option<f64> {
        if self.is_null(idx) {
            return None;
        }
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        let mut buf = [0u8; 8];
        buf.copy_from_slice(&self.data[offset..offset + 8]);
        Some(f64::from_le_bytes(buf))
    }

    /// Set an f64 (double) value at index.
    #[inline]
    pub fn set_double(&mut self, idx: usize, val: f64) {
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        self.data[offset..offset + 8].copy_from_slice(&val.to_le_bytes());
        self.null_mask[idx] = true;
        if idx >= self.size {
            self.size = idx + 1;
        }
    }
}

impl LegacyValueVector {
    /// Get a Value enum from this vector at a given row index.
    /// This converts the raw byte buffer into the appropriate Value variant.
    pub fn get_value(&self, idx: usize) -> Option<Value> {
        if idx >= self.size || self.is_null(idx) {
            return None;
        }
        let type_size = physical_type_size(self.physical_type);
        let offset = idx * type_size;
        match self.physical_type {
            PhysicalTypeID::Bool => Some(Value::Bool(self.data[offset] != 0)),
            PhysicalTypeID::Int64 => {
                let mut buf = [0u8; 8];
                buf.copy_from_slice(&self.data[offset..offset + 8]);
                Some(Value::Int64(i64::from_le_bytes(buf)))
            }
            PhysicalTypeID::Int32 => {
                let mut buf = [0u8; 4];
                buf.copy_from_slice(&self.data[offset..offset + 4]);
                Some(Value::Int32(i32::from_le_bytes(buf)))
            }
            PhysicalTypeID::Int16 => {
                let mut buf = [0u8; 2];
                buf.copy_from_slice(&self.data[offset..offset + 2]);
                Some(Value::Int16(i16::from_le_bytes(buf)))
            }
            PhysicalTypeID::Int8 => Some(Value::Int8(self.data[offset] as i8)),
            PhysicalTypeID::UInt64 => {
                let mut buf = [0u8; 8];
                buf.copy_from_slice(&self.data[offset..offset + 8]);
                Some(Value::UInt64(u64::from_le_bytes(buf)))
            }
            PhysicalTypeID::UInt32 => {
                let mut buf = [0u8; 4];
                buf.copy_from_slice(&self.data[offset..offset + 4]);
                Some(Value::UInt32(u32::from_le_bytes(buf)))
            }
            PhysicalTypeID::UInt16 => {
                let mut buf = [0u8; 2];
                buf.copy_from_slice(&self.data[offset..offset + 2]);
                Some(Value::UInt16(u16::from_le_bytes(buf)))
            }
            PhysicalTypeID::UInt8 => Some(Value::UInt8(self.data[offset])),
            PhysicalTypeID::Double => {
                let mut buf = [0u8; 8];
                buf.copy_from_slice(&self.data[offset..offset + 8]);
                Some(Value::Double(f64::from_le_bytes(buf)))
            }
            PhysicalTypeID::Float => {
                let mut buf = [0u8; 4];
                buf.copy_from_slice(&self.data[offset..offset + 4]);
                Some(Value::Float(f32::from_le_bytes(buf)))
            }
            PhysicalTypeID::String => {
                let len = self.data[offset] as usize;
                let s = String::from_utf8_lossy(&self.data[offset + 1..offset + 1 + len.min(255)]).to_string();
                Some(Value::String(s))
            }
            // For struct/list types, return a simplified representation
            PhysicalTypeID::Struct => Some(Value::Struct(Vec::new())),
            PhysicalTypeID::List => Some(Value::List(Vec::new())),
            _ => None,
        }
    }

    /// Set a `Value` at the given row index.
    ///
    /// Converts the `Value` variant to the vector's physical type.
    /// Returns an error if the type cannot be converted.
    pub fn set_value(&mut self, idx: usize, val: &Value) -> Result<(), String> {
        match (self.physical_type, val) {
            (_, Value::Null) => {
                self.set_null(idx, true);
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::Bool, Value::Bool(b)) => {
                let byte: u8 = if *b { 1 } else { 0 };
                self.data[idx] = byte;
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Int64(v)) => {
                self.set_i64(idx, *v);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Int32(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Int16(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Int8(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::UInt64(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::UInt32(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::UInt16(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::UInt8(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Double(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Float(v)) => {
                self.set_i64(idx, *v as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Date(v)) => {
                self.set_i64(idx, v.0 as i64);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::Timestamp(v))
            | (PhysicalTypeID::Int64, Value::TimestampNs(v))
            | (PhysicalTypeID::Int64, Value::TimestampMs(v))
            | (PhysicalTypeID::Int64, Value::TimestampSec(v)) => {
                self.set_i64(idx, v.0);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::TimestampTz(v)) => {
                self.set_i64(idx, v.0);
                Ok(())
            }
            (PhysicalTypeID::Int64, Value::DTime(v)) => {
                self.set_i64(idx, *v);
                Ok(())
            }
            (PhysicalTypeID::Int32, Value::Int32(v)) => {
                self.set_i32(idx, *v);
                Ok(())
            }
            (PhysicalTypeID::Int32, Value::Int16(v)) => {
                self.set_i32(idx, *v as i32);
                Ok(())
            }
            (PhysicalTypeID::Int32, Value::Int8(v)) => {
                self.set_i32(idx, *v as i32);
                Ok(())
            }
            (PhysicalTypeID::Int32, Value::Int64(v)) => {
                self.set_i32(idx, *v as i32);
                Ok(())
            }
            (PhysicalTypeID::Double, Value::Double(v)) => {
                self.set_double(idx, *v);
                Ok(())
            }
            (PhysicalTypeID::Double, Value::Float(v)) => {
                self.set_double(idx, *v as f64);
                Ok(())
            }
            (PhysicalTypeID::Double, Value::Int64(v)) => {
                self.set_double(idx, *v as f64);
                Ok(())
            }
            (PhysicalTypeID::Float, Value::Float(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 4].copy_from_slice(&v.to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::Float, Value::Double(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 4].copy_from_slice(&(*v as f32).to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::String, Value::String(s)) => {
                let bytes = s.as_bytes();
                if bytes.len() > 255 {
                    return Err(format!(
                        "Cannot store string of {} bytes: inline string storage limit is 255 bytes",
                        bytes.len()
                    ));
                }
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset] = bytes.len() as u8;
                self.data[offset + 1..offset + 1 + bytes.len()].copy_from_slice(bytes);
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            // UInt64 — accept UInt64 or Int64 values
            (PhysicalTypeID::UInt64, Value::UInt64(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 8].copy_from_slice(&v.to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::UInt64, Value::Int64(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 8].copy_from_slice(&(*v as u64).to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            // UInt32 — accept UInt32 or Int32 values
            (PhysicalTypeID::UInt32, Value::UInt32(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 4].copy_from_slice(&v.to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::UInt32, Value::Int32(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 4].copy_from_slice(&(*v as u32).to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            // UInt16 — accept UInt16 or Int16 values
            (PhysicalTypeID::UInt16, Value::UInt16(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 2].copy_from_slice(&v.to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::UInt16, Value::Int16(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 2].copy_from_slice(&(*v as u16).to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            // UInt8 — accept UInt8 or Int8 values
            (PhysicalTypeID::UInt8, Value::UInt8(v)) => {
                self.data[idx] = *v;
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            (PhysicalTypeID::UInt8, Value::Int8(v)) => {
                self.data[idx] = *v as u8;
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            // Int16
            (PhysicalTypeID::Int16, Value::Int16(v)) => {
                let type_size = physical_type_size(self.physical_type);
                let offset = idx * type_size;
                self.data[offset..offset + 2].copy_from_slice(&v.to_le_bytes());
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            // Int8
            (PhysicalTypeID::Int8, Value::Int8(v)) => {
                self.data[idx] = *v as u8;
                self.null_mask[idx] = true;
                if idx >= self.size {
                    self.size = idx + 1;
                }
                Ok(())
            }
            _ => Err(format!(
                "Cannot set value {:?} into vector of type {:?}",
                val, self.physical_type
            )),
        }
    }

    /// Push a boolean value to the end of the vector.
    #[inline]
    pub fn push_bool(&mut self, val: bool) {
        let idx = self.size;
        let byte: u8 = if val { 1 } else { 0 };
        self.data[idx] = byte;
        self.null_mask[idx] = true;
        self.size += 1;
    }

    /// Get a boolean value at index.
    #[inline]
    pub fn get_bool(&self, idx: usize) -> Option<bool> {
        if self.is_null(idx) {
            return None;
        }
        Some(self.data[idx] != 0)
    }

    /// Push a string value (stores as inline bytes for now).
    /// Returns an error if the string exceeds the 255-byte inline storage limit.
    #[inline]
    pub fn push_string(&mut self, val: &str) -> Result<(), String> {
        let idx = self.size;
        let bytes = val.as_bytes();
        if bytes.len() > 255 {
            return Err(format!(
                "Cannot store string of {} bytes: inline string storage limit is 255 bytes",
                bytes.len()
            ));
        }
        self.data[idx * 256] = bytes.len() as u8;
        self.data[idx * 256 + 1..idx * 256 + 1 + bytes.len()].copy_from_slice(bytes);
        self.null_mask[idx] = true;
        self.size += 1;
        Ok(())
    }

    /// Append a value from another vector (for DataChunk operations).
    pub fn append(&mut self, other: &LegacyValueVector) {
        let start = self.size;
        let count = other.size;
        let type_size = physical_type_size(self.physical_type);
        let bytes_to_copy = count * type_size;
        if start * type_size + bytes_to_copy > self.data.len() {
            self.data.resize((start + count) * type_size, 0);
            self.null_mask.resize(start + count, true);
            self.capacity = start + count;
        }
        self.data[start * type_size..start * type_size + bytes_to_copy].copy_from_slice(&other.data[..bytes_to_copy]);
        for i in 0..count {
            self.null_mask[start + i] = other.null_mask[i];
        }
        self.size = start + count;
    }
}

/// Type alias for backward compatibility during Arrow migration.
/// Use `ValueVector` in existing code; new code should prefer `Vector` from arrow_vector.
pub type ValueVector = LegacyValueVector;

/// Re-export DataChunk from its own module.
pub use crate::data_chunk::DataChunk;

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

    #[test]
    fn set_value_string_overflow_returns_error() {
        let mut v = LegacyValueVector::new(PhysicalTypeID::String, 1);
        let long = "a".repeat(256);
        let err = v.set_value(0, &Value::String(long)).unwrap_err();
        assert!(err.contains("255"), "err: {err}");
    }

    #[test]
    fn set_value_string_exact_255_round_trips() {
        let mut v = LegacyValueVector::new(PhysicalTypeID::String, 1);
        let s = "a".repeat(255);
        v.set_value(0, &Value::String(s.clone())).unwrap();
        assert_eq!(v.get_value(0), Some(Value::String(s)));
    }

    #[test]
    fn push_string_overflow_returns_error() {
        let mut v = LegacyValueVector::new(PhysicalTypeID::String, 1);
        let err = v.push_string(&"a".repeat(256)).unwrap_err();
        assert!(err.contains("255"), "err: {err}");
        assert_eq!(v.size(), 0);
    }
}