leopard_vec 0.1.0

A high-performance parallelized vector container with deferred execution for bulk parallel operations
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
//! # Leopard
//!
//! A high-performance parallelized vector container library with deferred execution.
//!
//! Leopard provides [`LVec`], a parallel vector container that records operations and
//! executes them in a single bulk parallel pass. This design minimizes thread pool
//! creation overhead by batching all operations together.
//!
//! ## Key Features
//!
//! - **Deferred Execution**: Operations are recorded between [`LQueue::start`] and
//!   [`LQueue::end`], then executed in one parallel batch
//! - **Type-Agnostic Queue**: A single [`LQueue`] can manage `LVec<T>` of different types
//! - **SIMD-Style Masking**: Boolean masks with blend, select, and masked operations
//! - **Operator Overloading**: Natural syntax with `+`, `-`, `*`, `/` operators
//! - **Dependency Graph**: Operations are automatically ordered based on data dependencies
//!
//! ## Quick Start
//!
//! ```rust
//! use leopard::{LQueue, LVec, LMask};
//!
//! let q = LQueue::new();
//! let x: LVec<f64> = q.lvec_with_capacity(1000);
//! let y: LVec<f64> = q.lvec_with_capacity(1000);
//!
//! q.start();
//! let x = x.fill_with(|i| i as f64);
//! let y = y.fill_with(|i| (i * 2) as f64);
//! let z = &x * &y + &x;
//! q.end();
//!
//! let result = z.materialize().unwrap();
//! ```

use std::any::Any;
use std::cell::RefCell;
use std::ops::{Add, Sub, Mul, Div, Index, BitAnd, BitOr, BitXor, Not};
use std::rc::Rc;
use std::sync::Arc;
use rayon::prelude::*;

/// Default reserved capacity for LVec when using [`LQueue::lvec`].
const DEFAULT_CAPACITY: usize = 128;

// ============================================================================
// Type-erased Operation Trait (Internal)
// ============================================================================

/// Internal trait for type-erased operations that can be executed.
trait ErasedOperation: Send + Sync {
    /// Execute the operation and return the result as a type-erased Arc.
    fn execute(&self, results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync>;
    
    /// Get the unique result ID for this operation.
    fn result_id(&self) -> usize;
    
    /// Get the list of result IDs this operation depends on.
    fn dependencies(&self) -> Vec<usize>;
}

// ============================================================================
// Operation Types (Internal)
// ============================================================================

#[derive(Clone, Copy, Debug)]
enum BinaryOpType {
    Add,
    Sub,
    Mul,
    Div,
}

/// Source of an operand - either direct data or a pending result from another operation.
#[derive(Clone)]
enum OperandSource<T: Clone + Send + Sync> {
    /// Direct data that is already available.
    Direct(Arc<Vec<T>>),
    /// Pending result from another operation, identified by result ID.
    Pending(usize),
}

/// Binary operation between two LVecs (add, sub, mul, div).
struct BinaryOp<T: Clone + Send + Sync + 'static> {
    op_type: BinaryOpType,
    left: OperandSource<T>,
    right: OperandSource<T>,
    result_id: usize,
}

impl<T> ErasedOperation for BinaryOp<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    fn execute(&self, results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync> {
        let left_data = get_data::<T>(&self.left, results);
        let right_data = get_data::<T>(&self.right, results);
        let len = left_data.len().min(right_data.len());
        let op_type = self.op_type;

        let result: Vec<T> = (0..len)
            .into_par_iter()
            .map(|i| {
                let l = left_data[i].clone();
                let r = right_data[i].clone();
                match op_type {
                    BinaryOpType::Add => l + r,
                    BinaryOpType::Sub => l - r,
                    BinaryOpType::Mul => l * r,
                    BinaryOpType::Div => l / r,
                }
            })
            .collect();

        Arc::new(result)
    }

    fn result_id(&self) -> usize {
        self.result_id
    }

    fn dependencies(&self) -> Vec<usize> {
        let mut deps = Vec::new();
        if let OperandSource::Pending(id) = &self.left {
            deps.push(*id);
        }
        if let OperandSource::Pending(id) = &self.right {
            deps.push(*id);
        }
        deps
    }
}

/// Map operation that transforms each element using a closure.
struct MapOp<T: Clone + Send + Sync + 'static> {
    source: OperandSource<T>,
    func: Arc<dyn Fn(usize, &T) -> T + Send + Sync>,
    len: usize,
    result_id: usize,
}

impl<T: Clone + Send + Sync + 'static> ErasedOperation for MapOp<T> {
    fn execute(&self, results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync> {
        let data = get_data::<T>(&self.source, results);
        let len = self.len.min(data.len());
        let func = &self.func;

        let result: Vec<T> = (0..len)
            .into_par_iter()
            .map(|i| func(i, &data[i]))
            .collect();

        Arc::new(result)
    }

    fn result_id(&self) -> usize {
        self.result_id
    }

    fn dependencies(&self) -> Vec<usize> {
        if let OperandSource::Pending(id) = &self.source {
            vec![*id]
        } else {
            vec![]
        }
    }
}

