-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy patharray.rs
More file actions
5596 lines (4919 loc) · 177 KB
/
Copy patharray.rs
File metadata and controls
5596 lines (4919 loc) · 177 KB
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
use crate::floats::{Float32, Float64};
use crate::ints::{Int16, Int32, Int64, Int8, UInt16, UInt32, UInt64, UInt8};
use crate::native_array::{ArrayType, NativeArray};
use crate::options::SomeWrapper;
use crate::types::FSharpRef;
use crate::util::{DefaultComparer, ProjectionComparer};
use pyo3::class::basic::CompareOp;
use pyo3::types::PyNotImplemented;
use pyo3::types::{PyBool, PyInt};
use pyo3::types::{PyBytes, PyTuple, PyType};
use pyo3::BoundObject;
use pyo3::{exceptions, IntoPyObjectExt, PyTypeInfo};
use pyo3::{
prelude::*,
types::{PyAnyMethods, PyList},
};
use std::sync::{Arc, Mutex};
#[pyclass(module = "fable", subclass, from_py_object)]
#[derive(Clone, Debug)]
pub struct FSharpArray {
storage: NativeArray,
}
#[pyclass(module="fable", extends=FSharpArray)]
struct Int8Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct UInt8Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct Int16Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct UInt16Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct Int32Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct UInt32Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct Int64Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct UInt64Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct Float32Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct Float64Array {}
#[pyclass(module="fable", extends=FSharpArray)]
struct BoolArray {}
#[pyclass(module="fable", extends=FSharpArray)]
struct GenericArray {}
// Macro to reduce repetition in type extraction for FSharpArray::new.
// This ensures both elegance and performance, following best Rust and craftsman practices.
macro_rules! try_extract_array {
($elements:expr, $_py:expr, $variant:ident, $wrapper:ty, $native:ty) => {
if let Ok(vec) = extract_typed_vec_from_elements::<$native>($elements) {
Some(FSharpArray {
storage: NativeArray::$variant(vec),
})
} else {
None
}
};
}
/// A cow-like wrapper that either borrows from an existing Python FSharpArray or owns a new one.
///
/// # Performance Optimization
///
/// This type avoids expensive deep clones when converting Python objects to FSharpArray.
/// When the input is already an FSharpArray, we borrow it directly (zero-copy).
/// When the input is something else (list, iterable, etc.), we create a new owned array.
///
/// The `Deref` implementation allows transparent access to `&FSharpArray` methods.
/// Use `into_owned()` only when mutation or ownership transfer is required.
enum ArrayRef<'py> {
/// Borrowed reference to an existing Python FSharpArray (no clone)
Borrowed(PyRef<'py, FSharpArray>),
/// Newly created array that we own
Owned(FSharpArray),
}
impl std::ops::Deref for ArrayRef<'_> {
type Target = FSharpArray;
fn deref(&self) -> &Self::Target {
match self {
ArrayRef::Borrowed(r) => r,
ArrayRef::Owned(a) => a,
}
}
}
impl ArrayRef<'_> {
/// Convert to an owned FSharpArray.
///
/// - If borrowed: clones the array data (unavoidable when ownership is needed)
/// - If owned: moves without copying
///
/// Use this only when you need ownership, e.g., for mutation or storing in collections.
fn into_owned(self) -> FSharpArray {
match self {
ArrayRef::Borrowed(r) => r.clone(),
ArrayRef::Owned(a) => a,
}
}
}
/// Converts a Python object to an FSharpArray reference.
///
/// # Performance Optimization
///
/// This function returns `ArrayRef` instead of `FSharpArray` to avoid cloning
/// when the input is already an FSharpArray. This is a common case in F# code
/// where arrays are passed through multiple function calls.
///
/// - If `ob` is an FSharpArray: returns a borrowed reference (O(1), no allocation)
/// - If `ob` is None: returns an empty array
/// - If `ob` is iterable (Python __iter__ or F# IEnumerable): converts to a new array
/// - Otherwise: wraps as a singleton array
fn ensure_array<'py>(py: Python<'py>, ob: &'py Bound<'py, PyAny>) -> PyResult<ArrayRef<'py>> {
// If it's already a FSharpArray, borrow it (no clone)
if let Ok(array) = ob.cast::<FSharpArray>() {
return Ok(ArrayRef::Borrowed(array.borrow()));
}
// If the object is None (null), create an empty array
if ob.is_none() {
return Ok(ArrayRef::Owned(FSharpArray::new(py, None, None)?));
}
// Check if the object is iterable (Python protocol)
if let Ok(iter) = ob.try_iter() {
// Convert iterable directly to FSharpArray
return Ok(ArrayRef::Owned(FSharpArray::new(py, Some(iter.as_any()), None)?));
}
// Check if the object implements IEnumerable (F# protocol with GetEnumerator)
if ob.hasattr("GetEnumerator").unwrap_or(false) {
// Pass to FSharpArray::new which handles IEnumerable
return Ok(ArrayRef::Owned(FSharpArray::new(py, Some(ob), None)?));
}
// If it's a single item, create a singleton array
let singleton_list = PyList::new(py, [ob])?;
Ok(ArrayRef::Owned(FSharpArray::new(py, Some(&singleton_list), None)?))
}
fn ensure_equal_length_arrays<'py>(
py: Python<'py>,
array1: &'py Bound<'py, PyAny>,
array2: &'py Bound<'py, PyAny>,
) -> PyResult<(ArrayRef<'py>, ArrayRef<'py>)> {
let array1 = ensure_array(py, array1)?;
let array2 = ensure_array(py, array2)?;
if array1.storage.len() != array2.storage.len() {
return Err(PyErr::new::<exceptions::PyValueError, _>(
"Arrays had different lengths",
));
}
Ok((array1, array2))
}
#[pymethods]
impl FSharpArray {
#[new]
#[pyo3(signature = (elements=None, array_type=None))]
pub fn new(
_py: Python<'_>,
elements: Option<&Bound<'_, PyAny>>,
array_type: Option<&str>,
) -> PyResult<Self> {
let nominal_type = array_type
.map(ArrayType::from_str)
.unwrap_or(ArrayType::Generic);
// Handle empty array case early
let Some(elements) = elements else {
return Ok(FSharpArray {
storage: NativeArray::create_empty_storage(&nominal_type),
});
};
// Try to extract as typed arrays first - if any succeed, return immediately
let typed_array = match &nominal_type {
ArrayType::Int8 => {
try_extract_array!(elements, _py, Int8, Int8, i8)
}
ArrayType::UInt8 => {
try_extract_array!(elements, _py, UInt8, UInt8, u8)
}
ArrayType::Int16 => {
try_extract_array!(elements, _py, Int16, Int16, i16)
}
ArrayType::UInt16 => {
try_extract_array!(elements, _py, UInt16, UInt16, u16)
}
ArrayType::Int32 => {
try_extract_array!(elements, _py, Int32, Int32, i32)
}
ArrayType::UInt32 => {
try_extract_array!(elements, _py, UInt32, UInt32, u32)
}
ArrayType::Int64 => {
try_extract_array!(elements, _py, Int64, Int64, i64)
}
ArrayType::UInt64 => {
try_extract_array!(elements, _py, UInt64, UInt64, u64)
}
ArrayType::Float32 => {
try_extract_array!(elements, _py, Float32, Float32, f32)
}
ArrayType::Float64 => {
try_extract_array!(elements, _py, Float64, Float64, f64)
}
ArrayType::Bool => {
try_extract_array!(elements, _py, Bool, bool, bool)
}
_ => None,
};
// If typed extraction succeeded, return it
if let Some(array) = typed_array {
return Ok(array);
}
// Fallback to PyObject storage if type extraction fails.
// This allows for generic or mixed-type arrays, at the cost of dynamic dispatch and locking.
// Arc<Mutex<...>> is used for thread safety and Python interop.
let len = elements.len().unwrap_or(0);
let mut vec = Vec::with_capacity(len);
for_each_element(elements, |item| {
vec.push(item.unbind());
Ok(())
})?;
Ok(FSharpArray {
storage: NativeArray::PyObject(Arc::new(Mutex::new(vec))),
})
}
#[classmethod]
pub fn __class_getitem__(
_cls: &Bound<'_, PyType>,
item: &Bound<'_, PyAny>,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
// Get type name - either from string or from type.__name__
let type_name: Option<String> = if let Ok(s) = item.extract::<String>() {
Some(s)
} else if let Ok(py_type) = item.cast::<PyType>() {
py_type.getattr("__name__")?.extract()?
} else {
None
};
// Match on the type name
let array_class = match type_name.map(|s| s.to_lowercase()).as_deref() {
Some("int8") | Some("sbyte") => Int8Array::type_object(py),
Some("uint8") | Some("byte") => UInt8Array::type_object(py),
Some("int16") => Int16Array::type_object(py),
Some("uint16") => UInt16Array::type_object(py),
Some("int32") => Int32Array::type_object(py),
Some("uint32") => UInt32Array::type_object(py),
Some("int64") => Int64Array::type_object(py),
Some("uint64") => UInt64Array::type_object(py),
Some("float32") => Float32Array::type_object(py),
Some("float64") => Float64Array::type_object(py),
Some("bool") => BoolArray::type_object(py),
_ => GenericArray::type_object(py),
};
Ok(array_class.into_pyobject(py)?.into())
}
/// Creates an array whose elements are all initially the given value.
#[staticmethod]
pub fn create(
_py: Python<'_>,
count: usize,
value: &Bound<'_, PyAny>,
) -> PyResult<FSharpArray> {
// Attempt to create specialized arrays based on value type
if let Ok(int8) = value.extract::<Int8>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *int8);
return Ok(FSharpArray {
storage: NativeArray::Int8(vec),
});
} else if let Ok(uint8) = value.extract::<UInt8>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *uint8);
return Ok(FSharpArray {
storage: NativeArray::UInt8(vec),
});
} else if let Ok(int16) = value.extract::<Int16>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *int16);
return Ok(FSharpArray {
storage: NativeArray::Int16(vec),
});
} else if let Ok(uint16) = value.extract::<UInt16>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *uint16);
return Ok(FSharpArray {
storage: NativeArray::UInt16(vec),
});
} else if let Ok(int32) = value.extract::<Int32>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *int32);
return Ok(FSharpArray {
storage: NativeArray::Int32(vec),
});
} else if let Ok(uint32) = value.extract::<UInt32>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *uint32);
return Ok(FSharpArray {
storage: NativeArray::UInt32(vec),
});
} else if let Ok(int64) = value.extract::<Int64>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *int64);
return Ok(FSharpArray {
storage: NativeArray::Int64(vec),
});
} else if let Ok(uint64) = value.extract::<UInt64>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *uint64);
return Ok(FSharpArray {
storage: NativeArray::UInt64(vec),
});
} else if let Ok(float32) = value.extract::<Float32>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *float32);
return Ok(FSharpArray {
storage: NativeArray::Float32(vec),
});
} else if let Ok(float64) = value.extract::<Float64>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, *float64);
return Ok(FSharpArray {
storage: NativeArray::Float64(vec),
});
} else if let Ok(bool_val) = value.extract::<bool>() {
let mut vec = Vec::with_capacity(count);
vec.resize(count, bool_val);
return Ok(FSharpArray {
storage: NativeArray::Bool(vec),
});
}
// Fallback to generic PyObject storage
let mut vec = Vec::with_capacity(count);
for _ in 0..count {
vec.push(value.clone().into());
}
Ok(FSharpArray {
storage: NativeArray::PyObject(Arc::new(Mutex::new(vec))),
})
}
pub fn __richcmp__<'py>(
&self,
other: &Bound<'_, PyAny>,
op: CompareOp,
py: Python<'py>,
) -> PyResult<Borrowed<'py, 'py, PyAny>> {
// First check if other is a FSharpArray
if let Ok(other_array) = other.extract::<PyRef<'_, FSharpArray>>() {
match op {
CompareOp::Eq => {
let result = self.storage.equals(&other_array.storage, py);
Ok(PyBool::new(py, result).into_any())
}
CompareOp::Ne => {
// For inequality, negate the equality result
let result = self.storage.equals(&other_array.storage, py);
Ok(PyBool::new(py, !result).into_any())
}
CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
// Create a default comparer using direct Python comparison
let default_comparer = DefaultComparer::new()?.into_pyobject(py)?;
let comparison_result =
self.compare_with(py, &default_comparer, &other_array)?;
let result = match op {
CompareOp::Lt => comparison_result < 0,
CompareOp::Le => comparison_result <= 0,
CompareOp::Gt => comparison_result > 0,
CompareOp::Ge => comparison_result >= 0,
_ => unreachable!(),
};
Ok(PyBool::new(py, result).into_any())
}
}
} else {
// If other is not a FSharpArray, return NotImplemented
Ok(PyNotImplemented::get(py).into_any())
}
}
pub fn __add__(&self, other: &Bound<'_, PyAny>, py: Python<'_>) -> PyResult<Py<PyAny>> {
// Use append to implement array concatenation
let result = self.append(py, other, None)?;
Ok(result.into_pyobject(py)?.into())
}
#[staticmethod]
pub fn initialize(
py: Python<'_>,
count: usize,
initializer: &Bound<'_, PyAny>,
cons: Option<&Bound<'_, PyAny>>,
) -> PyResult<FSharpArray> {
if count == 0 {
return FSharpArray::empty(py, cons);
}
// Create the builder for results
let fs_cons = FSharpCons::extract(cons, &ArrayType::Generic);
let mut results = fs_cons.create(count);
// Initialize each element using the provided initializer function
for i in 0..count {
let item = initializer.call1((i,))?;
results.push_value(&item, py)?;
}
// Construct the result array
Ok(FSharpArray { storage: results })
}
#[staticmethod]
#[pyo3(signature = (value, cons=None))]
pub fn singleton(
py: Python<'_>,
value: &Bound<'_, PyAny>,
cons: Option<&Bound<'_, PyAny>>,
) -> PyResult<FSharpArray> {
// Determine the type from constructor
let fs_cons = FSharpCons::extract(cons, &ArrayType::Generic);
let mut builder = fs_cons.create(1);
// Set the single element
builder.push_value(value, py)?;
let array = FSharpArray { storage: builder };
Ok(array)
}
#[inline]
pub fn __len__(&self) -> usize {
self.storage.len()
}
/// Returns the length of the array as Int32 (F# compatible).
///
/// This property provides F# interop compatibility by returning the array length
/// as an Int32 instead of Python's native int. In F#, Array.length returns int32.
#[getter]
pub fn length(&self) -> Int32 {
Int32(self.storage.len() as i32)
}
/// Returns an iterator over the array elements.
///
/// # Performance Optimization
///
/// This method takes `PyRef<'_, Self>` instead of `&self` to access the underlying
/// Python object reference. This allows us to increment the reference count via
/// `Py::from_borrowed_ptr` instead of cloning the entire array data.
///
/// The iterator holds a `Py<FSharpArray>` which keeps the array alive during iteration.
/// This is O(1) (just a refcount increment) vs O(n) for cloning the array contents.
///
/// # Safety
///
/// The `unsafe` block is safe because:
/// - `slf.as_ptr()` returns a valid pointer to the Python object
/// - `from_borrowed_ptr` increments the refcount, ensuring the object stays alive
/// - The `PyRef` guarantees we have a valid borrow of the object
pub fn __iter__(slf: PyRef<'_, Self>, py: Python<'_>) -> PyResult<Py<PyAny>> {
let len = slf.storage.len();
// SAFETY: slf.as_ptr() is valid and from_borrowed_ptr increments refcount
let array: Py<FSharpArray> = unsafe {
Bound::from_borrowed_ptr(py, slf.as_ptr())
.cast_into_unchecked::<FSharpArray>()
}
.unbind();
let iter = FSharpArrayIter {
array,
index: 0,
len,
};
iter.into_py_any(py)
}
/// Returns an IEnumerator for this array.
/// Implements the .NET IEnumerable.GetEnumerator() interface.
#[allow(non_snake_case)]
#[pyo3(signature = (_unit=None))]
pub fn GetEnumerator(slf: PyRef<'_, Self>, py: Python<'_>, _unit: Option<&Bound<'_, PyAny>>) -> PyResult<Py<PyAny>> {
let len = slf.storage.len();
// SAFETY: slf.as_ptr() is valid and from_borrowed_ptr increments refcount
let array: Py<FSharpArray> = unsafe {
Bound::from_borrowed_ptr(py, slf.as_ptr())
.cast_into_unchecked::<FSharpArray>()
}
.unbind();
let enumerator = FSharpArrayEnumerator {
array,
index: -1, // Before first element
len,
};
enumerator.into_py_any(py)
}
/// Pydantic v2 integration for schema generation.
///
/// This method is called by Pydantic when building a model that uses FSharpArray.
/// It returns a pydantic-core schema that enables:
/// - Validation of input values (any iterable)
/// - Serialization to JSON-compatible lists
/// - JSON Schema generation for OpenAPI documentation
///
/// The pydantic_core module is imported lazily - pydantic is only required
/// if this method is actually called (i.e., when used in a Pydantic model).
#[classmethod]
#[pyo3(name = "__get_pydantic_core_schema__")]
fn get_pydantic_core_schema(
cls: &Bound<'_, PyType>,
_source_type: &Bound<'_, PyAny>,
_handler: &Bound<'_, PyAny>,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
// Lazy import of pydantic_core - only fails if pydantic is not installed
// AND this type is used in a Pydantic model
let core_schema = py.import("pydantic_core")?.getattr("core_schema")?;
// Create a validator function that wraps the constructor
let validator_fn = cls.getattr("_pydantic_validator")?;
// Create a serializer function that converts to list
let serializer_fn = cls.getattr("_pydantic_serializer")?;
// Build the serialization schema
let ser_schema =
core_schema.call_method1("plain_serializer_function_ser_schema", (serializer_fn,))?;
// Create a list schema as the base - this enables JSON Schema generation
let list_schema = core_schema.call_method0("list_schema")?;
// Wrap with validator function, keeping list_schema for JSON Schema
let validator_kwargs = pyo3::types::PyDict::new(py);
validator_kwargs.set_item("serialization", ser_schema)?;
let validator_schema = core_schema.call_method(
"no_info_after_validator_function",
(validator_fn, list_schema),
Some(&validator_kwargs),
)?;
Ok(validator_schema.unbind())
}
/// Pydantic validator function.
///
/// Called by Pydantic during validation to convert input values to FSharpArray.
/// Accepts any iterable.
#[staticmethod]
#[pyo3(name = "_pydantic_validator")]
fn pydantic_validator(py: Python<'_>, value: &Bound<'_, PyAny>) -> PyResult<Self> {
// If already a FSharpArray, return a clone
if let Ok(array) = value.extract::<PyRef<'_, FSharpArray>>() {
return Ok(array.clone());
}
// Otherwise create from iterable
FSharpArray::new(py, Some(value), None)
}
/// Pydantic serializer function.
///
/// Called by Pydantic during serialization to convert FSharpArray to a
/// JSON-compatible list.
#[staticmethod]
#[pyo3(name = "_pydantic_serializer")]
fn pydantic_serializer(py: Python<'_>, instance: &Self) -> PyResult<Py<PyAny>> {
// Convert FSharpArray to a Python list for JSON serialization
let len = instance.storage.len();
let list = PyList::empty(py);
for i in 0..len {
let item = instance.storage.get(py, i)?;
list.append(item)?;
}
Ok(list.into())
}
/// Returns the raw bytes of the array's underlying storage.
///
/// For numeric types (Int8, UInt8, Int16, etc.), this returns the raw memory
/// representation of the array elements as bytes. The byte order is native
/// (platform-dependent): little-endian on x86/x64/ARM, big-endian on some
/// older architectures.
///
/// For Int8/UInt8 arrays, the result is a direct byte representation.
/// For larger types (Int16, Int32, Float64, etc.), each element occupies
/// multiple bytes in native byte order.
///
/// Returns NotImplemented for String and PyObject arrays.
pub fn __bytes__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
match &self.storage {
// For UInt8/Int8 arrays, we can create bytes directly
NativeArray::UInt8(vec) => {
let bytes = PyBytes::new(py, vec.as_slice());
Ok(bytes.into())
}
NativeArray::Int8(vec) => {
// Convert i8 slice to u8 slice with unsafe transmute
// This is safe because we're just reinterpreting the bits
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(vec.as_ptr() as *const u8, vec.len())
});
Ok(bytes.into())
}
// For other numeric types, create a bytearray from their raw memory
NativeArray::Int16(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<i16>(),
)
});
Ok(bytes.into())
}
NativeArray::UInt16(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<u16>(),
)
});
Ok(bytes.into())
}
// Similar patterns for other numeric types
NativeArray::Int32(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<i32>(),
)
});
Ok(bytes.into())
}
NativeArray::UInt32(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<u32>(),
)
});
Ok(bytes.into())
}
NativeArray::Int64(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<i64>(),
)
});
Ok(bytes.into())
}
NativeArray::UInt64(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<u64>(),
)
});
Ok(bytes.into())
}
NativeArray::Float32(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<f32>(),
)
});
Ok(bytes.into())
}
NativeArray::Float64(vec) => {
let bytes = PyBytes::new(py, unsafe {
std::slice::from_raw_parts(
vec.as_ptr() as *const u8,
vec.len() * std::mem::size_of::<f64>(),
)
});
Ok(bytes.into())
}
// For non-numeric types, return NotImplemented
_ => Ok(py.NotImplemented()),
}
}
// Separate function to handle slice access
fn get_item_slice(
&self,
slice: &Bound<'_, pyo3::types::PySlice>,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
let len = self.storage.len();
let indices = slice.indices(len as isize)?;
let start = indices.start as usize;
let stop = indices.stop as usize;
let step = indices.step;
// If step is not 1, we need to handle it differently
if step != 1 {
// Calculate the size of the resulting array
let mut size = 0;
let mut i = indices.start;
while (step > 0 && i < indices.stop) || (step < 0 && i > indices.stop) {
size += 1;
i += step;
}
// Create a new array with the same type
let fs_cons = FSharpCons::new(
&self
.storage
.type_name()
.into_pyobject(py)?
.extract::<String>()?,
)?;
let mut result = fs_cons.allocate(py, size)?;
// Fill the result array with sliced elements
let mut result_idx = 0;
i = indices.start;
while (step > 0 && i < indices.stop) || (step < 0 && i > indices.stop) {
let item = self.get_item_at_index(i, py)?;
result.__setitem__(result_idx, item.bind(py), py)?;
result_idx += 1;
i += step;
}
return Ok(Py::new(py, result)?.into());
}
// For step=1, use set_slice
// Create a new array of the appropriate size
let slice_len = if step > 0 {
stop - start
} else {
// For negative steps, the calculation is different
start - stop
};
// println!("Slice length: {:?}", slice_len);
// println!("Nominal type: {:?}", self.nominal_type);
let mut builder = NativeArray::new(self.storage.get_type(), Some(slice_len));
// Add each element from the slice range
for i in 0..slice_len {
builder.push_from_storage(&self.storage, start + i, py);
}
// Create the result array
let result = FSharpArray { storage: builder };
Ok(Py::new(py, result)?.into())
}
pub fn __getitem__(&self, idx: &Bound<'_, PyAny>, py: Python<'_>) -> PyResult<Py<PyAny>> {
// Try to downcast to a slice first
if let Ok(slice) = idx.cast::<pyo3::types::PySlice>() {
// println!("Slice: {:?}", slice);
self.get_item_slice(slice, py)
}
// Then try to extract as an integer
else if let Ok(i) = idx.extract::<isize>() {
// println!("Integer: {:?}", i);
self.get_item_at_index(i, py)
}
// If neither works, raise TypeError
else {
Err(PyErr::new::<exceptions::PyTypeError, _>(
"indices must be integers or slices",
))
}
}
// Helper method to get an item at a specific index
#[inline]
fn get_item_at_index(&self, idx: isize, py: Python<'_>) -> PyResult<Py<PyAny>> {
let len = self.storage.len();
let idx = if idx < 0 { len as isize + idx } else { idx };
if idx < 0 || idx as usize >= len {
return Err(PyErr::new::<exceptions::PyIndexError, _>(
"index out of range",
));
}
self.storage.get(py, idx as usize)
}
pub fn __setitem__(
&mut self,
idx: isize,
value: &Bound<'_, PyAny>,
_py: Python<'_>,
) -> PyResult<()> {
let len = self.storage.len();
let idx = if idx < 0 { len as isize + idx } else { idx };
if idx < 0 || idx as usize >= len {
return Err(PyErr::new::<exceptions::PyIndexError, _>(
"index out of range",
));
}
match &mut self.storage {
NativeArray::Int8(vec) => {
if let Ok(i_val) = value.extract::<i8>() {
vec[idx as usize] = i_val;
return Ok(());
}
}
NativeArray::UInt8(vec) => {
if let Ok(u_val) = value.extract::<u8>() {
vec[idx as usize] = u_val;
return Ok(());
}
}
NativeArray::Int16(vec) => {
if let Ok(i_val) = value.extract::<i16>() {
vec[idx as usize] = i_val;
return Ok(());
}
}
NativeArray::UInt16(vec) => {
if let Ok(u_val) = value.extract::<u16>() {
vec[idx as usize] = u_val;
return Ok(());
}
}
NativeArray::Int32(vec) => {
if let Ok(i_val) = value.extract::<i32>() {
vec[idx as usize] = i_val;
return Ok(());
}
}
NativeArray::UInt32(vec) => {
if let Ok(u_val) = value.extract::<u32>() {
vec[idx as usize] = u_val;
return Ok(());
}
}
NativeArray::Int64(vec) => {
if let Ok(i_val) = value.extract::<i64>() {
vec[idx as usize] = i_val;
return Ok(());
}
}
NativeArray::UInt64(vec) => {
// Fast path: Try to extract directly as u64
if let Ok(u_val) = value.extract::<u64>() {
vec[idx as usize] = u_val;
return Ok(());
}
// Fast path: Try to extract as UInt64 wrapper
if let Ok(uint64_value) = value.extract::<UInt64>() {
vec[idx as usize] = *uint64_value;
return Ok(());
}
// Fast path: Try to extract as Float32/Float64 and convert
if let Ok(f32_val) = value.extract::<crate::floats::Float32>() {
vec[idx as usize] = f32_val.0 as u64;
return Ok(());
}
if let Ok(f64_val) = value.extract::<crate::floats::Float64>() {
vec[idx as usize] = f64_val.0 as u64;
return Ok(());
}
// Fast path: Try to extract as other integer types
if let Ok(i_val) = value.extract::<i64>() {
vec[idx as usize] = i_val as u64;
return Ok(());
}
// Fallback to full conversion
let uint64_value: UInt64 = UInt64::new(value)?;
vec[idx as usize] = *uint64_value;
}
NativeArray::Float32(vec) => {
// Fast path: Try to extract as Float32 wrapper first
if let Ok(float32_value) = value.extract::<Float32>() {
vec[idx as usize] = *float32_value;
return Ok(());
}
// Fast path: Try to extract directly as f32
if let Ok(f_val) = value.extract::<f32>() {
vec[idx as usize] = f_val;
return Ok(());
}
// Fallback to full conversion
let float32_value = value.extract::<Float32>()?;
vec[idx as usize] = *float32_value;
}
NativeArray::Float64(vec) => {
// Fast path: Try to extract as Float64 wrapper first
if let Ok(float64_value) = value.extract::<Float64>() {
vec[idx as usize] = *float64_value;
return Ok(());
}
// Fast path: Try to extract directly as f64
if let Ok(f_val) = value.extract::<f64>() {
vec[idx as usize] = f_val;
return Ok(());
}
// Fallback to full conversion
let float64_value = value.extract::<Float64>()?;
vec[idx as usize] = *float64_value;
}
NativeArray::Bool(vec) => {
vec[idx as usize] = value.extract()?;
}
NativeArray::PyObject(arc_mutex_vec) => {
let mut vec = arc_mutex_vec.lock().unwrap(); // Acquire the lock
vec[idx as usize] = value.clone().into();
}
}
Ok(())
}
pub fn __delitem__(&mut self, idx: isize, _py: Python<'_>) -> PyResult<()> {
let len = self.storage.len();
let idx = if idx < 0 { len as isize + idx } else { idx };
if idx < 0 || idx as usize >= len {
return Err(PyErr::new::<exceptions::PyIndexError, _>(
"index out of range",
));
}
self.storage.remove_at_index(idx as usize);
Ok(())
}
pub fn insert(&mut self, idx: isize, value: &Bound<'_, PyAny>, py: Python<'_>) -> PyResult<()> {
let len = self.storage.len();
let idx = if idx < 0 { len as isize + idx } else { idx };
if idx < 0 || idx as usize > len {
return Err(PyErr::new::<exceptions::PyIndexError, _>(
"index out of range",
));
}
self.storage.insert(idx as usize, value, py)
}
#[staticmethod]
#[pyo3(signature = (cons=None))]
pub fn empty(py: Python<'_>, cons: Option<&Bound<'_, PyAny>>) -> PyResult<FSharpArray> {
// Determine the type from constructor
let fs_cons = FSharpCons::extract(cons, &ArrayType::Generic);
// Create an empty array with this type
let array = fs_cons.allocate(py, 0)?;
Ok(array)
}
pub fn remove_at(&mut self, py: Python<'_>, index: isize) -> PyResult<FSharpArray> {
let len = self.storage.len();
if index < 0 || index as usize >= len {
return Err(PyErr::new::<exceptions::PyIndexError, _>(
"index out of range",
));