motedb 0.1.6

AI-native embedded multimodal database for embodied intelligence (robots, AR glasses, industrial arms).
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! SIMD 加速的 SQL 算子
//!
//! 提供高性能的聚合、过滤和扫描操作:
//! - x86_64: AVX2/SSE2
//! - aarch64: NEON
//! - fallback: 标量实现

use crate::types::Value;

/// SIMD 加速的 SUM 聚合
pub fn simd_sum_i64(values: &[i64]) -> i64 {
    #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
    {
        unsafe { simd_sum_i64_avx2(values) }
    }
    
    #[cfg(all(
        target_arch = "aarch64",
        target_feature = "neon",
        not(all(target_arch = "x86_64", target_feature = "avx2"))
    ))]
    {
        unsafe { simd_sum_i64_neon(values) }
    }
    
    #[cfg(not(any(
        all(target_arch = "x86_64", target_feature = "avx2"),
        all(target_arch = "aarch64", target_feature = "neon")
    )))]
    {
        simd_sum_i64_fallback(values)
    }
}

/// SIMD 加速的 SUM (f64)
pub fn simd_sum_f64(values: &[f64]) -> f64 {
    #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
    {
        unsafe { simd_sum_f64_avx2(values) }
    }
    
    #[cfg(all(
        target_arch = "aarch64",
        target_feature = "neon",
        not(all(target_arch = "x86_64", target_feature = "avx2"))
    ))]
    {
        unsafe { simd_sum_f64_neon(values) }
    }
    
    #[cfg(not(any(
        all(target_arch = "x86_64", target_feature = "avx2"),
        all(target_arch = "aarch64", target_feature = "neon")
    )))]
    {
        simd_sum_f64_fallback(values)
    }
}

/// SIMD 加速的 MIN (i64)
pub fn simd_min_i64(values: &[i64]) -> Option<i64> {
    if values.is_empty() {
        return None;
    }
    
    #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
    {
        Some(unsafe { simd_min_i64_avx2(values) })
    }
    
    #[cfg(all(
        target_arch = "aarch64",
        target_feature = "neon",
        not(all(target_arch = "x86_64", target_feature = "avx2"))
    ))]
    {
        Some(unsafe { simd_min_i64_neon(values) })
    }
    
    #[cfg(not(any(
        all(target_arch = "x86_64", target_feature = "avx2"),
        all(target_arch = "aarch64", target_feature = "neon")
    )))]
    {
        Some(simd_min_i64_fallback(values))
    }
}

/// SIMD 加速的 MAX (i64)
pub fn simd_max_i64(values: &[i64]) -> Option<i64> {
    if values.is_empty() {
        return None;
    }
    
    #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
    {
        Some(unsafe { simd_max_i64_avx2(values) })
    }
    
    #[cfg(all(
        target_arch = "aarch64",
        target_feature = "neon",
        not(all(target_arch = "x86_64", target_feature = "avx2"))
    ))]
    {
        Some(unsafe { simd_max_i64_neon(values) })
    }
    
    #[cfg(not(any(
        all(target_arch = "x86_64", target_feature = "avx2"),
        all(target_arch = "aarch64", target_feature = "neon")
    )))]
    {
        Some(simd_max_i64_fallback(values))
    }
}

/// SIMD 加速的 WHERE 过滤 (等值比较)
/// 返回满足条件的索引
pub fn simd_filter_eq_i64(values: &[i64], target: i64) -> Vec<usize> {
    #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
    {
        unsafe { simd_filter_eq_i64_avx2(values, target) }
    }
    
    #[cfg(all(
        target_arch = "aarch64",
        target_feature = "neon",
        not(all(target_arch = "x86_64", target_feature = "avx2"))
    ))]
    {
        unsafe { simd_filter_eq_i64_neon(values, target) }
    }
    
    #[cfg(not(any(
        all(target_arch = "x86_64", target_feature = "avx2"),
        all(target_arch = "aarch64", target_feature = "neon")
    )))]
    {
        simd_filter_eq_i64_fallback(values, target)
    }
}

/// SIMD 加速的范围过滤 (min <= value <= max)
pub fn simd_filter_range_i64(values: &[i64], min: i64, max: i64) -> Vec<usize> {
    #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
    {
        unsafe { simd_filter_range_i64_avx2(values, min, max) }
    }
    
    #[cfg(all(
        target_arch = "aarch64",
        target_feature = "neon",
        not(all(target_arch = "x86_64", target_feature = "avx2"))
    ))]
    {
        unsafe { simd_filter_range_i64_neon(values, min, max) }
    }
    
    #[cfg(not(any(
        all(target_arch = "x86_64", target_feature = "avx2"),
        all(target_arch = "aarch64", target_feature = "neon")
    )))]
    {
        simd_filter_range_i64_fallback(values, min, max)
    }
}