/// Conditional map operation that applies different transformations based on a condition.
struct MapWhereOp<T: Clone + Send + Sync + 'static> {
    source: OperandSource<T>,
    condition: Arc<dyn Fn(usize, &T) -> bool + Send + Sync>,
    if_true: Arc<dyn Fn(usize, &T) -> T + Send + Sync>,
    if_false: Arc<dyn Fn(usize, &T) -> T + Send + Sync>,
    len: usize,
    result_id: usize,
}

impl<T: Clone + Send + Sync + 'static> ErasedOperation for MapWhereOp<T> {
    fn execute(&self, results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync> {
        let data = get_data::<T>(&self.source, results);
        let len = self.len.min(data.len());

        let result: Vec<T> = (0..len)
            .into_par_iter()
            .map(|i| {
                if (self.condition)(i, &data[i]) {
                    (self.if_true)(i, &data[i])
                } else {
                    (self.if_false)(i, &data[i])
                }
            })
            .collect();

        Arc::new(result)
    }

    fn result_id(&self) -> usize {
        self.result_id
    }

    fn dependencies(&self) -> Vec<usize> {
        if let OperandSource::Pending(id) = &self.source {
            vec![*id]
        } else {
            vec![]
        }
    }
}

/// Blend operation that selects elements from two vectors based on a mask.
struct BlendOp<T: Clone + Send + Sync + 'static> {
    if_false: OperandSource<T>,
    if_true: OperandSource<T>,
    mask: Arc<Vec<bool>>,
    len: usize,
    result_id: usize,
}

impl<T: Clone + Send + Sync + 'static> ErasedOperation for BlendOp<T> {
    fn execute(&self, results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync> {
        let false_data = get_data::<T>(&self.if_false, results);
        let true_data = get_data::<T>(&self.if_true, results);
        let mask = &self.mask;
        let len = self.len;

        let result: Vec<T> = (0..len)
            .into_par_iter()
            .map(|i| {
                if mask[i] {
                    true_data[i].clone()
                } else {
                    false_data[i].clone()
                }
            })
            .collect();

        Arc::new(result)
    }

    fn result_id(&self) -> usize {
        self.result_id
    }

    fn dependencies(&self) -> Vec<usize> {
        let mut deps = Vec::new();
        if let OperandSource::Pending(id) = &self.if_false {
            deps.push(*id);
        }
        if let OperandSource::Pending(id) = &self.if_true {
            deps.push(*id);
        }
        deps
    }
}

/// Masked apply operation that applies a function only where mask is true.
struct MaskedApplyOp<T: Clone + Send + Sync + 'static> {
    source: OperandSource<T>,
    mask: Arc<Vec<bool>>,
    func: Arc<dyn Fn(usize, &T) -> T + Send + Sync>,
    len: usize,
    result_id: usize,
}

impl<T: Clone + Send + Sync + 'static> ErasedOperation for MaskedApplyOp<T> {
    fn execute(&self, results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync> {
        let data = get_data::<T>(&self.source, results);
        let mask = &self.mask;
        let len = self.len;
        let func = &self.func;

        let result: Vec<T> = (0..len)
            .into_par_iter()
            .map(|i| {
                if mask[i] {
                    func(i, &data[i])
                } else {
                    data[i].clone()
                }
            })
            .collect();

        Arc::new(result)
    }

    fn result_id(&self) -> usize {
        self.result_id
    }

    fn dependencies(&self) -> Vec<usize> {
        if let OperandSource::Pending(id) = &self.source {
            vec![*id]
        } else {
            vec![]
        }
    }
}

/// Fill operation that initializes a vector using a closure.
struct FillOp<T: Clone + Send + Sync + 'static> {
    func: Arc<dyn Fn(usize) -> T + Send + Sync>,
    len: usize,
    result_id: usize,
}

impl<T: Clone + Send + Sync + 'static> ErasedOperation for FillOp<T> {
    fn execute(&self, _results: &[Option<Arc<dyn Any + Send + Sync>>]) -> Arc<dyn Any + Send + Sync> {
        let len = self.len;
        let func = &self.func;

        let result: Vec<T> = (0..len)
            .into_par_iter()
            .map(|i| func(i))
            .collect();

        Arc::new(result)
    }

    fn result_id(&self) -> usize {
        self.result_id
    }

    fn dependencies(&self) -> Vec<usize> {
        vec![]
    }
}

/// Helper to extract data from an operand source.
fn get_data<T: Clone + Send + Sync + 'static>(
    source: &OperandSource<T>,
    results: &[Option<Arc<dyn Any + Send + Sync>>],
) -> Arc<Vec<T>> {
    match source {
        OperandSource::Direct(data) => Arc::clone(data),
        OperandSource::Pending(id) => {
            let any_ref = results[*id].as_ref().unwrap();
            any_ref.clone().downcast::<Vec<T>>().unwrap()
        }
    }
}

// ============================================================================
// LMask - Boolean mask for SIMD-style branchless operations
// ============================================================================

