1use std::any::Any;
9use std::ops::Deref;
10use std::sync::atomic::Ordering;
11use std::sync::{Arc, OnceLock};
12
13use crate::complex::Cx;
14use crate::dtype::DType;
15use crate::exact::{Ext, Rat};
16
17pub type Owner = Arc<dyn Any + Send + Sync>;
20
21static JOINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
28
29static LAYOUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
34
35pub fn joins_made() -> u64 {
37 JOINS.load(Ordering::Relaxed)
38}
39
40pub fn layouts_made() -> u64 {
43 LAYOUTS.load(Ordering::Relaxed)
44}
45
46pub struct Buf<T> {
57 repr: Repr<T>,
58}
59
60enum Repr<T> {
61 Owned(Arc<Vec<T>>),
63 Slice { buf: Arc<Vec<T>>, off: usize, len: usize },
68 Foreign { ptr: *const T, len: usize, owner: Owner },
69 Cols {
79 parts: Vec<Buf<T>>,
80 len: usize,
81 flat: Arc<OnceLock<Arc<Vec<T>>>>,
82 join: fn(&[Buf<T>], usize) -> Vec<T>,
83 },
84}
85
86unsafe impl<T: Send + Sync> Send for Buf<T> {}
97unsafe impl<T: Send + Sync> Sync for Buf<T> {}
99
100impl<T> Buf<T> {
101 pub fn new() -> Buf<T> {
102 Buf { repr: Repr::Owned(Arc::new(Vec::new())) }
103 }
104
105 pub fn from_vec(v: Vec<T>) -> Buf<T> {
106 Buf { repr: Repr::Owned(Arc::new(v)) }
107 }
108
109 pub unsafe fn foreign(ptr: *const T, len: usize, owner: Owner) -> Buf<T> {
117 Buf { repr: Repr::Foreign { ptr, len, owner } }
118 }
119
120 pub fn is_foreign(&self) -> bool {
124 match &self.repr {
125 Repr::Foreign { .. } => true,
126 Repr::Cols { parts, flat, .. } => {
127 flat.get().is_none() && parts.iter().any(Buf::is_foreign)
128 }
129 _ => false,
130 }
131 }
132
133 pub fn len(&self) -> usize {
135 match &self.repr {
136 Repr::Owned(v) => v.len(),
137 Repr::Slice { len, .. } | Repr::Foreign { len, .. } | Repr::Cols { len, .. } => *len,
138 }
139 }
140
141 pub fn is_empty(&self) -> bool {
142 self.len() == 0
143 }
144
145 pub fn is_joined(&self) -> bool {
148 matches!(&self.repr, Repr::Cols { flat, .. } if flat.get().is_some())
149 }
150
151 pub fn parts(&self) -> Option<&[Buf<T>]> {
155 match &self.repr {
156 Repr::Cols { parts, .. } => Some(parts),
157 _ => None,
158 }
159 }
160
161 pub fn owner(&self) -> Option<&Owner> {
169 match &self.repr {
170 Repr::Foreign { owner, .. } => Some(owner),
171 _ => None,
172 }
173 }
174}
175
176fn join_sequential<T: Clone>(parts: &[Buf<T>], len: usize) -> Vec<T> {
179 let mut v = Vec::with_capacity(len);
180 for part in parts {
181 v.extend_from_slice(part.as_slice());
182 }
183 v
184}
185
186fn join_parallel<T: Copy + Default + Send + Sync>(parts: &[Buf<T>], len: usize) -> Vec<T> {
190 let slices: Vec<&[T]> = parts.iter().map(Buf::as_slice).collect();
191 let (out, ok) = crate::par::fill(len, |start, dst: &mut [T]| {
192 let mut at = 0;
193 let mut written = 0;
194 for s in &slices {
195 let (from, to) = (at, at + s.len());
196 at = to;
197 let lo = start.max(from);
198 let hi = (start + dst.len()).min(to);
199 if lo < hi {
200 dst[lo - start..hi - start].copy_from_slice(&s[lo - from..hi - from]);
201 written += hi - lo;
202 }
203 }
204 written == dst.len()
205 });
206 debug_assert!(ok, "the parts do not cover the join");
207 out
208}
209
210impl<T: Clone> Buf<T> {
211 pub fn join(parts: Vec<Buf<T>>) -> Buf<T> {
215 Buf::joined(parts, join_sequential)
216 }
217
218 fn joined(parts: Vec<Buf<T>>, join: fn(&[Buf<T>], usize) -> Vec<T>) -> Buf<T> {
219 let len = parts.iter().map(Buf::len).sum();
220 Buf { repr: Repr::Cols { parts, len, flat: Arc::new(OnceLock::new()), join } }
221 }
222
223 pub fn as_slice(&self) -> &[T] {
224 match &self.repr {
225 Repr::Owned(v) => v,
226 Repr::Slice { buf, off, len } => &buf[*off..*off + *len],
227 Repr::Foreign { ptr, len, .. } => {
228 if *len == 0 {
229 &[]
230 } else {
231 unsafe { std::slice::from_raw_parts(*ptr, *len) }
235 }
236 }
237 Repr::Cols { parts, len, flat, join } => flat.get_or_init(|| {
241 JOINS.fetch_add(1, Ordering::Relaxed);
242 Arc::new(join(parts, *len))
243 }),
244 }
245 }
246
247 pub fn to_mut(&mut self) -> &mut Vec<T> {
251 if !matches!(self.repr, Repr::Owned(_)) {
255 self.repr = Repr::Owned(Arc::new(self.as_slice().to_vec()));
256 }
257 match &mut self.repr {
258 Repr::Owned(v) => Arc::make_mut(v),
259 _ => unreachable!("just converted to a whole owned buffer"),
260 }
261 }
262
263 pub fn into_vec(self) -> Vec<T> {
266 match self.repr {
267 Repr::Owned(v) => Arc::try_unwrap(v).unwrap_or_else(|v| v.as_slice().to_vec()),
268 Repr::Slice { ref buf, off, len } => buf[off..off + len].to_vec(),
269 Repr::Foreign { .. } | Repr::Cols { .. } => self.as_slice().to_vec(),
270 }
271 }
272
273 pub fn push(&mut self, value: T) {
274 self.to_mut().push(value);
275 }
276
277 pub fn extend_from_slice(&mut self, other: &[T]) {
278 self.to_mut().extend_from_slice(other);
279 }
280
281 pub fn slice(&self, start: usize, end: usize) -> Buf<T> {
286 match &self.repr {
287 Repr::Owned(v) => {
288 assert!(start <= end && end <= v.len(), "slice out of range");
289 if start == 0 && end == v.len() {
290 return Buf { repr: Repr::Owned(Arc::clone(v)) };
291 }
292 Buf { repr: Repr::Slice { buf: Arc::clone(v), off: start, len: end - start } }
293 }
294 Repr::Slice { buf, off, len } => {
295 assert!(start <= end && end <= *len, "slice out of range");
296 let repr =
297 Repr::Slice { buf: Arc::clone(buf), off: off + start, len: end - start };
298 Buf { repr }
299 }
300 Repr::Foreign { ptr, len, owner } => {
301 assert!(start <= end && end <= *len, "slice out of range");
302 unsafe { Buf::foreign(ptr.add(start), end - start, owner.clone()) }
305 }
306 Repr::Cols { parts, len, flat, .. } => {
310 assert!(start <= end && end <= *len, "slice out of range");
311 if flat.get().is_none() {
312 let mut at = 0;
313 for part in parts {
314 let stop = at + part.len();
315 if start >= at && end <= stop {
316 return part.slice(start - at, end - at);
317 }
318 at = stop;
319 }
320 }
321 let whole = Arc::clone(self.flat_arc());
322 if start == 0 && end == whole.len() {
323 return Buf { repr: Repr::Owned(whole) };
324 }
325 Buf { repr: Repr::Slice { buf: whole, off: start, len: end - start } }
326 }
327 }
328 }
329
330 fn flat_arc(&self) -> &Arc<Vec<T>> {
332 self.as_slice();
333 match &self.repr {
334 Repr::Cols { flat, .. } => flat.get().expect("just initialised"),
335 _ => unreachable!("only a joined buffer is asked for its join"),
336 }
337 }
338}
339
340impl<T: Copy + Default + Send + Sync> Buf<T> {
341 pub fn join_fast(parts: Vec<Buf<T>>) -> Buf<T> {
344 Buf::joined(parts, join_parallel)
345 }
346}
347
348impl<T: Clone> Deref for Buf<T> {
349 type Target = [T];
350
351 fn deref(&self) -> &[T] {
352 self.as_slice()
353 }
354}
355
356impl<T: Clone> Clone for Buf<T> {
360 fn clone(&self) -> Buf<T> {
361 match &self.repr {
362 Repr::Owned(v) => Buf { repr: Repr::Owned(Arc::clone(v)) },
363 Repr::Slice { buf, off, len } => {
364 Buf { repr: Repr::Slice { buf: Arc::clone(buf), off: *off, len: *len } }
365 }
366 Repr::Foreign { ptr, len, owner } => {
367 unsafe { Buf::foreign(*ptr, *len, owner.clone()) }
369 }
370 Repr::Cols { parts, len, flat, join } => Buf {
374 repr: Repr::Cols {
375 parts: parts.clone(),
376 len: *len,
377 flat: Arc::clone(flat),
378 join: *join,
379 },
380 },
381 }
382 }
383}
384
385impl<T> Default for Buf<T> {
386 fn default() -> Buf<T> {
387 Buf::new()
388 }
389}
390
391impl<T: Clone + std::fmt::Debug> std::fmt::Debug for Buf<T> {
392 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393 std::fmt::Debug::fmt(self.as_slice(), f)
394 }
395}
396
397impl<T: Clone + PartialEq> PartialEq for Buf<T> {
398 fn eq(&self, other: &Buf<T>) -> bool {
399 self.as_slice() == other.as_slice()
400 }
401}
402
403impl<T> From<Vec<T>> for Buf<T> {
404 fn from(v: Vec<T>) -> Buf<T> {
405 Buf::from_vec(v)
406 }
407}
408
409impl<'a, T: Clone> IntoIterator for &'a Buf<T> {
410 type Item = &'a T;
411 type IntoIter = std::slice::Iter<'a, T>;
412
413 fn into_iter(self) -> std::slice::Iter<'a, T> {
414 self.as_slice().iter()
415 }
416}
417
418impl<T> FromIterator<T> for Buf<T> {
419 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Buf<T> {
420 Buf::from_vec(Vec::from_iter(iter))
421 }
422}
423
424#[derive(Clone, Debug, PartialEq)]
425pub enum Data {
426 Bool(Buf<u8>),
427 I64(Buf<i64>),
428 Ext(Buf<Ext>),
432 Rat(Buf<Rat>),
434 F64(Buf<f64>),
435 Complex(Buf<Cx>),
438 Char(Buf<char>),
439 Box(Buf<Array>),
443}
444
445impl Data {
446 pub fn dtype(&self) -> DType {
447 match self {
448 Data::Bool(_) => DType::Bool,
449 Data::I64(_) => DType::I64,
450 Data::Ext(_) => DType::Ext,
451 Data::Rat(_) => DType::Rat,
452 Data::F64(_) => DType::F64,
453 Data::Complex(_) => DType::Complex,
454 Data::Char(_) => DType::Char,
455 Data::Box(_) => DType::Box,
456 }
457 }
458
459 pub fn len(&self) -> usize {
460 match self {
461 Data::Bool(v) => v.len(),
462 Data::I64(v) => v.len(),
463 Data::Ext(v) => v.len(),
464 Data::Rat(v) => v.len(),
465 Data::F64(v) => v.len(),
466 Data::Complex(v) => v.len(),
467 Data::Char(v) => v.len(),
468 Data::Box(v) => v.len(),
469 }
470 }
471
472 pub fn is_empty(&self) -> bool {
473 self.len() == 0
474 }
475
476 pub fn is_foreign(&self) -> bool {
478 match self {
479 Data::Bool(v) => v.is_foreign(),
480 Data::I64(v) => v.is_foreign(),
481 Data::Ext(v) => v.is_foreign(),
482 Data::Rat(v) => v.is_foreign(),
483 Data::F64(v) => v.is_foreign(),
484 Data::Complex(v) => v.is_foreign(),
485 Data::Char(v) => v.is_foreign(),
486 Data::Box(v) => v.is_foreign(),
487 }
488 }
489
490 pub fn owner(&self) -> Option<&Owner> {
493 match self {
494 Data::Bool(v) => v.owner(),
495 Data::I64(v) => v.owner(),
496 Data::Ext(v) => v.owner(),
497 Data::Rat(v) => v.owner(),
498 Data::F64(v) => v.owner(),
499 Data::Complex(v) => v.owner(),
500 Data::Char(v) => v.owner(),
501 Data::Box(v) => v.owner(),
502 }
503 }
504
505 pub fn slice(&self, start: usize, end: usize) -> Data {
506 match self {
507 Data::Bool(v) => Data::Bool(v.slice(start, end)),
508 Data::I64(v) => Data::I64(v.slice(start, end)),
509 Data::Ext(v) => Data::Ext(v.slice(start, end)),
510 Data::Rat(v) => Data::Rat(v.slice(start, end)),
511 Data::F64(v) => Data::F64(v.slice(start, end)),
512 Data::Complex(v) => Data::Complex(v.slice(start, end)),
513 Data::Char(v) => Data::Char(v.slice(start, end)),
514 Data::Box(v) => Data::Box(v.slice(start, end)),
515 }
516 }
517
518 pub fn empty(dtype: DType) -> Data {
519 match dtype {
520 DType::Bool => Data::Bool(Buf::new()),
521 DType::I64 => Data::I64(Buf::new()),
522 DType::Ext => Data::Ext(Buf::new()),
523 DType::Rat => Data::Rat(Buf::new()),
524 DType::F64 => Data::F64(Buf::new()),
525 DType::Complex => Data::Complex(Buf::new()),
526 DType::Char => Data::Char(Buf::new()),
527 DType::Box => Data::Box(Buf::new()),
528 }
529 }
530
531 pub fn push_fill(&mut self) {
534 match self {
535 Data::Bool(v) => v.push(0),
536 Data::I64(v) => v.push(0),
537 Data::Ext(v) => v.push(Ext::default()),
538 Data::Rat(v) => v.push(Rat::zero()),
539 Data::F64(v) => v.push(0.0),
540 Data::Complex(v) => v.push(crate::complex::ZERO),
541 Data::Char(v) => v.push(' '),
542 Data::Box(v) => v.push(Array::box_fill()),
543 }
544 }
545
546 pub fn push_from(&mut self, src: &Data, i: usize) {
549 match (self, src) {
550 (Data::Bool(a), Data::Bool(b)) => a.push(b[i]),
551 (Data::I64(a), Data::I64(b)) => a.push(b[i]),
552 (Data::Ext(a), Data::Ext(b)) => a.push(b[i].clone()),
553 (Data::Rat(a), Data::Rat(b)) => a.push(b[i].clone()),
554 (Data::F64(a), Data::F64(b)) => a.push(b[i]),
555 (Data::Complex(a), Data::Complex(b)) => a.push(b[i]),
556 (Data::Char(a), Data::Char(b)) => a.push(b[i]),
557 (Data::Box(a), Data::Box(b)) => a.push(b[i].clone()),
558 _ => {}
559 }
560 }
561
562 pub fn extend_from(&mut self, other: &Data) -> bool {
563 match (self, other) {
564 (Data::Bool(a), Data::Bool(b)) => a.extend_from_slice(b),
565 (Data::I64(a), Data::I64(b)) => a.extend_from_slice(b),
566 (Data::Ext(a), Data::Ext(b)) => a.extend_from_slice(b),
567 (Data::Rat(a), Data::Rat(b)) => a.extend_from_slice(b),
568 (Data::F64(a), Data::F64(b)) => a.extend_from_slice(b),
569 (Data::Complex(a), Data::Complex(b)) => a.extend_from_slice(b),
570 (Data::Char(a), Data::Char(b)) => a.extend_from_slice(b),
571 (Data::Box(a), Data::Box(b)) => a.extend_from_slice(b),
572 _ => return false,
573 }
574 true
575 }
576
577 pub fn join(columns: &[Data], rows: usize) -> Option<Data> {
586 let first = columns.first()?;
587 if columns.iter().any(|c| c.dtype() != first.dtype() || c.len() < rows) {
588 return None;
589 }
590 macro_rules! by {
591 ($variant:ident, $join:expr) => {{
592 let mut parts = Vec::with_capacity(columns.len());
593 for c in columns {
594 let Data::$variant(v) = c else { return None };
595 parts.push(if v.len() == rows { v.clone() } else { v.slice(0, rows) });
598 }
599 Some(Data::$variant($join(parts)))
600 }};
601 }
602 match first.dtype() {
603 DType::Bool => by!(Bool, Buf::join_fast),
604 DType::I64 => by!(I64, Buf::join_fast),
605 DType::F64 => by!(F64, Buf::join_fast),
606 DType::Complex => by!(Complex, Buf::join_fast),
607 DType::Char => by!(Char, Buf::join),
608 DType::Ext => by!(Ext, Buf::join),
609 DType::Rat => by!(Rat, Buf::join),
610 DType::Box => by!(Box, Buf::join),
611 }
612 }
613
614 pub fn columns(&self, rows: usize, cols: usize) -> Vec<Data> {
619 (0..cols).map(|j| self.slice(j * rows, (j + 1) * rows)).collect()
620 }
621
622 pub fn interleave(columns: &[Data], rows: usize) -> Option<Data> {
634 let cols = columns.len();
635 let first = columns.first()?;
636 if columns.iter().any(|c| c.dtype() != first.dtype() || c.len() < rows) {
637 return None;
638 }
639
640 fn weave<T: Copy + Default + Send + Sync>(columns: &[&[T]], rows: usize) -> Vec<T> {
644 let cols = columns.len();
645 let (out, _) = crate::par::fill(rows * cols, |start, part: &mut [T]| {
646 let mut rest = &mut part[..];
647 let mut at = start;
648 let lead = ((cols - at % cols) % cols).min(rest.len());
650 if lead > 0 {
651 let (head, tail) = rest.split_at_mut(lead);
652 let r = at / cols;
653 for (k, slot) in head.iter_mut().enumerate() {
654 *slot = columns[at % cols + k][r];
655 }
656 at += lead;
657 rest = tail;
658 }
659 let whole = rest.len() / cols;
660 let (body, tail) = rest.split_at_mut(whole * cols);
661 let r0 = at / cols;
662 for (k, row) in body.chunks_exact_mut(cols).enumerate() {
663 for (slot, col) in row.iter_mut().zip(columns) {
664 *slot = col[r0 + k];
665 }
666 }
667 let r = r0 + whole;
669 for (c, slot) in tail.iter_mut().enumerate() {
670 *slot = columns[c][r];
671 }
672 true
673 });
674 out
675 }
676
677 fn weave_cloned<T: Clone>(columns: &[&[T]], rows: usize) -> Vec<T> {
681 let mut out = Vec::with_capacity(rows * columns.len());
682 for r in 0..rows {
683 for c in columns {
684 out.push(c[r].clone());
685 }
686 }
687 out
688 }
689
690 macro_rules! by {
691 ($variant:ident, $weave:ident) => {{
692 let mut s = Vec::with_capacity(cols);
693 for c in columns {
694 let Data::$variant(v) = c else { return None };
695 s.push(v.as_slice());
696 }
697 Some(Data::$variant($weave(&s, rows).into()))
698 }};
699 }
700 match first.dtype() {
701 DType::Bool => by!(Bool, weave),
702 DType::I64 => by!(I64, weave),
703 DType::F64 => by!(F64, weave),
704 DType::Complex => by!(Complex, weave),
705 DType::Char => by!(Char, weave),
706 DType::Ext => by!(Ext, weave_cloned),
707 DType::Rat => by!(Rat, weave_cloned),
708 DType::Box => by!(Box, weave_cloned),
709 }
710 }
711
712 pub fn cast(&self, to: DType) -> Option<Data> {
714 if self.dtype() == to {
715 return Some(self.clone());
716 }
717 match (self, to) {
718 (Data::Bool(v), DType::I64) => Some(Data::I64(v.iter().map(|&x| x as i64).collect())),
719 (Data::Bool(v), DType::F64) => Some(Data::F64(v.iter().map(|&x| x as f64).collect())),
720 (Data::I64(v), DType::F64) => Some(Data::F64(v.iter().map(|&x| x as f64).collect())),
721 (Data::Bool(v), DType::Ext) => Some(Data::Ext(v.iter().map(|&x| Ext::from(x)).collect())),
722 (Data::I64(v), DType::Ext) => Some(Data::Ext(v.iter().map(|&x| Ext::from(x)).collect())),
723 (Data::Bool(v), DType::Rat) => {
724 Some(Data::Rat(v.iter().map(|&x| Rat::from_int(Ext::from(x))).collect()))
725 }
726 (Data::I64(v), DType::Rat) => {
727 Some(Data::Rat(v.iter().map(|&x| Rat::from_int(Ext::from(x))).collect()))
728 }
729 (Data::Ext(v), DType::Rat) => {
730 Some(Data::Rat(v.iter().map(|x| Rat::from_int(x.clone())).collect()))
731 }
732 (Data::Ext(v), DType::F64) => {
733 Some(Data::F64(v.iter().map(crate::exact::ext_to_f64).collect()))
734 }
735 (Data::Rat(v), DType::F64) => Some(Data::F64(v.iter().map(Rat::to_f64).collect())),
736 (Data::Bool(v), DType::Complex) => {
737 Some(Data::Complex(v.iter().map(|&x| [x as f64, 0.0]).collect()))
738 }
739 (Data::I64(v), DType::Complex) => {
740 Some(Data::Complex(v.iter().map(|&x| [x as f64, 0.0]).collect()))
741 }
742 (Data::Ext(v), DType::Complex) => {
743 Some(Data::Complex(v.iter().map(|x| [crate::exact::ext_to_f64(x), 0.0]).collect()))
744 }
745 (Data::Rat(v), DType::Complex) => {
746 Some(Data::Complex(v.iter().map(|x| [x.to_f64(), 0.0]).collect()))
747 }
748 (Data::F64(v), DType::Complex) => {
749 Some(Data::Complex(v.iter().map(|&x| [x, 0.0]).collect()))
750 }
751 _ => None,
752 }
753 }
754}
755
756#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
763pub enum Layout {
764 #[default]
767 RowMajor,
768 ColMajor,
773}
774
775#[derive(Clone, Debug)]
782pub struct Array {
783 pub shape: Vec<usize>,
784 pub data: Data,
785 layout: Layout,
786}
787
788impl PartialEq for Array {
791 fn eq(&self, other: &Array) -> bool {
792 if self.shape != other.shape {
793 return false;
794 }
795 if self.layout == other.layout {
796 return self.data == other.data;
797 }
798 self.to_row_major().data == other.to_row_major().data
799 }
800}
801
802impl Array {
803 pub fn new(shape: Vec<usize>, data: Data) -> Array {
804 debug_assert_eq!(shape.iter().product::<usize>(), data.len());
805 Array { shape, data, layout: Layout::RowMajor }
806 }
807
808 pub fn col_major(shape: Vec<usize>, data: Data) -> Array {
811 debug_assert_eq!(shape.iter().product::<usize>(), data.len());
812 let layout = if shape.len() < 2 { Layout::RowMajor } else { Layout::ColMajor };
813 Array { shape, data, layout }
814 }
815
816 pub fn with_layout(mut self, layout: Layout) -> Array {
819 self.layout = if self.shape.len() < 2 { Layout::RowMajor } else { layout };
820 self
821 }
822
823 pub fn layout(&self) -> Layout {
825 self.layout
826 }
827
828 pub fn is_row_major(&self) -> bool {
829 self.layout == Layout::RowMajor
830 }
831
832 pub fn row_major_data(&self) -> &Data {
836 debug_assert!(self.is_row_major(), "a column-major buffer read as row-major");
837 &self.data
838 }
839
840 pub fn to_row_major(&self) -> Array {
843 if self.is_row_major() {
844 return self.clone();
845 }
846 LAYOUTS.fetch_add(1, Ordering::Relaxed);
847 Array::new(self.shape.clone(), self.transposed_data())
848 }
849
850 fn transposed_data(&self) -> Data {
852 let rows = self.shape[0];
853 let rest: usize = self.shape[1..].iter().product();
854 if self.rank() == 2
857 && let Some(d) = Data::interleave(&self.data.columns(rows, rest), rows)
858 {
859 return d;
860 }
861 let n = self.count();
864 let mut out = Data::empty(self.dtype());
865 let mut coord = vec![0usize; self.rank()];
866 for _ in 0..n {
867 let mut idx = 0;
868 let mut stride = 1;
869 for (k, &len) in self.shape.iter().enumerate() {
870 idx += coord[k] * stride;
871 stride *= len;
872 }
873 out.push_from(&self.data, idx);
874 let mut k = self.rank();
875 while k > 0 {
876 k -= 1;
877 coord[k] += 1;
878 if coord[k] < self.shape[k] {
879 break;
880 }
881 coord[k] = 0;
882 }
883 }
884 out
885 }
886
887 pub fn scalar_i64(v: i64) -> Array {
888 Array::new(vec![], Data::I64(vec![v].into()))
889 }
890
891 pub fn scalar_f64(v: f64) -> Array {
892 Array::new(vec![], Data::F64(vec![v].into()))
893 }
894
895 pub fn scalar_bool(v: bool) -> Array {
896 Array::new(vec![], Data::Bool(vec![v as u8].into()))
897 }
898
899 pub fn from_i64(values: Vec<i64>) -> Array {
900 Array::new(vec![values.len()], Data::I64(values.into()))
901 }
902
903 pub fn from_f64(values: Vec<f64>) -> Array {
904 Array::new(vec![values.len()], Data::F64(values.into()))
905 }
906
907 pub fn from_chars(values: Vec<char>) -> Array {
908 Array::new(vec![values.len()], Data::Char(values.into()))
909 }
910
911 pub fn empty(dtype: DType) -> Array {
912 Array::new(vec![0], Data::empty(dtype))
913 }
914
915 pub fn boxed(value: Array) -> Array {
917 Array::new(vec![], Data::Box(vec![value].into()))
918 }
919
920 pub fn box_fill() -> Array {
923 Array::empty(DType::I64)
924 }
925
926 pub fn dtype(&self) -> DType {
927 self.data.dtype()
928 }
929
930 pub fn rank(&self) -> usize {
931 self.shape.len()
932 }
933
934 pub fn count(&self) -> usize {
936 self.shape.iter().product()
937 }
938
939 pub fn items(&self) -> usize {
941 self.shape.first().copied().unwrap_or(1)
942 }
943
944 pub fn item_size(&self) -> usize {
946 self.shape.iter().skip(1).product()
947 }
948
949 pub fn cast(&self, to: DType) -> Option<Array> {
952 Some(Array { shape: self.shape.clone(), data: self.data.cast(to)?, layout: self.layout })
953 }
954
955 pub fn cells(&self, frame_rank: usize) -> Vec<Array> {
958 debug_assert!(frame_rank <= self.rank());
959 debug_assert!(self.is_row_major(), "cells of a column-major buffer");
960 let cell_shape: Vec<usize> = self.shape[frame_rank..].to_vec();
961 let cell_size: usize = cell_shape.iter().product();
962 let n: usize = self.shape[..frame_rank].iter().product();
963 (0..n)
964 .map(|i| {
965 Array::new(cell_shape.clone(), self.data.slice(i * cell_size, (i + 1) * cell_size))
966 })
967 .collect()
968 }
969
970 pub fn cell_at(&self, frame_rank: usize, index: usize) -> Array {
972 debug_assert!(self.is_row_major(), "a cell of a column-major buffer");
973 let cell_shape: Vec<usize> = self.shape[frame_rank..].to_vec();
974 let cell_size: usize = cell_shape.iter().product();
975 Array::new(cell_shape, self.data.slice(index * cell_size, (index + 1) * cell_size))
976 }
977
978 pub fn item(&self, i: usize) -> Array {
980 debug_assert!(self.rank() >= 1);
981 self.cell_at(1, i)
982 }
983
984 pub fn as_i64_slice(&self) -> Option<&[i64]> {
985 match &self.data {
986 Data::I64(v) => Some(v),
987 _ => None,
988 }
989 }
990
991 pub fn as_boxes(&self) -> Option<&[Array]> {
993 match &self.data {
994 Data::Box(v) => Some(v),
995 _ => None,
996 }
997 }
998
999 pub fn as_f64_slice(&self) -> Option<&[f64]> {
1000 match &self.data {
1001 Data::F64(v) => Some(v),
1002 _ => None,
1003 }
1004 }
1005
1006 pub fn as_ext_slice(&self) -> Option<&[Ext]> {
1008 match &self.data {
1009 Data::Ext(v) => Some(v),
1010 _ => None,
1011 }
1012 }
1013
1014 pub fn as_rat_slice(&self) -> Option<&[Rat]> {
1016 match &self.data {
1017 Data::Rat(v) => Some(v),
1018 _ => None,
1019 }
1020 }
1021
1022 pub fn as_complex_slice(&self) -> Option<&[Cx]> {
1023 match &self.data {
1024 Data::Complex(v) => Some(v),
1025 _ => None,
1026 }
1027 }
1028
1029 pub fn to_complex_vec(&self) -> Option<Vec<Cx>> {
1031 match &self.data {
1032 Data::Bool(v) => Some(v.iter().map(|&x| [x as f64, 0.0]).collect()),
1033 Data::I64(v) => Some(v.iter().map(|&x| [x as f64, 0.0]).collect()),
1034 Data::Ext(v) => Some(v.iter().map(|x| [crate::exact::ext_to_f64(x), 0.0]).collect()),
1035 Data::Rat(v) => Some(v.iter().map(|x| [x.to_f64(), 0.0]).collect()),
1036 Data::F64(v) => Some(v.iter().map(|&x| [x, 0.0]).collect()),
1037 Data::Complex(v) => Some(v.to_vec()),
1038 Data::Char(_) | Data::Box(_) => None,
1039 }
1040 }
1041
1042 pub fn to_f64_vec(&self) -> Option<Vec<f64>> {
1044 match &self.data {
1045 Data::Bool(v) => Some(v.iter().map(|&x| x as f64).collect()),
1046 Data::I64(v) => Some(v.iter().map(|&x| x as f64).collect()),
1047 Data::Ext(v) => Some(v.iter().map(crate::exact::ext_to_f64).collect()),
1048 Data::Rat(v) => Some(v.iter().map(Rat::to_f64).collect()),
1049 Data::F64(v) => Some(v.to_vec()),
1050 Data::Complex(_) | Data::Char(_) | Data::Box(_) => None,
1053 }
1054 }
1055
1056 pub fn to_i64_vec(&self) -> Option<Vec<i64>> {
1058 match &self.data {
1059 Data::Bool(v) => Some(v.iter().map(|&x| x as i64).collect()),
1060 Data::I64(v) => Some(v.to_vec()),
1061 Data::Ext(v) => v.iter().map(crate::exact::ext_to_i64).collect(),
1064 Data::Rat(v) => {
1065 v.iter().map(|x| x.to_int().as_ref().and_then(crate::exact::ext_to_i64)).collect()
1066 }
1067 Data::F64(v) => {
1068 let mut out = Vec::with_capacity(v.len());
1069 for &x in v.iter() {
1070 if x.fract() != 0.0 || x.abs() >= i64::MAX as f64 {
1071 return None;
1072 }
1073 out.push(x as i64);
1074 }
1075 Some(out)
1076 }
1077 Data::Complex(_) | Data::Char(_) | Data::Box(_) => None,
1078 }
1079 }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 use super::*;
1085 use std::sync::atomic::{AtomicBool, Ordering};
1086
1087 struct Guard {
1090 values: Vec<i64>,
1091 dropped: Arc<AtomicBool>,
1092 }
1093
1094 impl Drop for Guard {
1095 fn drop(&mut self) {
1096 self.dropped.store(true, Ordering::SeqCst);
1097 }
1098 }
1099
1100 fn foreign_buf(values: Vec<i64>, dropped: Arc<AtomicBool>) -> Buf<i64> {
1101 let guard = Arc::new(Guard { values, dropped });
1102 let ptr = guard.values.as_ptr();
1103 let len = guard.values.len();
1104 unsafe { Buf::foreign(ptr, len, guard) }
1107 }
1108
1109 #[test]
1110 fn owned_buf_derefs_to_its_slice() {
1111 let b: Buf<i64> = vec![1, 2, 3].into();
1112 assert!(!b.is_foreign());
1113 assert_eq!(&b[..], &[1, 2, 3]);
1114 assert_eq!(b.len(), 3);
1115 assert_eq!(b.iter().sum::<i64>(), 6);
1116 }
1117
1118 #[test]
1119 fn empty_buf_is_a_valid_empty_slice() {
1120 let b: Buf<f64> = Buf::new();
1121 assert_eq!(&b[..], &[] as &[f64]);
1122 let f = unsafe { Buf::<f64>::foreign(std::ptr::null(), 0, Arc::new(())) };
1124 assert_eq!(&f[..], &[] as &[f64]);
1125 }
1126
1127 #[test]
1128 fn cloning_an_owned_buf_shares_the_same_memory() {
1129 let b: Buf<i64> = vec![1, 2, 3].into();
1130 let c = b.clone();
1131 assert_eq!(b.as_ptr(), c.as_ptr(), "owned clone copied the elements");
1132 assert_eq!(&c[..], &[1, 2, 3]);
1133 }
1134
1135 #[test]
1136 fn writing_to_a_shared_owned_buf_copies_first() {
1137 let b: Buf<i64> = vec![1, 2, 3].into();
1138 let mut c = b.clone();
1139 c.to_mut()[0] = 99;
1140 assert_eq!(&b[..], &[1, 2, 3], "the other holder saw the write");
1141 assert_eq!(&c[..], &[99, 2, 3]);
1142 assert_ne!(b.as_ptr(), c.as_ptr());
1143 let ptr = c.as_ptr();
1145 c.to_mut()[1] = 98;
1146 assert_eq!(c.as_ptr(), ptr, "unshared write copied");
1147 }
1148
1149 #[test]
1150 fn into_vec_moves_when_sole_holder_and_copies_when_shared() {
1151 let b: Buf<i64> = vec![1, 2, 3].into();
1152 let ptr = b.as_ptr();
1153 let v = b.into_vec();
1154 assert_eq!(v.as_ptr(), ptr, "sole holder copied instead of moving");
1155
1156 let b: Buf<i64> = vec![1, 2, 3].into();
1157 let c = b.clone();
1158 let v = b.into_vec();
1159 assert_eq!(v, vec![1, 2, 3]);
1160 assert_eq!(&c[..], &[1, 2, 3]);
1161 }
1162
1163 #[test]
1164 fn foreign_buf_reads_borrowed_memory_and_keeps_the_owner_alive() {
1165 let dropped = Arc::new(AtomicBool::new(false));
1166 let b = foreign_buf(vec![10, 20, 30], dropped.clone());
1167 assert!(b.is_foreign());
1168 assert_eq!(&b[..], &[10, 20, 30]);
1169 assert!(!dropped.load(Ordering::SeqCst), "owner dropped while borrowed");
1170 drop(b);
1171 assert!(dropped.load(Ordering::SeqCst), "owner leaked after the buffer died");
1172 }
1173
1174 #[test]
1175 fn cloning_a_foreign_buf_shares_the_same_memory() {
1176 let dropped = Arc::new(AtomicBool::new(false));
1177 let b = foreign_buf(vec![1, 2, 3], dropped.clone());
1178 let c = b.clone();
1179 assert!(c.is_foreign());
1180 assert_eq!(b.as_ptr(), c.as_ptr());
1181 drop(b);
1182 assert!(!dropped.load(Ordering::SeqCst), "owner dropped while a clone lives");
1183 assert_eq!(&c[..], &[1, 2, 3]);
1184 }
1185
1186 #[test]
1187 fn slicing_a_foreign_buf_keeps_borrowing() {
1188 let dropped = Arc::new(AtomicBool::new(false));
1189 let b = foreign_buf(vec![1, 2, 3, 4], dropped.clone());
1190 let s = b.slice(1, 3);
1191 assert!(s.is_foreign());
1192 assert_eq!(&s[..], &[2, 3]);
1193 drop(b);
1194 assert_eq!(&s[..], &[2, 3]);
1195 assert!(!dropped.load(Ordering::SeqCst));
1196 }
1197
1198 #[test]
1199 fn mutating_a_foreign_buf_copies_first() {
1200 let dropped = Arc::new(AtomicBool::new(false));
1201 let mut b = foreign_buf(vec![1, 2, 3], dropped.clone());
1202 b.push(4);
1203 assert!(!b.is_foreign());
1204 assert_eq!(&b[..], &[1, 2, 3, 4]);
1205 drop(b);
1207 assert!(dropped.load(Ordering::SeqCst));
1208 }
1209
1210 #[test]
1211 fn copy_on_write_leaves_other_holders_alone() {
1212 let dropped = Arc::new(AtomicBool::new(false));
1213 let b = foreign_buf(vec![1, 2, 3], dropped.clone());
1214 let mut c = b.clone();
1215 c.to_mut()[0] = 99;
1216 assert_eq!(&b[..], &[1, 2, 3]);
1217 assert_eq!(&c[..], &[99, 2, 3]);
1218 }
1219
1220 #[test]
1221 fn foreign_data_slices_without_copying() {
1222 let dropped = Arc::new(AtomicBool::new(false));
1223 let a = Array::new(vec![2, 2], Data::I64(foreign_buf(vec![1, 2, 3, 4], dropped)));
1224 assert!(a.data.is_foreign());
1225 let row = a.item(1);
1226 assert!(row.data.is_foreign());
1227 assert_eq!(row.as_i64_slice(), Some(&[3, 4][..]));
1228 }
1229
1230 #[test]
1231 fn foreign_data_extends_by_copying() {
1232 let dropped = Arc::new(AtomicBool::new(false));
1233 let mut d = Data::I64(foreign_buf(vec![1, 2], dropped));
1234 assert!(d.is_foreign());
1235 assert!(d.extend_from(&Data::I64(vec![3].into())));
1236 assert!(!d.is_foreign());
1237 assert_eq!(d, Data::I64(vec![1, 2, 3].into()));
1238 }
1239}