forked from uiua-lang/uiua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.rs
More file actions
1614 lines (1538 loc) · 48 KB
/
array.rs
File metadata and controls
1614 lines (1538 loc) · 48 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 std::{
any::TypeId,
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
sync::Arc,
};
use bitflags::bitflags;
use bytemuck::must_cast;
use ecow::{EcoString, EcoVec};
use serde::{de::DeserializeOwned, *};
use crate::{
algorithm::map::{MapKeys, EMPTY_NAN, TOMBSTONE_NAN},
cowslice::{cowslice, CowSlice},
fill::Fill,
grid_fmt::{ElemAlign, GridFmt},
Boxed, Complex, ExactDoubleIterator, HandleKind, Shape, Value,
};
/// Uiua's array type
#[derive(Clone, Serialize, Deserialize)]
#[serde(
from = "ArrayRep<T>",
into = "ArrayRep<T>",
bound(
serialize = "T: ArrayValueSer + Serialize",
deserialize = "T: ArrayValueSer + Deserialize<'de>"
)
)]
#[repr(C)]
pub struct Array<T> {
pub(crate) shape: Shape,
pub(crate) data: CowSlice<T>,
pub(crate) meta: Option<Arc<ArrayMeta>>,
}
/// Non-shape metadata for an array
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArrayMeta {
/// The label
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<EcoString>,
/// Flags for the array
#[serde(default, skip_serializing_if = "ArrayFlags::is_empty")]
pub flags: ArrayFlags,
/// The keys of a map array
#[serde(default, skip_serializing_if = "Option::is_none")]
pub map_keys: Option<MapKeys>,
/// The pointer value for FFI
#[serde(skip)]
pub pointer: Option<MetaPtr>,
/// The kind of system handle
#[serde(skip)]
pub handle_kind: Option<HandleKind>,
}
impl ArrayMeta {
/// Take the persistent metadata
pub fn take_per_meta(&mut self) -> PersistentMeta {
let label = self.label.take();
let map_keys = self.map_keys.take();
PersistentMeta { label, map_keys }
}
/// Set the persistent metadata
pub fn set_per_meta(&mut self, per_meta: PersistentMeta) {
self.label = per_meta.label;
self.map_keys = per_meta.map_keys;
}
/// Reset the flags
pub fn reset_flags(&mut self) {
self.flags.reset();
}
/// Combine the metadata with another
pub fn combine(&mut self, other: &Self) {
self.flags &= other.flags;
self.map_keys = None;
if self.handle_kind != other.handle_kind {
self.handle_kind = None;
}
}
/// Check if the metadata is the default
pub fn is_default(&self) -> bool {
self.label.is_none()
&& self.map_keys.is_none()
&& self.handle_kind.is_none()
&& self.pointer.is_none()
&& self.flags.is_empty()
}
}
/// Array pointer metadata
#[derive(Debug, Clone, Copy)]
pub struct MetaPtr {
/// The pointer value
pub ptr: usize,
/// Whether the pointer should prevent the array's value from being shown
pub raw: bool,
}
impl MetaPtr {
/// Get a null metadata pointer
pub const fn null() -> Self {
Self { ptr: 0, raw: true }
}
/// Create a new metadata pointer
pub fn new<T: ?Sized>(ptr: *const T, raw: bool) -> Self {
Self {
ptr: ptr as *const () as usize,
raw,
}
}
/// Get the pointer as a raw pointer
pub fn get<T>(&self) -> *const T {
self.ptr as *const T
}
/// Get the pointer as a raw pointer
pub fn get_mut<T>(&self) -> *mut T {
self.ptr as *mut T
}
}
impl PartialEq for MetaPtr {
fn eq(&self, other: &Self) -> bool {
self.ptr == other.ptr
}
}
impl Eq for MetaPtr {}
bitflags! {
/// Flags for an array
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ArrayFlags: u8 {
/// No flags
const NONE = 0;
/// The array is boolean
const BOOLEAN = 1;
/// The array was *created from* a boolean
const BOOLEAN_LITERAL = 2;
}
}
impl ArrayFlags {
/// Check if the array is boolean
pub fn is_boolean(self) -> bool {
self.contains(Self::BOOLEAN)
}
/// Reset all flags
pub fn reset(&mut self) {
*self = Self::NONE;
}
}
/// Default metadata for an array
pub static DEFAULT_META: ArrayMeta = ArrayMeta {
label: None,
flags: ArrayFlags::NONE,
map_keys: None,
pointer: None,
handle_kind: None,
};
/// Array metadata that can be persisted across operations
#[derive(Clone, Default)]
pub struct PersistentMeta {
pub(crate) label: Option<EcoString>,
pub(crate) map_keys: Option<MapKeys>,
}
impl PersistentMeta {
/// XOR this metadata with another
pub fn xor(self, other: Self) -> Self {
Self {
label: self.label.xor(other.label),
map_keys: self.map_keys.xor(other.map_keys),
}
}
/// XOR several metadatas
pub fn xor_all(metas: impl IntoIterator<Item = Self>) -> Self {
let mut label = None;
let mut map_keys = None;
let mut set_label = false;
let mut set_map_keys = false;
for meta in metas {
if let Some(l) = meta.label {
if set_label {
label = None;
} else {
label = Some(l);
set_label = true;
}
}
if let Some(keys) = meta.map_keys {
if set_map_keys {
map_keys = None;
} else {
map_keys = Some(keys);
set_map_keys = true;
}
}
}
Self { label, map_keys }
}
}
impl<T: ArrayValue> Default for Array<T> {
fn default() -> Self {
Self {
shape: 0.into(),
data: CowSlice::new(),
meta: None,
}
}
}
impl<T: ArrayValue> fmt::Debug for Array<T>
where
Array<T>: GridFmt,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.grid_string(true))
}
}
impl<T: ArrayValue> fmt::Display for Array<T>
where
Array<T>: GridFmt,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.rank() {
0 => write!(f, "{}", self.data[0]),
1 => {
let (start, end) = T::format_delims();
write!(f, "{}", start)?;
for (i, x) in self.data.iter().enumerate() {
if i > 0 {
write!(f, "{}", T::format_sep())?;
}
write!(f, "{x}")?;
}
write!(f, "{}", end)
}
_ => {
write!(f, "\n{}", self.grid_string(false))
}
}
}
}
#[track_caller]
#[inline(always)]
pub(crate) fn validate_shape(shape: &[usize], len: usize) {
let elems = if shape.contains(&0) {
0
} else {
shape.iter().product()
};
debug_assert_eq!(
elems, len,
"shape {shape:?} does not match data length {}",
len
);
}
impl<T> Array<T> {
#[track_caller]
/// Create an array from a shape and data
///
/// # Panics
/// Panics in debug mode if the shape does not match the data length
pub fn new(shape: impl Into<Shape>, data: impl Into<CowSlice<T>>) -> Self {
let shape = shape.into();
let data = data.into();
validate_shape(&shape, data.len());
Self {
shape,
data,
meta: None,
}
}
#[track_caller]
#[inline(always)]
/// Debug-only function to validate that the shape matches the data length
pub(crate) fn validate_shape(&self) {
validate_shape(&self.shape, self.data.len());
}
/// Get the number of rows in the array
pub fn row_count(&self) -> usize {
self.shape.first().copied().unwrap_or(1)
}
/// Get the number of elements in the array
pub fn element_count(&self) -> usize {
self.data.len()
}
/// Get the number of elements in a row
pub fn row_len(&self) -> usize {
self.shape.iter().skip(1).product()
}
/// Get the rank of the array
pub fn rank(&self) -> usize {
self.shape.len()
}
/// Get the shape of the array
pub fn shape(&self) -> &Shape {
&self.shape
}
/// Get a mutable reference to the shape of the array
pub fn shape_mut(&mut self) -> &mut Shape {
&mut self.shape
}
/// Iterate over the elements of the array
pub fn elements(&self) -> impl ExactDoubleIterator<Item = &T> {
self.data.iter()
}
/// Get the metadata of the array
pub fn meta(&self) -> &ArrayMeta {
self.meta.as_deref().unwrap_or(&DEFAULT_META)
}
pub(crate) fn meta_mut_impl(meta: &mut Option<Arc<ArrayMeta>>) -> &mut ArrayMeta {
let meta = meta.get_or_insert_with(Default::default);
Arc::make_mut(meta)
}
/// Get a mutable reference to the metadata of the array if it exists
pub fn get_meta_mut(&mut self) -> Option<&mut ArrayMeta> {
self.meta.as_mut().map(Arc::make_mut)
}
/// Get a mutable reference to the metadata of the array
pub fn meta_mut(&mut self) -> &mut ArrayMeta {
Self::meta_mut_impl(&mut self.meta)
}
/// Take the label from the metadata
pub fn take_label(&mut self) -> Option<EcoString> {
self.get_meta_mut().and_then(|meta| meta.label.take())
}
/// Take the map keys from the metadata
pub fn take_map_keys(&mut self) -> Option<MapKeys> {
self.get_meta_mut().and_then(|meta| meta.map_keys.take())
}
/// The the persistent metadata of the array
pub fn take_per_meta(&mut self) -> PersistentMeta {
self.get_meta_mut()
.map(ArrayMeta::take_per_meta)
.unwrap_or_default()
}
/// Set the map keys in the metadata
pub fn set_per_meta(&mut self, per_meta: PersistentMeta) {
if self.meta().map_keys.is_some() != per_meta.map_keys.is_some() {
self.meta_mut().map_keys = per_meta.map_keys;
}
if self.meta().label.is_some() != per_meta.label.is_some() {
self.meta_mut().label = per_meta.label;
}
}
/// Get a reference to the map keys
pub fn map_keys(&self) -> Option<&MapKeys> {
self.meta().map_keys.as_ref()
}
/// Get a mutable reference to the map keys
pub fn map_keys_mut(&mut self) -> Option<&mut MapKeys> {
self.get_meta_mut().and_then(|meta| meta.map_keys.as_mut())
}
/// Reset all metadata flags
pub fn reset_meta_flags(&mut self) {
self.get_meta_mut().map(ArrayMeta::reset_flags);
}
/// Get an iterator over the row slices of the array
pub fn row_slices(
&self,
) -> impl ExactSizeIterator<Item = &[T]> + DoubleEndedIterator + Clone + Send + Sync
where
T: Send + Sync,
{
(0..self.row_count()).map(move |row| self.row_slice(row))
}
/// Get a slice of a row
#[track_caller]
pub fn row_slice(&self, row: usize) -> &[T] {
let row_len = self.row_len();
&self.data[row * row_len..(row + 1) * row_len]
}
/// Combine the metadata of two arrays
///
/// This combines:
/// - flags
/// - map keys
/// - handle kind
///
/// Notably, this does not combine the label, as label
/// combination should be more nuanced.
pub fn combine_meta(&mut self, other: &ArrayMeta) {
if !(self.meta.is_none() && other.is_default()) {
self.meta_mut().combine(other);
}
}
}
impl<T: ArrayValue> Array<T> {
/// Create a scalar array
pub fn scalar(data: T) -> Self {
Self::new(Shape::SCALAR, cowslice![data])
}
/// Attempt to convert the array into a scalar
pub fn into_scalar(self) -> Result<T, Self> {
if self.shape.is_empty() {
Ok(self.data.into_iter().next().unwrap())
} else {
Err(self)
}
}
/// Attempt to get a reference to the scalar value
pub fn as_scalar(&self) -> Option<&T> {
if self.shape.is_empty() {
Some(&self.data[0])
} else {
None
}
}
/// Attempt to get a mutable reference to the scalar value
pub fn as_scalar_mut(&mut self) -> Option<&mut T> {
if self.shape.is_empty() {
Some(&mut self.data.as_mut_slice()[0])
} else {
None
}
}
/// Get an iterator over the row arrays of the array
pub fn rows(&self) -> impl ExactSizeIterator<Item = Self> + DoubleEndedIterator + '_ {
(0..self.row_count()).map(|row| self.row(row))
}
pub(crate) fn row_shaped_slice(&self, index: usize, row_shape: Shape) -> Self {
let row_len = row_shape.elements();
let start = index * row_len;
let end = start + row_len;
Self::new(row_shape, self.data.slice(start..end))
}
/// Get an iterator over the row arrays of the array that have the given shape
pub fn row_shaped_slices(
&self,
row_shape: Shape,
) -> impl ExactSizeIterator<Item = Self> + DoubleEndedIterator + '_ {
let row_len = row_shape.elements();
let row_count = self.element_count() / row_len;
(0..row_count).map(move |i| {
let start = i * row_len;
let end = start + row_len;
Self::new(row_shape.clone(), self.data.slice(start..end))
})
}
/// Get an iterator over the row arrays of the array that have the given shape
pub fn into_row_shaped_slices(self, row_shape: Shape) -> impl DoubleEndedIterator<Item = Self> {
let row_len = row_shape.elements();
let zero_count = if row_len == 0 { self.row_count() } else { 0 };
let row_sh = row_shape.clone();
let nonzero = self
.data
.into_slices(row_len)
.map(move |data| Self::new(row_sh.clone(), data));
let zero = (0..zero_count).map(move |_| Self::new(row_shape.clone(), CowSlice::new()));
nonzero.chain(zero)
}
/// Get a row array
#[track_caller]
pub fn row(&self, row: usize) -> Self {
if self.rank() == 0 {
let mut row = self.clone();
row.take_map_keys();
row.take_label();
return row;
}
let row_count = self.row_count();
if row >= row_count {
panic!("row index out of bounds: {} >= {}", row, row_count);
}
let row_len = self.row_len();
let start = row * row_len;
let end = start + row_len;
let mut row = Self::new(&self.shape[1..], self.data.slice(start..end));
if self.meta().flags != ArrayFlags::NONE {
row.meta_mut().flags = self.meta().flags;
}
row
}
#[track_caller]
pub(crate) fn depth_row(&self, depth: usize, row: usize) -> Self {
if self.rank() <= depth {
let mut row = self.clone();
row.take_map_keys();
row.take_label();
return row;
}
let row_count: usize = self.shape[..depth + 1].iter().product();
if row >= row_count {
panic!("row index out of bounds: {} >= {}", row, row_count);
}
let row_len: usize = self.shape[depth + 1..].iter().product();
let start = row * row_len;
let end = start + row_len;
Self::new(&self.shape[depth + 1..], self.data.slice(start..end))
}
#[track_caller]
/// Create an array that is a slice of this array's rows
///
/// Generally doesn't allocate
///
/// - `start` must be <= `end`
/// - `start` must be < `self.row_count()`
/// - `end` must be <= `self.row_count()`
pub fn slice_rows(&self, start: usize, end: usize) -> Self {
assert!(start <= end);
assert!(start < self.row_count());
assert!(end <= self.row_count());
let row_len = self.row_len();
let mut shape = self.shape.clone();
shape[0] = end - start;
let start = start * row_len;
let end = end * row_len;
Self::new(shape, self.data.slice(start..end))
}
/// Consume the array and get an iterator over its rows
pub fn into_rows(self) -> impl ExactSizeIterator<Item = Self> + DoubleEndedIterator {
(0..self.row_count()).map(move |i| self.row(i))
}
pub(crate) fn first_dim_zero(&self) -> Self {
if self.rank() == 0 {
return self.clone();
}
let mut shape = self.shape.clone();
shape[0] = 0;
Array::new(shape, CowSlice::new())
}
/// Get a pretty-printed string representing the array
///
/// This is what is printed by the `&s` function
pub fn show(&self) -> String {
self.grid_string(true)
}
pub(crate) fn pop_row(&mut self) -> Option<Self> {
if self.row_count() == 0 {
return None;
}
let data = self.data.split_off(self.data.len() - self.row_len());
self.shape[0] -= 1;
let shape: Shape = self.shape[1..].into();
self.validate_shape();
Some(Self::new(shape, data))
}
/// Get a mutable slice of a row
#[track_caller]
pub fn row_slice_mut(&mut self, row: usize) -> &mut [T] {
let row_len = self.row_len();
&mut self.data.as_mut_slice()[row * row_len..(row + 1) * row_len]
}
}
impl<T: Clone> Array<T> {
/// Convert the elements of the array
#[inline(always)]
pub fn convert<U>(self) -> Array<U>
where
T: Into<U> + 'static,
U: Clone + 'static,
{
if TypeId::of::<T>() == TypeId::of::<U>() {
unsafe { std::mem::transmute::<Array<T>, Array<U>>(self) }
} else {
self.convert_with(Into::into)
}
}
/// Convert the elements of the array with a function
pub fn convert_with<U: Clone>(self, f: impl FnMut(T) -> U) -> Array<U> {
Array {
shape: self.shape,
data: self.data.into_iter().map(f).collect(),
meta: self.meta,
}
}
/// Convert the elements of the array with a fallible function
pub fn try_convert_with<U: Clone, E>(
self,
f: impl FnMut(T) -> Result<U, E>,
) -> Result<Array<U>, E> {
Ok(Array {
shape: self.shape,
data: self.data.into_iter().map(f).collect::<Result<_, _>>()?,
meta: self.meta,
})
}
/// Convert the elements of the array without consuming it
pub fn convert_ref<U>(&self) -> Array<U>
where
T: Into<U>,
U: Clone,
{
self.convert_ref_with(Into::into)
}
/// Convert the elements of the array with a function without consuming it
pub fn convert_ref_with<U: Clone>(&self, f: impl FnMut(T) -> U) -> Array<U> {
Array {
shape: self.shape.clone(),
data: self.data.iter().cloned().map(f).collect(),
meta: self.meta.clone(),
}
}
}
impl Array<u8> {
pub(crate) fn json_bool(b: bool) -> Self {
let mut arr = Self::from(b);
arr.meta_mut().flags |= ArrayFlags::BOOLEAN_LITERAL;
arr
}
}
impl Array<Boxed> {
/// Attempt to unbox a scalar box array
pub fn into_unboxed(self) -> Result<Value, Self> {
match self.into_scalar() {
Ok(v) => Ok(v.0),
Err(a) => Err(a),
}
}
/// Attempt to unbox a scalar box array
pub fn as_unboxed(&self) -> Option<&Value> {
self.as_scalar().map(|v| &v.0)
}
/// Attempt to unbox a scalar box array
pub fn as_unboxed_mut(&mut self) -> Option<&mut Value> {
self.as_scalar_mut().map(|v| &mut v.0)
}
}
impl<T: ArrayValue + ArrayCmp<U>, U: ArrayValue> PartialEq<Array<U>> for Array<T> {
fn eq(&self, other: &Array<U>) -> bool {
if self.shape() != other.shape() {
return false;
}
if self.map_keys() != other.map_keys() {
return false;
}
self.data
.iter()
.zip(&other.data)
.all(|(a, b)| a.array_eq(b))
}
}
impl<T: ArrayValue> Eq for Array<T> {}
impl<T: ArrayValue + ArrayCmp<U>, U: ArrayValue> PartialOrd<Array<U>> for Array<T> {
fn partial_cmp(&self, other: &Array<U>) -> Option<Ordering> {
let rank_cmp = self.rank().cmp(&other.rank());
if rank_cmp != Ordering::Equal {
return Some(rank_cmp);
}
let cmp = self
.data
.iter()
.zip(&other.data)
.map(|(a, b)| a.array_cmp(b))
.find(|o| o != &Ordering::Equal)
.unwrap_or_else(|| self.shape.cmp(&other.shape));
Some(cmp)
}
}
impl<T: ArrayValue> Ord for Array<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl<T: ArrayValue> Hash for Array<T> {
fn hash<H: Hasher>(&self, hasher: &mut H) {
if let Some(keys) = self.map_keys() {
keys.hash(hasher);
}
T::TYPE_ID.hash(hasher);
if let Some(scalar) = self.as_scalar() {
if let Some(value) = scalar.nested_value() {
value.hash(hasher);
return;
}
}
self.shape.hash(hasher);
self.data.iter().for_each(|x| x.array_hash(hasher));
}
}
impl<T: ArrayValue> From<T> for Array<T> {
fn from(data: T) -> Self {
Self::scalar(data)
}
}
impl<T: ArrayValue> From<EcoVec<T>> for Array<T> {
fn from(data: EcoVec<T>) -> Self {
Self::new(data.len(), data)
}
}
impl<T: ArrayValue> From<CowSlice<T>> for Array<T> {
fn from(data: CowSlice<T>) -> Self {
Self::new(data.len(), data)
}
}
impl<'a, T: ArrayValue> From<&'a [T]> for Array<T> {
fn from(data: &'a [T]) -> Self {
Self::new(data.len(), data)
}
}
impl<T: ArrayValue> FromIterator<T> for Array<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self::from(iter.into_iter().collect::<CowSlice<T>>())
}
}
impl From<String> for Array<char> {
fn from(s: String) -> Self {
Self::new(s.len(), s.chars().collect::<CowSlice<_>>())
}
}
impl From<Vec<bool>> for Array<u8> {
fn from(data: Vec<bool>) -> Self {
Self::new(
data.len(),
data.into_iter().map(u8::from).collect::<CowSlice<_>>(),
)
}
}
impl From<bool> for Array<u8> {
fn from(data: bool) -> Self {
let mut arr = Self::new(Shape::SCALAR, cowslice![u8::from(data)]);
arr.meta_mut().flags |= ArrayFlags::BOOLEAN;
arr
}
}
impl From<Vec<usize>> for Array<f64> {
fn from(data: Vec<usize>) -> Self {
Self::new(
data.len(),
data.into_iter().map(|u| u as f64).collect::<CowSlice<_>>(),
)
}
}
impl FromIterator<String> for Array<Boxed> {
fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
Array::from(
iter.into_iter()
.map(Value::from)
.map(Boxed)
.collect::<CowSlice<_>>(),
)
}
}
impl<'a> FromIterator<&'a str> for Array<Boxed> {
fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
Array::from(
iter.into_iter()
.map(Value::from)
.map(Boxed)
.collect::<CowSlice<_>>(),
)
}
}
/// A trait for types that can be used as array elements
#[allow(unused_variables)]
pub trait ArrayValue:
Default + Clone + fmt::Debug + fmt::Display + GridFmt + ArrayCmp + Send + Sync + 'static
{
/// The type name
const NAME: &'static str;
/// A glyph indicating the type
const SYMBOL: char;
/// An ID for the type
const TYPE_ID: u8;
/// Get the scalar fill value from the environment
fn get_scalar_fill(fill: &Fill) -> Result<Self, &'static str>;
/// Get the array fill value from the environment
fn get_array_fill(fill: &Fill) -> Result<Array<Self>, &'static str>;
/// Hash the value
fn array_hash<H: Hasher>(&self, hasher: &mut H);
/// Get the proxy value
fn proxy() -> Self;
/// Delimiters for formatting
fn format_delims() -> (&'static str, &'static str) {
("[", "]")
}
/// Marker for empty lists in grid formatting
fn empty_list_inner() -> &'static str {
""
}
/// Separator for formatting
fn format_sep() -> &'static str {
" "
}
/// Delimiters for grid formatting
fn grid_fmt_delims(boxed: bool) -> (char, char) {
if boxed {
('⟦', '⟧')
} else {
('[', ']')
}
}
/// Whether to compress all items of a list when grid formatting
fn compress_list_grid() -> bool {
false
}
/// Get a nested value
fn nested_value(&self) -> Option<&Value> {
None
}
/// Check if this element has the wildcard value
fn has_wildcard(&self) -> bool {
false
}
/// Summarize the elements of an array of this type
fn summarize(elems: &[Self]) -> String {
String::new()
}
/// The minimum number of elements that require a summary
fn summary_min_elems() -> usize {
3600
}
/// How to align elements when formatting
fn alignment() -> ElemAlign {
ElemAlign::Left
}
/// How to determine the maximum width of a formatted column
fn max_col_width<'a>(rows: impl Iterator<Item = &'a [char]> + Clone) -> usize {
rows.map(|row| row.len()).max().unwrap_or(0)
}
}
// NOTE: must_cast to f64 only works if f64 and u64 have same endianness.
// This is true of all currently supported platforms for rust,
// but may not be true in general. Swap out for f64::from_bits when
// the MSRV passes 1.83 to ensure correctness on all future platforms.
/// A NaN value that always compares as equal
pub const WILDCARD_NAN: f64 = must_cast(0x7ff8_0000_0000_0000u64 | 0x0000_0000_0000_0003);
/// A character value used as a wildcard that will equal any character
pub const WILDCARD_CHAR: char = '\u{100000}';
/// Round to a number of significant decimal places
fn round_sig_dec(f: f64, n: i32) -> f64 {
if f.fract() == 0.0 || f.is_infinite() {
return f;
}
let mul = 10f64.powf(n as f64 - f.fract().abs().log10().ceil());
(f * mul).round() / mul
}
impl ArrayValue for f64 {
const NAME: &'static str = "number";
const SYMBOL: char = 'ℝ';
const TYPE_ID: u8 = 0;
fn get_scalar_fill(fill: &Fill) -> Result<Self, &'static str> {
fill.num_scalar()
}
fn get_array_fill(fill: &Fill) -> Result<Array<Self>, &'static str> {
fill.num_array()
}
fn array_hash<H: Hasher>(&self, hasher: &mut H) {
let v = if self.to_bits() == EMPTY_NAN.to_bits() {
EMPTY_NAN
} else if self.to_bits() == TOMBSTONE_NAN.to_bits() {
TOMBSTONE_NAN
} else if self.to_bits() == WILDCARD_NAN.to_bits() {
WILDCARD_NAN
} else if self.is_nan() {
f64::NAN
} else if *self == 0.0 && self.is_sign_negative() {
0.0
} else {
*self
};
v.to_bits().hash(hasher)
}
fn proxy() -> Self {
0.0
}
fn has_wildcard(&self) -> bool {
self.to_bits() == WILDCARD_NAN.to_bits()
}
fn summarize(elems: &[Self]) -> String {
if elems.is_empty() {
return String::new();
}
if elems.iter().all(|&n| n.is_nan()) {
return "all NaN".into();
}
let mut min = f64::NAN;
let mut max = f64::NAN;
let mut nan_count = elems.iter().take_while(|n| n.is_nan()).count();
let mut mean = 0.0;
let mut i = 0;
let mut inf_balance = 0i64;
for &elem in &elems[nan_count..] {
if elem.is_nan() {
nan_count += 1;
} else if elem.is_infinite() {
inf_balance += elem.is_sign_positive() as i64;
min = min.min(elem);
max = max.max(elem);
} else {
min = min.min(elem);
max = max.max(elem);
mean += (elem - mean) / (i + 1) as f64;
i += 1;
}
}
if inf_balance != 0 {
mean = inf_balance.signum() as f64 * f64::INFINITY;
}
if min == max {
format!("all {}", min.grid_string(false))
} else {
let mut s = format!(
"{}-{} μ{}",
round_sig_dec(min, 4).grid_string(false),
round_sig_dec(max, 4).grid_string(false),
round_sig_dec(mean, 4).grid_string(false)
);
if nan_count > 0 {
s.push_str(&format!(
" ({nan_count} NaN{})",
if nan_count > 1 { "s" } else { "" }
));
}
s
}
}
fn alignment() -> ElemAlign {
ElemAlign::DelimOrRight(".")
}
fn max_col_width<'a>(rows: impl Iterator<Item = &'a [char]>) -> usize {
let mut max_whole_len = 0;
let mut max_dec_len: Option<usize> = None;
for row in rows {
if let Some(dot_pos) = row.iter().position(|&c| c == '.') {
max_whole_len = max_whole_len.max(dot_pos);
max_dec_len = max_dec_len.max(Some(row.len() - dot_pos - 1));
} else {
max_whole_len = max_whole_len.max(row.len());
}
}
if let Some(dec_len) = max_dec_len {
max_whole_len + dec_len + 1
} else {
max_whole_len
}
}
}
#[cfg(test)]
#[test]
fn f64_summarize() {
assert_eq!(f64::summarize(&[2.0, 6.0, 1.0]), "1-6 μ3");
}
impl ArrayValue for u8 {
const NAME: &'static str = "number";
const SYMBOL: char = 'ℝ';
const TYPE_ID: u8 = 0;
fn get_scalar_fill(fill: &Fill) -> Result<Self, &'static str> {
fill.byte_scalar()
}
fn get_array_fill(fill: &Fill) -> Result<Array<Self>, &'static str> {
fill.byte_array()
}
fn array_hash<H: Hasher>(&self, hasher: &mut H) {
(*self as f64).to_bits().hash(hasher)
}
fn proxy() -> Self {
0
}
fn summarize(elems: &[Self]) -> String {
if elems.is_empty() {
return String::new();
}
let mut min = u8::MAX;
let mut max = 0;
for &elem in elems {
min = min.min(elem);
max = max.max(elem);
}
let mut mean = elems[0] as f64;
for (i, &elem) in elems.iter().enumerate().skip(1) {
mean += (elem as f64 - mean) / (i + 1) as f64;
}
if min == max {