/// A boolean mask for parallel conditional operations.
///
/// `LMask` provides SIMD-style masking capabilities for [`LVec`] operations.
/// Masks can be combined using logical operators (`&`, `|`, `^`, `!`) and
/// used with methods like [`LVec::blend`], [`LVec::masked_apply`], and
/// [`LVec::masked_fill`].
///
/// # Examples
///
/// ```rust
/// use leopard::LMask;
///
/// // Create a uniform mask
/// let all_true = LMask::new(10, true);
///
/// // Create a pattern mask
/// let evens = LMask::from_fn(10, |i| i % 2 == 0);
///
/// // Combine masks
/// let combined = &all_true & &evens;
/// let inverted = !&evens;
/// ```
#[derive(Clone)]
pub struct LMask {
    data: Arc<Vec<bool>>,
    len: usize,
}

impl LMask {
    /// Creates a new mask with all elements set to the same value.
    ///
    /// # Arguments
    ///
    /// * `len` - The length of the mask
    /// * `value` - The boolean value for all elements
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LMask;
    ///
    /// let all_true = LMask::new(100, true);
    /// let all_false = LMask::new(100, false);
    /// ```
    pub fn new(len: usize, value: bool) -> Self {
        LMask {
            data: Arc::new(vec![value; len]),
            len,
        }
    }

    /// Creates a mask from a closure that takes an index and returns a boolean.
    ///
    /// # Arguments
    ///
    /// * `len` - The length of the mask
    /// * `f` - A closure that takes an index `usize` and returns `bool`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LMask;
    ///
    /// // Even indices
    /// let evens = LMask::from_fn(10, |i| i % 2 == 0);
    ///
    /// // First half
    /// let first_half = LMask::from_fn(100, |i| i < 50);
    /// ```
    pub fn from_fn<F>(len: usize, f: F) -> Self
    where
        F: Fn(usize) -> bool,
    {
        let data: Vec<bool> = (0..len).map(f).collect();
        LMask {
            data: Arc::new(data),
            len,
        }
    }

    /// Returns the length of the mask.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LMask;
    ///
    /// let mask = LMask::new(100, true);
    /// assert_eq!(mask.len(), 100);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the mask has no elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LMask;
    ///
    /// let empty = LMask::new(0, true);
    /// assert!(empty.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the mask data as a slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LMask;
    ///
    /// let mask = LMask::from_fn(5, |i| i > 2);
    /// assert_eq!(mask.as_slice(), &[false, false, false, true, true]);
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[bool] {
        &self.data[..self.len]
    }
}

impl Index<usize> for LMask {
    type Output = bool;
    
    /// Accesses the mask value at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `index >= self.len()`.
    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index]
    }
}

impl BitAnd for &LMask {
    type Output = LMask;
    
    /// Performs element-wise logical AND between two masks.
    fn bitand(self, other: Self) -> Self::Output {
        let len = self.len.min(other.len);
        let data: Vec<bool> = (0..len).map(|i| self.data[i] && other.data[i]).collect();
        LMask { data: Arc::new(data), len }
    }
}

impl BitAnd for LMask {
    type Output = LMask;
    fn bitand(self, other: Self) -> Self::Output { (&self).bitand(&other) }
}

impl BitOr for &LMask {
    type Output = LMask;
    
    /// Performs element-wise logical OR between two masks.
    fn bitor(self, other: Self) -> Self::Output {
        let len = self.len.min(other.len);
        let data: Vec<bool> = (0..len).map(|i| self.data[i] || other.data[i]).collect();
        LMask { data: Arc::new(data), len }
    }
}

impl BitOr for LMask {
    type Output = LMask;
    fn bitor(self, other: Self) -> Self::Output { (&self).bitor(&other) }
}

impl BitXor for &LMask {
    type Output = LMask;
    
    /// Performs element-wise logical XOR between two masks.
    fn bitxor(self, other: Self) -> Self::Output {
        let len = self.len.min(other.len);
        let data: Vec<bool> = (0..len).map(|i| self.data[i] ^ other.data[i]).collect();
        LMask { data: Arc::new(data), len }
    }
}

impl BitXor for LMask {
    type Output = LMask;
    fn bitxor(self, other: Self) -> Self::Output { (&self).bitxor(&other) }
}

impl Not for &LMask {
    type Output = LMask;
    
    /// Performs element-wise logical NOT on the mask.
    fn not(self) -> Self::Output {
        let data: Vec<bool> = self.data.iter().map(|&b| !b).collect();
        LMask { data: Arc::new(data), len: self.len }
    }
}

impl Not for LMask {
    type Output = LMask;
    fn not(self) -> Self::Output { (&self).not() }
}

impl std::fmt::Debug for LMask {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LMask({:?})", self.as_slice())
    }
}

// ============================================================================
// LQueue - The operation queue
// ============================================================================

/// Internal state of the operation queue.
struct LQueueInner {
    operations: Vec<Box<dyn ErasedOperation>>,
    results: Vec<Option<Arc<dyn Any + Send + Sync>>>,
    recording: bool,
    next_result_id: usize,
}