//=============================================================================
// Fallback implementations (标量)
//=============================================================================

fn simd_sum_i64_fallback(values: &[i64]) -> i64 {
    values.iter().sum()
}

fn simd_sum_f64_fallback(values: &[f64]) -> f64 {
    values.iter().sum()
}

fn simd_min_i64_fallback(values: &[i64]) -> i64 {
    values.iter().min().copied().unwrap_or(i64::MAX)
}

fn simd_max_i64_fallback(values: &[i64]) -> i64 {
    values.iter().max().copied().unwrap_or(i64::MIN)
}

fn simd_filter_eq_i64_fallback(values: &[i64], target: i64) -> Vec<usize> {
    values.iter()
        .enumerate()
        .filter_map(|(i, &v)| if v == target { Some(i) } else { None })
        .collect()
}

fn simd_filter_range_i64_fallback(values: &[i64], min: i64, max: i64) -> Vec<usize> {
    values.iter()
        .enumerate()
        .filter_map(|(i, &v)| if v >= min && v <= max { Some(i) } else { None })
        .collect()
}

//=============================================================================
// AVX2 implementations (x86_64)
//=============================================================================

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn simd_sum_i64_avx2(values: &[i64]) -> i64 {
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;
    
    let len = values.len();
    let mut sum = _mm256_setzero_si256();
    
    // 处理 4 个 i64 的块 (AVX2 = 256-bit = 4 × 64-bit)
    let chunks = len / 4;
    let remainder = len % 4;
    
    for i in 0..chunks {
        let idx = i * 4;
        let data = _mm256_loadu_si256(values.as_ptr().add(idx) as *const __m256i);
        sum = _mm256_add_epi64(sum, data);
    }
    
    // 水平求和
    let mut result = [0i64; 4];
    _mm256_storeu_si256(result.as_mut_ptr() as *mut __m256i, sum);
    let mut total = result.iter().sum::<i64>();
    
    // 处理剩余元素
    for i in (chunks * 4)..len {
        total += values[i];
    }
    
    total
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn simd_sum_f64_avx2(values: &[f64]) -> f64 {
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;
    
    let len = values.len();
    let mut sum = _mm256_setzero_pd();
    
    // 处理 4 个 f64 的块
    let chunks = len / 4;
    let remainder = len % 4;
    
    for i in 0..chunks {
        let idx = i * 4;
        let data = _mm256_loadu_pd(values.as_ptr().add(idx));
        sum = _mm256_add_pd(sum, data);
    }
    
    // 水平求和
    let mut result = [0.0f64; 4];
    _mm256_storeu_pd(result.as_mut_ptr(), sum);
    let mut total = result.iter().sum::<f64>();
    
    // 处理剩余元素
    for i in (chunks * 4)..len {
        total += values[i];
    }
    
    total
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn simd_min_i64_avx2(values: &[i64]) -> i64 {
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;
    
    let len = values.len();
    if len == 0 {
        return i64::MAX;
    }
    
    // 初始化为第一个元素
    let mut min_vec = _mm256_set1_epi64x(values[0]);
    
    // 处理 4 个 i64 的块
    let chunks = len / 4;
    
    for i in 0..chunks {
        let idx = i * 4;
        let data = _mm256_loadu_si256(values.as_ptr().add(idx) as *const __m256i);
        
        // AVX2 没有直接的 i64 min,使用比较 + blend
        let cmp = _mm256_cmpgt_epi64(min_vec, data);
        min_vec = _mm256_blendv_epi8(min_vec, data, cmp);
    }
    
    // 提取最小值
    let mut result = [0i64; 4];
    _mm256_storeu_si256(result.as_mut_ptr() as *mut __m256i, min_vec);
    let mut min_val = result.iter().min().copied().unwrap_or(i64::MAX);
    
    // 处理剩余元素
    for i in (chunks * 4)..len {
        min_val = min_val.min(values[i]);
    }
    
    min_val
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn simd_max_i64_avx2(values: &[i64]) -> i64 {
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;
    
    let len = values.len();
    if len == 0 {
        return i64::MIN;
    }
    
    let mut max_vec = _mm256_set1_epi64x(values[0]);
    
    let chunks = len / 4;
    
    for i in 0..chunks {
        let idx = i * 4;
        let data = _mm256_loadu_si256(values.as_ptr().add(idx) as *const __m256i);
        
        // 使用比较 + blend
        let cmp = _mm256_cmpgt_epi64(data, max_vec);
        max_vec = _mm256_blendv_epi8(max_vec, data, cmp);
    }
    
    let mut result = [0i64; 4];
    _mm256_storeu_si256(result.as_mut_ptr() as *mut __m256i, max_vec);
    let mut max_val = result.iter().max().copied().unwrap_or(i64::MIN);
    
    for i in (chunks * 4)..len {
        max_val = max_val.max(values[i]);
    }
    
    max_val
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn simd_filter_eq_i64_avx2(values: &[i64], target: i64) -> Vec<usize> {
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;
    
    let len = values.len();
    // 🚀 P1 优化:预分配容量(估算 25% 匹配率)
    let mut results = Vec::with_capacity(len / 4);
    
    let target_vec = _mm256_set1_epi64x(target);
    let chunks = len / 4;
    
    for i in 0..chunks {
        let idx = i * 4;
        let data = _mm256_loadu_si256(values.as_ptr().add(idx) as *const __m256i);
        
        // 比较相等
        let cmp = _mm256_cmpeq_epi64(data, target_vec);
        let mask = _mm256_movemask_pd(_mm256_castsi256_pd(cmp));
        
        // 检查每个位
        if mask & 0x1 != 0 { results.push(idx); }
        if mask & 0x2 != 0 { results.push(idx + 1); }
        if mask & 0x4 != 0 { results.push(idx + 2); }
        if mask & 0x8 != 0 { results.push(idx + 3); }
    }
    
    // 处理剩余元素
    for i in (chunks * 4)..len {
        if values[i] == target {
            results.push(i);
        }
    }
    
    results
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn simd_filter_range_i64_avx2(values: &[i64], min: i64, max: i64) -> Vec<usize> {
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;
    
    let len = values.len();
    // 🚀 P1 优化:预分配容量(估算 50% 匹配率)
    let mut results = Vec::with_capacity(len / 2);
    
    let min_vec = _mm256_set1_epi64x(min);
    let max_vec = _mm256_set1_epi64x(max);
    let chunks = len / 4;
    
    for i in 0..chunks {
        let idx = i * 4;
        let data = _mm256_loadu_si256(values.as_ptr().add(idx) as *const __m256i);
        
        // value >= min
        let cmp_min = _mm256_or_si256(
            _mm256_cmpgt_epi64(data, min_vec),
            _mm256_cmpeq_epi64(data, min_vec)
        );
        
        // value <= max
        let cmp_max = _mm256_or_si256(
            _mm256_cmpgt_epi64(max_vec, data),
            _mm256_cmpeq_epi64(data, max_vec)
        );
        
        // min <= value <= max
        let cmp = _mm256_and_si256(cmp_min, cmp_max);
        let mask = _mm256_movemask_pd(_mm256_castsi256_pd(cmp));
        
        if mask & 0x1 != 0 { results.push(idx); }
        if mask & 0x2 != 0 { results.push(idx + 1); }
        if mask & 0x4 != 0 { results.push(idx + 2); }
        if mask & 0x8 != 0 { results.push(idx + 3); }
    }
    
    // 处理剩余元素
    for i in (chunks * 4)..len {
        if values[i] >= min && values[i] <= max {
            results.push(i);
        }
    }
    
    results
}

//=============================================================================
// NEON implementations (aarch64)
//=============================================================================

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn simd_sum_i64_neon(values: &[i64]) -> i64 {
    #[cfg(target_arch = "aarch64")]
    use std::arch::aarch64::*;
    
    let len = values.len();
    let mut sum = vdupq_n_s64(0);
    
    // 处理 2 个 i64 的块 (NEON = 128-bit = 2 × 64-bit)
    let chunks = len / 2;
    let remainder = len % 2;
    
    for i in 0..chunks {
        let idx = i * 2;
        let data = vld1q_s64(values.as_ptr().add(idx));
        sum = vaddq_s64(sum, data);
    }
    
    // 提取结果
    let result = [vgetq_lane_s64(sum, 0), vgetq_lane_s64(sum, 1)];
    let mut total = result.iter().sum::<i64>();
    
    // 处理剩余元素
    for i in (chunks * 2)..len {
        total += values[i];
    }
    
    total
}

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn simd_sum_f64_neon(values: &[f64]) -> f64 {
    #[cfg(target_arch = "aarch64")]
    use std::arch::aarch64::*;
    
    let len = values.len();
    let mut sum = vdupq_n_f64(0.0);
    
    let chunks = len / 2;
    
    for i in 0..chunks {
        let idx = i * 2;
        let data = vld1q_f64(values.as_ptr().add(idx));
        sum = vaddq_f64(sum, data);
    }
    
    let result = [vgetq_lane_f64(sum, 0), vgetq_lane_f64(sum, 1)];
    let mut total = result.iter().sum::<f64>();
    
    for i in (chunks * 2)..len {
        total += values[i];
    }
    
    total
}

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn simd_min_i64_neon(values: &[i64]) -> i64 {
    // NEON 不直接支持 i64 min,回退到标量
    simd_min_i64_fallback(values)
}

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn simd_max_i64_neon(values: &[i64]) -> i64 {
    // NEON 不直接支持 i64 max,回退到标量
    simd_max_i64_fallback(values)
}

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn simd_filter_eq_i64_neon(values: &[i64], target: i64) -> Vec<usize> {
    #[cfg(target_arch = "aarch64")]
    use std::arch::aarch64::*;
    
    let len = values.len();
    // 🚀 P1 优化:预分配容量(估算 25% 匹配率)
    let mut results = Vec::with_capacity(len / 4);
    
    let target_vec = vdupq_n_s64(target);
    let chunks = len / 2;
    
    for i in 0..chunks {
        let idx = i * 2;
        let data = vld1q_s64(values.as_ptr().add(idx));
        let cmp = vceqq_s64(data, target_vec);
        
        // 提取比较结果 (cmp is uint64x2_t from vceqq_s64)
        let result_arr = [vgetq_lane_u64(cmp, 0), vgetq_lane_u64(cmp, 1)];
        
        if result_arr[0] != 0 {
            results.push(idx);
        }
        if result_arr[1] != 0 {
            results.push(idx + 1);
        }
    }
    
    for i in (chunks * 2)..len {
        if values[i] == target {
            results.push(i);
        }
    }
    
    results
}

#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn simd_filter_range_i64_neon(values: &[i64], min: i64, max: i64) -> Vec<usize> {
    #[cfg(target_arch = "aarch64")]
    use std::arch::aarch64::*;
    
    let len = values.len();
    // 🚀 P1 优化:预分配容量(估算 50% 匹配率)
    let mut results = Vec::with_capacity(len / 2);
    
    let min_vec = vdupq_n_s64(min);
    let max_vec = vdupq_n_s64(max);
    let chunks = len / 2;
    
    for i in 0..chunks {
        let idx = i * 2;
        let data = vld1q_s64(values.as_ptr().add(idx));
        
        // value >= min
        let cmp_min = vcgeq_s64(data, min_vec);
        // value <= max
        let cmp_max = vcleq_s64(data, max_vec);
        // AND
        let cmp = vandq_u64(cmp_min, cmp_max);
        
        if vgetq_lane_u64(cmp, 0) != 0 {
            results.push(idx);
        }
        if vgetq_lane_u64(cmp, 1) != 0 {
            results.push(idx + 1);
        }
    }
    
    for i in (chunks * 2)..len {
        if values[i] >= min && values[i] <= max {
            results.push(i);
        }
    }
    
    results
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_simd_sum_i64() {
        let values = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        let sum = simd_sum_i64(&values);
        assert_eq!(sum, 55);
    }
    
    #[test]
    fn test_simd_sum_f64() {
        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let sum = simd_sum_f64(&values);
        assert!((sum - 15.0).abs() < 1e-10);
    }
    
    #[test]
    fn test_simd_min_max() {
        let values = vec![5, 2, 9, 1, 7, 3];
        assert_eq!(simd_min_i64(&values), Some(1));
        assert_eq!(simd_max_i64(&values), Some(9));
    }
    
    #[test]
    fn test_simd_filter_eq() {
        let values = vec![1, 2, 3, 2, 4, 2, 5];
        let indices = simd_filter_eq_i64(&values, 2);
        assert_eq!(indices, vec![1, 3, 5]);
    }
    
    #[test]
    fn test_simd_filter_range() {
        let values = vec![1, 5, 10, 15, 20, 25, 30];
        let indices = simd_filter_range_i64(&values, 10, 20);
        assert_eq!(indices, vec![2, 3, 4]);
    }
    
    #[test]
    fn test_large_dataset() {
        // 测试大数据集 (100K 元素)
        let values: Vec<i64> = (0..100_000).collect();
        let sum = simd_sum_i64(&values);
        assert_eq!(sum, 4_999_950_000);
    }
}