/// The operation queue that records and executes parallel operations.
///
/// `LQueue` is the central coordinator for deferred parallel execution. It manages
/// the recording of operations and their bulk execution, minimizing thread pool
/// overhead by batching all operations together.
///
/// # Workflow
///
/// 1. Create vectors with [`LQueue::lvec`] or [`LQueue::lvec_with_capacity`]
/// 2. Call [`LQueue::start`] to begin recording
/// 3. Perform operations on [`LVec`] instances (all operations are recorded, not executed)
/// 4. Call [`LQueue::end`] to execute all recorded operations in parallel
/// 5. Use [`LVec::materialize`] to retrieve results
///
/// # Type Agnostic
///
/// A single `LQueue` can manage vectors of different types simultaneously:
///
/// ```rust
/// use leopard::{LQueue, LVec};
///
/// let q = LQueue::new();
/// let integers: LVec<i32> = q.lvec_with_capacity(100);
/// let floats: LVec<f64> = q.lvec_with_capacity(100);
/// // Both can be used in the same recording session
/// ```
///
/// # Examples
///
/// ```rust
/// use leopard::{LQueue, LVec};
///
/// let q = LQueue::new();
/// let x: LVec<f64> = q.lvec_with_capacity(1000);
/// let y: LVec<f64> = q.lvec_with_capacity(1000);
///
/// q.start();
/// let x = x.fill_with(|i| i as f64);
/// let y = y.fill_with(|i| (i * 2) as f64);
/// let z = &x + &y;
/// q.end();
///
/// let result = z.materialize().unwrap();
/// println!("Sum: {:?}", &result[0..5]);
/// ```
#[derive(Clone)]
pub struct LQueue {
    inner: Rc<RefCell<LQueueInner>>,
}

impl LQueue {
    /// Creates a new operation queue.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LQueue;
    ///
    /// let q = LQueue::new();
    /// ```
    pub fn new() -> Self {
        LQueue {
            inner: Rc::new(RefCell::new(LQueueInner {
                operations: Vec::new(),
                results: Vec::new(),
                recording: false,
                next_result_id: 0,
            })),
        }
    }

    /// Creates a new [`LVec`] with the default capacity (128 elements).
    ///
    /// # Type Parameters
    ///
    /// * `T` - The element type, must implement `Clone + Send + Sync + Default`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let vec: LVec<f64> = q.lvec();
    /// assert_eq!(vec.capacity(), 128);
    /// ```
    pub fn lvec<T>(&self) -> LVec<T>
    where
        T: Clone + Send + Sync + Default + 'static,
    {
        self.lvec_with_capacity(DEFAULT_CAPACITY)
    }

    /// Creates a new [`LVec`] with the specified capacity.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The number of elements the vector can hold
    ///
    /// # Type Parameters
    ///
    /// * `T` - The element type, must implement `Clone + Send + Sync + Default`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let vec: LVec<f64> = q.lvec_with_capacity(10000);
    /// assert_eq!(vec.capacity(), 10000);
    /// ```
    pub fn lvec_with_capacity<T>(&self, capacity: usize) -> LVec<T>
    where
        T: Clone + Send + Sync + Default + 'static,
    {
        LVec {
            data: Arc::new(vec![T::default(); capacity]),
            len: capacity,
            capacity,
            queue: Rc::clone(&self.inner),
            pending_result_id: None,
        }
    }

    /// Starts recording operations.
    ///
    /// After calling `start()`, all operations on [`LVec`] instances created from
    /// this queue will be recorded rather than executed. The operations will be
    /// executed when [`LQueue::end`] is called.
    ///
    /// # Panics
    ///
    /// Operations on [`LVec`] will panic if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<f64> = q.lvec_with_capacity(100);
    ///
    /// q.start();  // Begin recording
    /// let x = x.fill(42.0);
    /// // ... more operations ...
    /// q.end();    // Execute all recorded operations
    /// ```
    pub fn start(&self) {
        let mut inner = self.inner.borrow_mut();
        inner.recording = true;
        inner.operations.clear();
        inner.results.clear();
        inner.next_result_id = 0;
    }

    /// Stops recording and executes all recorded operations in parallel.
    ///
    /// This method executes all operations that were recorded since the last
    /// [`LQueue::start`] call. Operations are executed in dependency order,
    /// with independent operations running in parallel.
    ///
    /// After `end()` is called, results can be retrieved using [`LVec::materialize`].
    ///
    /// # Performance
    ///
    /// All parallel execution happens in this single call, minimizing thread pool
    /// creation overhead compared to executing operations individually.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<f64> = q.lvec_with_capacity(1000);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as f64);
    /// let y = x.map(|_, v| v * 2.0);
    /// q.end();  // Both fill and map execute here
    ///
    /// let result = y.materialize().unwrap();
    /// ```
    pub fn end(&self) {
        let mut inner = self.inner.borrow_mut();
        inner.recording = false;
        Self::execute_all(&mut inner);
    }

    /// Executes all recorded operations respecting dependencies.
    fn execute_all(inner: &mut LQueueInner) {
        if inner.operations.is_empty() {
            return;
        }

        // Resize results vector
        inner.results.resize_with(inner.next_result_id, || None);

        // Build dependency levels for proper execution order
        let mut levels: Vec<Vec<usize>> = Vec::new();
        let mut op_levels: Vec<usize> = vec![0; inner.operations.len()];

        let mut result_to_op: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
        for (i, op) in inner.operations.iter().enumerate() {
            result_to_op.insert(op.result_id(), i);
        }

        // Compute the level for each operation based on dependencies
        for (i, op) in inner.operations.iter().enumerate() {
            let mut level = 0;
            for dep_id in op.dependencies() {
                if let Some(&dep_op_idx) = result_to_op.get(&dep_id) {
                    level = level.max(op_levels[dep_op_idx] + 1);
                }
            }
            op_levels[i] = level;
            while levels.len() <= level {
                levels.push(Vec::new());
            }
            levels[level].push(i);
        }

        // Execute each level (operations within a level have no dependencies on each other)
        for level_ops in levels {
            for &op_idx in &level_ops {
                let result = inner.operations[op_idx].execute(&inner.results);
                let result_id = inner.operations[op_idx].result_id();
                inner.results[result_id] = Some(result);
            }
        }
    }

    /// Returns `true` if the queue is currently recording operations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::LQueue;
    ///
    /// let q = LQueue::new();
    /// assert!(!q.is_recording());
    ///
    /// q.start();
    /// assert!(q.is_recording());
    ///
    /// q.end();
    /// assert!(!q.is_recording());
    /// ```
    pub fn is_recording(&self) -> bool {
        self.inner.borrow().recording
    }
}

impl Default for LQueue {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// LVec - The parallelized vector container
// ============================================================================

/// A parallelized vector container with deferred execution.
///
/// `LVec` is the main data structure in Leopard. It represents a vector that
/// supports parallel operations through deferred execution. Operations on `LVec`
/// are recorded when called between [`LQueue::start`] and [`LQueue::end`], and
/// executed in bulk when `end()` is called.
///
/// # Creating LVec
///
/// `LVec` instances must be created through an [`LQueue`]:
///
/// ```rust
/// use leopard::{LQueue, LVec};
///
/// let q = LQueue::new();
/// let vec: LVec<f64> = q.lvec_with_capacity(1000);
/// ```
///
/// # Operations
///
/// All operations must be called between `q.start()` and `q.end()`:
///
/// - **Initialization**: [`fill`](LVec::fill), [`fill_with`](LVec::fill_with)
/// - **Transformation**: [`map`](LVec::map), [`map_where`](LVec::map_where)
/// - **Arithmetic**: `+`, `-`, `*`, `/` operators
/// - **Masking**: [`blend`](LVec::blend), [`masked_apply`](LVec::masked_apply), [`masked_fill`](LVec::masked_fill)
///
/// # Retrieving Results
///
/// After `q.end()`, use [`materialize`](LVec::materialize) to get the computed data:
///
/// ```rust
/// use leopard::{LQueue, LVec};
///
/// let q = LQueue::new();
/// let x: LVec<f64> = q.lvec_with_capacity(10);
///
/// q.start();
/// let x = x.fill_with(|i| i as f64);
/// q.end();
///
/// let data = x.materialize().unwrap();
/// println!("{:?}", &data[..]);
/// ```
///
/// # Pending State
///
/// After an operation is recorded, the resulting `LVec` is in a "pending" state.
/// The actual data is not available until after `q.end()` is called and
/// [`materialize`](LVec::materialize) is used to retrieve it.
#[derive(Clone)]
pub struct LVec<T: Clone + Send + Sync + 'static> {
    data: Arc<Vec<T>>,
    len: usize,
    capacity: usize,
    queue: Rc<RefCell<LQueueInner>>,
    pending_result_id: Option<usize>,
}

impl<T: Clone + Send + Sync + 'static> LVec<T> {
    /// Returns the length of the vector.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let vec: LVec<f64> = q.lvec_with_capacity(100);
    /// assert_eq!(vec.len(), 100);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the vector has no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the capacity of the vector.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns `true` if this vector has a pending operation.
    ///
    /// A pending vector's data is not yet available. Call [`materialize`](LVec::materialize)
    /// after [`LQueue::end`] to retrieve the computed data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<f64> = q.lvec_with_capacity(10);
    /// assert!(!x.is_pending());
    ///
    /// q.start();
    /// let y = x.fill(1.0);
    /// assert!(y.is_pending());
    /// q.end();
    /// ```
    #[inline]
    pub fn is_pending(&self) -> bool {
        self.pending_result_id.is_some()
    }

    /// Retrieves the computed data after [`LQueue::end`] has been called.
    ///
    /// For pending vectors (those created by operations), this returns the
    /// computed result. For non-pending vectors, this returns the original data.
    ///
    /// # Returns
    ///
    /// - `Some(Arc<Vec<T>>)` if the data is available
    /// - `None` if the vector is pending and `q.end()` hasn't been called
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<f64> = q.lvec_with_capacity(5);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as f64 * 2.0);
    /// q.end();
    ///
    /// let data = x.materialize().unwrap();
    /// assert_eq!(&data[..], &[0.0, 2.0, 4.0, 6.0, 8.0]);
    /// ```
    pub fn materialize(&self) -> Option<Arc<Vec<T>>> {
        if let Some(result_id) = self.pending_result_id {
            let inner = self.queue.borrow();
            inner.results.get(result_id).and_then(|r| {
                r.as_ref().and_then(|arc| arc.clone().downcast::<Vec<T>>().ok())
            })
        } else {
            Some(Arc::clone(&self.data))
        }
    }

    /// Returns the data as a slice.
    ///
    /// # Warning
    ///
    /// For pending vectors, this returns an empty or default-initialized slice,
    /// not the computed result. Use [`materialize`](LVec::materialize) after
    /// [`LQueue::end`] to get the actual computed data.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.data[..self.len]
    }

    // ========================================================================
    // Internal helpers
    // ========================================================================

    fn get_source(&self) -> OperandSource<T> {
        if let Some(id) = self.pending_result_id {
            OperandSource::Pending(id)
        } else {
            OperandSource::Direct(Arc::clone(&self.data))
        }
    }

    fn create_pending(&self, result_id: usize, len: usize) -> Self {
        LVec {
            data: Arc::new(Vec::new()),
            len,
            capacity: len,
            queue: Rc::clone(&self.queue),
            pending_result_id: Some(result_id),
        }
    }

    // ========================================================================
    // Recording Operations
    // ========================================================================

    /// Fills the vector using a closure that takes an index.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `f` - A closure that takes an index `usize` and returns the value `T`
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<f64> = q.lvec_with_capacity(5);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as f64 * 10.0);
    /// q.end();
    ///
    /// let data = x.materialize().unwrap();
    /// assert_eq!(&data[..], &[0.0, 10.0, 20.0, 30.0, 40.0]);
    /// ```
    pub fn fill_with<F>(&self, f: F) -> Self
    where
        F: Fn(usize) -> T + Send + Sync + 'static,
    {
        let mut inner = self.queue.borrow_mut();
        if !inner.recording {
            panic!("fill_with must be called between q.start() and q.end()");
        }

        let result_id = inner.next_result_id;
        inner.next_result_id += 1;

        inner.operations.push(Box::new(FillOp {
            func: Arc::new(f),
            len: self.len,
            result_id,
        }));

        drop(inner);
        self.create_pending(result_id, self.len)
    }

    /// Fills the vector with a constant value.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `value` - The value to fill the vector with
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<i32> = q.lvec_with_capacity(5);
    ///
    /// q.start();
    /// let x = x.fill(42);
    /// q.end();
    ///
    /// let data = x.materialize().unwrap();
    /// assert_eq!(&data[..], &[42, 42, 42, 42, 42]);
    /// ```
    pub fn fill(&self, value: T) -> Self {
        self.fill_with(move |_| value.clone())
    }

    /// Transforms each element using a closure.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `f` - A closure that takes an index and a reference to the element,
    ///         and returns the transformed value
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<f64> = q.lvec_with_capacity(5);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as f64);
    /// let y = x.map(|_, v| v * v);  // Square each element
    /// q.end();
    ///
    /// let data = y.materialize().unwrap();
    /// assert_eq!(&data[..], &[0.0, 1.0, 4.0, 9.0, 16.0]);
    /// ```
    pub fn map<F>(&self, f: F) -> Self
    where
        F: Fn(usize, &T) -> T + Send + Sync + 'static,
    {
        let mut inner = self.queue.borrow_mut();
        if !inner.recording {
            panic!("map must be called between q.start() and q.end()");
        }

        let result_id = inner.next_result_id;
        inner.next_result_id += 1;

        inner.operations.push(Box::new(MapOp {
            source: self.get_source(),
            func: Arc::new(f),
            len: self.len,
            result_id,
        }));

        drop(inner);
        self.create_pending(result_id, self.len)
    }

    /// Applies different transformations based on a condition.
    ///
    /// For each element, if the condition returns `true`, `if_true` is applied;
    /// otherwise, `if_false` is applied. This is SIMD-style branchless conditional
    /// execution.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `condition` - A closure that returns `true` or `false` for each element
    /// * `if_true` - Transformation to apply when condition is `true`
    /// * `if_false` - Transformation to apply when condition is `false`
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<i32> = q.lvec_with_capacity(6);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as i32 + 1);
    /// let y = x.map_where(
    ///     |_, v| *v % 2 == 0,  // Is even?
    ///     |_, v| v * 10,       // If even: multiply by 10
    ///     |_, v| v + 1000,     // If odd: add 1000
    /// );
    /// q.end();
    ///
    /// let data = y.materialize().unwrap();
    /// // [1, 2, 3, 4, 5, 6] -> [1001, 20, 1003, 40, 1005, 60]
    /// ```
    pub fn map_where<C, TF, FF>(&self, condition: C, if_true: TF, if_false: FF) -> Self
    where
        C: Fn(usize, &T) -> bool + Send + Sync + 'static,
        TF: Fn(usize, &T) -> T + Send + Sync + 'static,
        FF: Fn(usize, &T) -> T + Send + Sync + 'static,
    {
        let mut inner = self.queue.borrow_mut();
        if !inner.recording {
            panic!("map_where must be called between q.start() and q.end()");
        }

        let result_id = inner.next_result_id;
        inner.next_result_id += 1;

        inner.operations.push(Box::new(MapWhereOp {
            source: self.get_source(),
            condition: Arc::new(condition),
            if_true: Arc::new(if_true),
            if_false: Arc::new(if_false),
            len: self.len,
            result_id,
        }));

        drop(inner);
        self.create_pending(result_id, self.len)
    }

    /// Creates a mask from a predicate applied to each element.
    ///
    /// Unlike other operations, this executes immediately (not recorded) because
    /// masks are needed to define subsequent masking operations.
    ///
    /// # Arguments
    ///
    /// * `predicate` - A closure that returns `true` or `false` for each element
    ///
    /// # Warning
    ///
    /// This only works on non-pending vectors. For pending vectors, use
    /// [`LMask::from_fn`] with the appropriate pattern.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<i32> = q.lvec_with_capacity(10);
    ///
    /// // Note: mask() works on the initial (non-pending) vector
    /// let mask = x.mask(|i, _| i >= 5);
    /// ```
    pub fn mask<F>(&self, predicate: F) -> LMask
    where
        F: Fn(usize, &T) -> bool,
    {
        let data: Vec<bool> = (0..self.len)
            .map(|i| predicate(i, &self.data[i]))
            .collect();
        
        LMask {
            data: Arc::new(data),
            len: self.len,
        }
    }

    /// Blends two vectors using a mask (SIMD-style select).
    ///
    /// For each element, if the mask is `true`, the value from `other` is used;
    /// otherwise, the value from `self` is used.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `other` - The vector to blend with
    /// * `mask` - The mask determining which vector to select from
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec, LMask};
    ///
    /// let q = LQueue::new();
    /// let a: LVec<i32> = q.lvec_with_capacity(5);
    /// let b: LVec<i32> = q.lvec_with_capacity(5);
    /// let mask = LMask::from_fn(5, |i| i >= 3);
    ///
    /// q.start();
    /// let a = a.fill(1);
    /// let b = b.fill(100);
    /// let c = a.blend(&b, &mask);
    /// q.end();
    ///
    /// let data = c.materialize().unwrap();
    /// // mask: [false, false, false, true, true]
    /// // result: [1, 1, 1, 100, 100]
    /// ```
    pub fn blend(&self, other: &Self, mask: &LMask) -> Self {
        let mut inner = self.queue.borrow_mut();
        if !inner.recording {
            panic!("blend must be called between q.start() and q.end()");
        }

        let result_id = inner.next_result_id;
        inner.next_result_id += 1;
        let len = self.len.min(other.len).min(mask.len());

        inner.operations.push(Box::new(BlendOp {
            if_false: self.get_source(),
            if_true: other.get_source(),
            mask: Arc::clone(&mask.data),
            len,
            result_id,
        }));

        drop(inner);
        self.create_pending(result_id, len)
    }

    /// Selects between two vectors based on a mask.
    ///
    /// This is equivalent to `if_false.blend(if_true, mask)`.
    ///
    /// # Arguments
    ///
    /// * `mask` - The mask determining which vector to select from
    /// * `if_true` - Values to use where mask is `true`
    /// * `if_false` - Values to use where mask is `false`
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    pub fn select(mask: &LMask, if_true: &Self, if_false: &Self) -> Self {
        if_false.blend(if_true, mask)
    }

    /// Applies a function only where the mask is `true`.
    ///
    /// Elements where the mask is `false` retain their original values.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `mask` - The mask determining where to apply the function
    /// * `f` - The function to apply
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec, LMask};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<i32> = q.lvec_with_capacity(5);
    /// let mask = LMask::from_fn(5, |i| i >= 3);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as i32);
    /// let y = x.masked_apply(&mask, |_, v| v * 100);
    /// q.end();
    ///
    /// let data = y.materialize().unwrap();
    /// // [0, 1, 2, 3, 4] with mask [F, F, F, T, T]
    /// // result: [0, 1, 2, 300, 400]
    /// ```
    pub fn masked_apply<F>(&self, mask: &LMask, f: F) -> Self
    where
        F: Fn(usize, &T) -> T + Send + Sync + 'static,
    {
        let mut inner = self.queue.borrow_mut();
        if !inner.recording {
            panic!("masked_apply must be called between q.start() and q.end()");
        }

        let result_id = inner.next_result_id;
        inner.next_result_id += 1;
        let len = self.len.min(mask.len());

        inner.operations.push(Box::new(MaskedApplyOp {
            source: self.get_source(),
            mask: Arc::clone(&mask.data),
            func: Arc::new(f),
            len,
            result_id,
        }));

        drop(inner);
        self.create_pending(result_id, len)
    }

    /// Fills with a constant value only where the mask is `true`.
    ///
    /// Elements where the mask is `false` retain their original values.
    ///
    /// This is a recorded operation that must be called between [`LQueue::start`]
    /// and [`LQueue::end`].
    ///
    /// # Arguments
    ///
    /// * `mask` - The mask determining where to fill
    /// * `value` - The value to fill with
    ///
    /// # Panics
    ///
    /// Panics if called outside of a `start()`/`end()` block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use leopard::{LQueue, LVec, LMask};
    ///
    /// let q = LQueue::new();
    /// let x: LVec<i32> = q.lvec_with_capacity(5);
    /// let mask = LMask::from_fn(5, |i| i >= 3);
    ///
    /// q.start();
    /// let x = x.fill_with(|i| i as i32);
    /// let y = x.masked_fill(&mask, 999);
    /// q.end();
    ///
    /// let data = y.materialize().unwrap();
    /// // [0, 1, 2, 3, 4] with mask [F, F, F, T, T]
    /// // result: [0, 1, 2, 999, 999]
    /// ```
    pub fn masked_fill(&self, mask: &LMask, value: T) -> Self
    where
        T: 'static,
    {
        self.masked_apply(mask, move |_, _| value.clone())
    }
}

impl<T: Clone + Send + Sync + Default + 'static> Default for LVec<T> {
    fn default() -> Self {
        panic!("LVec must be created via LQueue::lvec() or LQueue::lvec_with_capacity()")
    }
}

impl<T: Clone + Send + Sync + 'static> Index<usize> for LVec<T> {
    type Output = T;
    
    /// Accesses the element at the given index.
    ///
    /// # Warning
    ///
    /// For pending vectors, this accesses the original (uncomputed) data,
    /// not the result of the pending operation. Use [`materialize`](LVec::materialize)
    /// after [`LQueue::end`] to get the computed data.
    ///
    /// # Panics
    ///
    /// Panics if `index >= self.len()`.
    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index]
    }
}

// ============================================================================
// Operator Overloading (all recorded)
// ============================================================================

fn record_binary_op<T>(left: &LVec<T>, right: &LVec<T>, op_type: BinaryOpType) -> LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    let mut inner = left.queue.borrow_mut();
    if !inner.recording {
        panic!("Binary operations must be called between q.start() and q.end()");
    }

    let result_id = inner.next_result_id;
    inner.next_result_id += 1;
    let len = left.len.min(right.len);

    inner.operations.push(Box::new(BinaryOp {
        op_type,
        left: left.get_source(),
        right: right.get_source(),
        result_id,
    }));

    drop(inner);
    left.create_pending(result_id, len)
}

impl<T> Add for LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = Self;
    
    /// Adds two vectors element-wise (recorded operation).
    fn add(self, other: Self) -> Self::Output {
        record_binary_op(&self, &other, BinaryOpType::Add)
    }
}

impl<T> Add for &LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = LVec<T>;
    
    /// Adds two vectors element-wise (recorded operation).
    fn add(self, other: Self) -> Self::Output {
        record_binary_op(self, other, BinaryOpType::Add)
    }
}

impl<T> Sub for LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = Self;
    
    /// Subtracts two vectors element-wise (recorded operation).
    fn sub(self, other: Self) -> Self::Output {
        record_binary_op(&self, &other, BinaryOpType::Sub)
    }
}

impl<T> Sub for &LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = LVec<T>;
    
    /// Subtracts two vectors element-wise (recorded operation).
    fn sub(self, other: Self) -> Self::Output {
        record_binary_op(self, other, BinaryOpType::Sub)
    }
}

impl<T> Mul for LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = Self;
    
    /// Multiplies two vectors element-wise (recorded operation).
    fn mul(self, other: Self) -> Self::Output {
        record_binary_op(&self, &other, BinaryOpType::Mul)
    }
}

impl<T> Mul for &LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = LVec<T>;
    
    /// Multiplies two vectors element-wise (recorded operation).
    fn mul(self, other: Self) -> Self::Output {
        record_binary_op(self, other, BinaryOpType::Mul)
    }
}

impl<T> Div for LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = Self;
    
    /// Divides two vectors element-wise (recorded operation).
    fn div(self, other: Self) -> Self::Output {
        record_binary_op(&self, &other, BinaryOpType::Div)
    }
}

impl<T> Div for &LVec<T>
where
    T: Clone + Send + Sync + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + 'static,
{
    type Output = LVec<T>;
    
    /// Divides two vectors element-wise (recorded operation).
    fn div(self, other: Self) -> Self::Output {
        record_binary_op(self, other, BinaryOpType::Div)
    }
}

impl<T: Clone + Send + Sync + std::fmt::Debug + 'static> std::fmt::Debug for LVec<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_pending() {
            write!(f, "LVec<pending>")
        } else {
            write!(f, "LVec({:?})", self.as_slice())
        }
    }
}