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 Symbol(Buf<crate::symbol::Id>),
443 Box(Buf<Array>),
447}
448
449impl Data {
450 pub fn dtype(&self) -> DType {
451 match self {
452 Data::Bool(_) => DType::Bool,
453 Data::I64(_) => DType::I64,
454 Data::Ext(_) => DType::Ext,
455 Data::Rat(_) => DType::Rat,
456 Data::F64(_) => DType::F64,
457 Data::Complex(_) => DType::Complex,
458 Data::Char(_) => DType::Char,
459 Data::Symbol(_) => DType::Symbol,
460 Data::Box(_) => DType::Box,
461 }
462 }
463
464 pub fn len(&self) -> usize {
465 match self {
466 Data::Bool(v) => v.len(),
467 Data::I64(v) => v.len(),
468 Data::Ext(v) => v.len(),
469 Data::Rat(v) => v.len(),
470 Data::F64(v) => v.len(),
471 Data::Complex(v) => v.len(),
472 Data::Char(v) => v.len(),
473 Data::Symbol(v) => v.len(),
474 Data::Box(v) => v.len(),
475 }
476 }
477
478 pub fn is_empty(&self) -> bool {
479 self.len() == 0
480 }
481
482 pub fn is_foreign(&self) -> bool {
484 match self {
485 Data::Bool(v) => v.is_foreign(),
486 Data::I64(v) => v.is_foreign(),
487 Data::Ext(v) => v.is_foreign(),
488 Data::Rat(v) => v.is_foreign(),
489 Data::F64(v) => v.is_foreign(),
490 Data::Complex(v) => v.is_foreign(),
491 Data::Char(v) => v.is_foreign(),
492 Data::Symbol(v) => v.is_foreign(),
493 Data::Box(v) => v.is_foreign(),
494 }
495 }
496
497 pub fn owner(&self) -> Option<&Owner> {
500 match self {
501 Data::Bool(v) => v.owner(),
502 Data::I64(v) => v.owner(),
503 Data::Ext(v) => v.owner(),
504 Data::Rat(v) => v.owner(),
505 Data::F64(v) => v.owner(),
506 Data::Complex(v) => v.owner(),
507 Data::Char(v) => v.owner(),
508 Data::Symbol(v) => v.owner(),
509 Data::Box(v) => v.owner(),
510 }
511 }
512
513 pub fn slice(&self, start: usize, end: usize) -> Data {
514 match self {
515 Data::Bool(v) => Data::Bool(v.slice(start, end)),
516 Data::I64(v) => Data::I64(v.slice(start, end)),
517 Data::Ext(v) => Data::Ext(v.slice(start, end)),
518 Data::Rat(v) => Data::Rat(v.slice(start, end)),
519 Data::F64(v) => Data::F64(v.slice(start, end)),
520 Data::Complex(v) => Data::Complex(v.slice(start, end)),
521 Data::Char(v) => Data::Char(v.slice(start, end)),
522 Data::Symbol(v) => Data::Symbol(v.slice(start, end)),
523 Data::Box(v) => Data::Box(v.slice(start, end)),
524 }
525 }
526
527 pub fn empty(dtype: DType) -> Data {
528 match dtype {
529 DType::Bool => Data::Bool(Buf::new()),
530 DType::I64 => Data::I64(Buf::new()),
531 DType::Ext => Data::Ext(Buf::new()),
532 DType::Rat => Data::Rat(Buf::new()),
533 DType::F64 => Data::F64(Buf::new()),
534 DType::Complex => Data::Complex(Buf::new()),
535 DType::Char => Data::Char(Buf::new()),
536 DType::Symbol => Data::Symbol(Buf::new()),
537 DType::Box => Data::Box(Buf::new()),
538 }
539 }
540
541 pub fn push_fill(&mut self) {
544 match self {
545 Data::Bool(v) => v.push(0),
546 Data::I64(v) => v.push(0),
547 Data::Ext(v) => v.push(Ext::default()),
548 Data::Rat(v) => v.push(Rat::zero()),
549 Data::F64(v) => v.push(0.0),
550 Data::Complex(v) => v.push(crate::complex::ZERO),
551 Data::Char(v) => v.push(' '),
552 Data::Symbol(v) => v.push(crate::symbol::EMPTY),
553 Data::Box(v) => v.push(Array::box_fill()),
554 }
555 }
556
557 pub fn push_from(&mut self, src: &Data, i: usize) {
560 match (self, src) {
561 (Data::Bool(a), Data::Bool(b)) => a.push(b[i]),
562 (Data::I64(a), Data::I64(b)) => a.push(b[i]),
563 (Data::Ext(a), Data::Ext(b)) => a.push(b[i].clone()),
564 (Data::Rat(a), Data::Rat(b)) => a.push(b[i].clone()),
565 (Data::F64(a), Data::F64(b)) => a.push(b[i]),
566 (Data::Complex(a), Data::Complex(b)) => a.push(b[i]),
567 (Data::Char(a), Data::Char(b)) => a.push(b[i]),
568 (Data::Symbol(a), Data::Symbol(b)) => a.push(b[i]),
569 (Data::Box(a), Data::Box(b)) => a.push(b[i].clone()),
570 _ => {}
571 }
572 }
573
574 pub fn extend_from(&mut self, other: &Data) -> bool {
575 match (self, other) {
576 (Data::Bool(a), Data::Bool(b)) => a.extend_from_slice(b),
577 (Data::I64(a), Data::I64(b)) => a.extend_from_slice(b),
578 (Data::Ext(a), Data::Ext(b)) => a.extend_from_slice(b),
579 (Data::Rat(a), Data::Rat(b)) => a.extend_from_slice(b),
580 (Data::F64(a), Data::F64(b)) => a.extend_from_slice(b),
581 (Data::Complex(a), Data::Complex(b)) => a.extend_from_slice(b),
582 (Data::Char(a), Data::Char(b)) => a.extend_from_slice(b),
583 (Data::Symbol(a), Data::Symbol(b)) => a.extend_from_slice(b),
584 (Data::Box(a), Data::Box(b)) => a.extend_from_slice(b),
585 _ => return false,
586 }
587 true
588 }
589
590 pub fn join(columns: &[Data], rows: usize) -> Option<Data> {
599 let first = columns.first()?;
600 if columns.iter().any(|c| c.dtype() != first.dtype() || c.len() < rows) {
601 return None;
602 }
603 macro_rules! by {
604 ($variant:ident, $join:expr) => {{
605 let mut parts = Vec::with_capacity(columns.len());
606 for c in columns {
607 let Data::$variant(v) = c else { return None };
608 parts.push(if v.len() == rows { v.clone() } else { v.slice(0, rows) });
611 }
612 Some(Data::$variant($join(parts)))
613 }};
614 }
615 match first.dtype() {
616 DType::Bool => by!(Bool, Buf::join_fast),
617 DType::I64 => by!(I64, Buf::join_fast),
618 DType::F64 => by!(F64, Buf::join_fast),
619 DType::Complex => by!(Complex, Buf::join_fast),
620 DType::Char => by!(Char, Buf::join),
621 DType::Symbol => by!(Symbol, Buf::join_fast),
622 DType::Ext => by!(Ext, Buf::join),
623 DType::Rat => by!(Rat, Buf::join),
624 DType::Box => by!(Box, Buf::join),
625 }
626 }
627
628 pub fn columns(&self, rows: usize, cols: usize) -> Vec<Data> {
633 (0..cols).map(|j| self.slice(j * rows, (j + 1) * rows)).collect()
634 }
635
636 pub fn interleave(columns: &[Data], rows: usize) -> Option<Data> {
648 let cols = columns.len();
649 let first = columns.first()?;
650 if columns.iter().any(|c| c.dtype() != first.dtype() || c.len() < rows) {
651 return None;
652 }
653
654 fn weave<T: Copy + Default + Send + Sync>(columns: &[&[T]], rows: usize) -> Vec<T> {
658 let cols = columns.len();
659 let (out, _) = crate::par::fill(rows * cols, |start, part: &mut [T]| {
660 let mut rest = &mut part[..];
661 let mut at = start;
662 let lead = ((cols - at % cols) % cols).min(rest.len());
664 if lead > 0 {
665 let (head, tail) = rest.split_at_mut(lead);
666 let r = at / cols;
667 for (k, slot) in head.iter_mut().enumerate() {
668 *slot = columns[at % cols + k][r];
669 }
670 at += lead;
671 rest = tail;
672 }
673 let whole = rest.len() / cols;
674 let (body, tail) = rest.split_at_mut(whole * cols);
675 let r0 = at / cols;
676 for (k, row) in body.chunks_exact_mut(cols).enumerate() {
677 for (slot, col) in row.iter_mut().zip(columns) {
678 *slot = col[r0 + k];
679 }
680 }
681 let r = r0 + whole;
683 for (c, slot) in tail.iter_mut().enumerate() {
684 *slot = columns[c][r];
685 }
686 true
687 });
688 out
689 }
690
691 fn weave_cloned<T: Clone>(columns: &[&[T]], rows: usize) -> Vec<T> {
695 let mut out = Vec::with_capacity(rows * columns.len());
696 for r in 0..rows {
697 for c in columns {
698 out.push(c[r].clone());
699 }
700 }
701 out
702 }
703
704 macro_rules! by {
705 ($variant:ident, $weave:ident) => {{
706 let mut s = Vec::with_capacity(cols);
707 for c in columns {
708 let Data::$variant(v) = c else { return None };
709 s.push(v.as_slice());
710 }
711 Some(Data::$variant($weave(&s, rows).into()))
712 }};
713 }
714 match first.dtype() {
715 DType::Bool => by!(Bool, weave),
716 DType::I64 => by!(I64, weave),
717 DType::F64 => by!(F64, weave),
718 DType::Complex => by!(Complex, weave),
719 DType::Char => by!(Char, weave),
720 DType::Symbol => by!(Symbol, weave),
721 DType::Ext => by!(Ext, weave_cloned),
722 DType::Rat => by!(Rat, weave_cloned),
723 DType::Box => by!(Box, weave_cloned),
724 }
725 }
726
727 pub fn cast(&self, to: DType) -> Option<Data> {
729 if self.dtype() == to {
730 return Some(self.clone());
731 }
732 match (self, to) {
733 (Data::Bool(v), DType::I64) => Some(Data::I64(v.iter().map(|&x| x as i64).collect())),
734 (Data::Bool(v), DType::F64) => Some(Data::F64(v.iter().map(|&x| x as f64).collect())),
735 (Data::I64(v), DType::F64) => Some(Data::F64(v.iter().map(|&x| x as f64).collect())),
736 (Data::Bool(v), DType::Ext) => Some(Data::Ext(v.iter().map(|&x| Ext::from(x)).collect())),
737 (Data::I64(v), DType::Ext) => Some(Data::Ext(v.iter().map(|&x| Ext::from(x)).collect())),
738 (Data::Bool(v), DType::Rat) => {
739 Some(Data::Rat(v.iter().map(|&x| Rat::from_int(Ext::from(x))).collect()))
740 }
741 (Data::I64(v), DType::Rat) => {
742 Some(Data::Rat(v.iter().map(|&x| Rat::from_int(Ext::from(x))).collect()))
743 }
744 (Data::Ext(v), DType::Rat) => {
745 Some(Data::Rat(v.iter().map(|x| Rat::from_int(x.clone())).collect()))
746 }
747 (Data::Ext(v), DType::F64) => {
748 Some(Data::F64(v.iter().map(crate::exact::ext_to_f64).collect()))
749 }
750 (Data::Rat(v), DType::F64) => Some(Data::F64(v.iter().map(Rat::to_f64).collect())),
751 (Data::Bool(v), DType::Complex) => {
752 Some(Data::Complex(v.iter().map(|&x| [x as f64, 0.0]).collect()))
753 }
754 (Data::I64(v), DType::Complex) => {
755 Some(Data::Complex(v.iter().map(|&x| [x as f64, 0.0]).collect()))
756 }
757 (Data::Ext(v), DType::Complex) => {
758 Some(Data::Complex(v.iter().map(|x| [crate::exact::ext_to_f64(x), 0.0]).collect()))
759 }
760 (Data::Rat(v), DType::Complex) => {
761 Some(Data::Complex(v.iter().map(|x| [x.to_f64(), 0.0]).collect()))
762 }
763 (Data::F64(v), DType::Complex) => {
764 Some(Data::Complex(v.iter().map(|&x| [x, 0.0]).collect()))
765 }
766 _ => None,
767 }
768 }
769}
770
771#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
778pub enum Layout {
779 #[default]
782 RowMajor,
783 ColMajor,
788}
789
790#[derive(Clone, Debug)]
797pub struct Array {
798 pub shape: Vec<usize>,
799 pub data: Data,
800 layout: Layout,
801}
802
803impl PartialEq for Array {
806 fn eq(&self, other: &Array) -> bool {
807 if self.shape != other.shape {
808 return false;
809 }
810 if self.layout == other.layout {
811 return self.data == other.data;
812 }
813 self.to_row_major().data == other.to_row_major().data
814 }
815}
816
817impl Array {
818 pub fn new(shape: Vec<usize>, data: Data) -> Array {
819 debug_assert_eq!(shape.iter().product::<usize>(), data.len());
820 Array { shape, data, layout: Layout::RowMajor }
821 }
822
823 pub fn col_major(shape: Vec<usize>, data: Data) -> Array {
826 debug_assert_eq!(shape.iter().product::<usize>(), data.len());
827 let layout = if shape.len() < 2 { Layout::RowMajor } else { Layout::ColMajor };
828 Array { shape, data, layout }
829 }
830
831 pub fn with_layout(mut self, layout: Layout) -> Array {
834 self.layout = if self.shape.len() < 2 { Layout::RowMajor } else { layout };
835 self
836 }
837
838 pub fn layout(&self) -> Layout {
840 self.layout
841 }
842
843 pub fn is_row_major(&self) -> bool {
844 self.layout == Layout::RowMajor
845 }
846
847 pub fn row_major_data(&self) -> &Data {
851 debug_assert!(self.is_row_major(), "a column-major buffer read as row-major");
852 &self.data
853 }
854
855 pub fn to_row_major(&self) -> Array {
858 if self.is_row_major() {
859 return self.clone();
860 }
861 LAYOUTS.fetch_add(1, Ordering::Relaxed);
862 Array::new(self.shape.clone(), self.transposed_data())
863 }
864
865 fn transposed_data(&self) -> Data {
867 let rows = self.shape[0];
868 let rest: usize = self.shape[1..].iter().product();
869 if self.rank() == 2
872 && let Some(d) = Data::interleave(&self.data.columns(rows, rest), rows)
873 {
874 return d;
875 }
876 let n = self.count();
879 let mut out = Data::empty(self.dtype());
880 let mut coord = vec![0usize; self.rank()];
881 for _ in 0..n {
882 let mut idx = 0;
883 let mut stride = 1;
884 for (k, &len) in self.shape.iter().enumerate() {
885 idx += coord[k] * stride;
886 stride *= len;
887 }
888 out.push_from(&self.data, idx);
889 let mut k = self.rank();
890 while k > 0 {
891 k -= 1;
892 coord[k] += 1;
893 if coord[k] < self.shape[k] {
894 break;
895 }
896 coord[k] = 0;
897 }
898 }
899 out
900 }
901
902 pub fn scalar_i64(v: i64) -> Array {
903 Array::new(vec![], Data::I64(vec![v].into()))
904 }
905
906 pub fn scalar_f64(v: f64) -> Array {
907 Array::new(vec![], Data::F64(vec![v].into()))
908 }
909
910 pub fn scalar_bool(v: bool) -> Array {
911 Array::new(vec![], Data::Bool(vec![v as u8].into()))
912 }
913
914 pub fn from_i64(values: Vec<i64>) -> Array {
915 Array::new(vec![values.len()], Data::I64(values.into()))
916 }
917
918 pub fn from_f64(values: Vec<f64>) -> Array {
919 Array::new(vec![values.len()], Data::F64(values.into()))
920 }
921
922 pub fn from_chars(values: Vec<char>) -> Array {
923 Array::new(vec![values.len()], Data::Char(values.into()))
924 }
925
926 pub fn empty(dtype: DType) -> Array {
927 Array::new(vec![0], Data::empty(dtype))
928 }
929
930 pub fn boxed(value: Array) -> Array {
932 Array::new(vec![], Data::Box(vec![value].into()))
933 }
934
935 pub fn box_fill() -> Array {
938 Array::empty(DType::I64)
939 }
940
941 pub fn dtype(&self) -> DType {
942 self.data.dtype()
943 }
944
945 pub fn rank(&self) -> usize {
946 self.shape.len()
947 }
948
949 pub fn count(&self) -> usize {
951 self.shape.iter().product()
952 }
953
954 pub fn items(&self) -> usize {
956 self.shape.first().copied().unwrap_or(1)
957 }
958
959 pub fn item_size(&self) -> usize {
961 self.shape.iter().skip(1).product()
962 }
963
964 pub fn cast(&self, to: DType) -> Option<Array> {
967 Some(Array { shape: self.shape.clone(), data: self.data.cast(to)?, layout: self.layout })
968 }
969
970 pub fn cells(&self, frame_rank: usize) -> Vec<Array> {
973 debug_assert!(frame_rank <= self.rank());
974 debug_assert!(self.is_row_major(), "cells of a column-major buffer");
975 let cell_shape: Vec<usize> = self.shape[frame_rank..].to_vec();
976 let cell_size: usize = cell_shape.iter().product();
977 let n: usize = self.shape[..frame_rank].iter().product();
978 (0..n)
979 .map(|i| {
980 Array::new(cell_shape.clone(), self.data.slice(i * cell_size, (i + 1) * cell_size))
981 })
982 .collect()
983 }
984
985 pub fn cell_at(&self, frame_rank: usize, index: usize) -> Array {
987 debug_assert!(self.is_row_major(), "a cell of a column-major buffer");
988 let cell_shape: Vec<usize> = self.shape[frame_rank..].to_vec();
989 let cell_size: usize = cell_shape.iter().product();
990 Array::new(cell_shape, self.data.slice(index * cell_size, (index + 1) * cell_size))
991 }
992
993 pub fn item(&self, i: usize) -> Array {
995 debug_assert!(self.rank() >= 1);
996 self.cell_at(1, i)
997 }
998
999 pub fn as_i64_slice(&self) -> Option<&[i64]> {
1000 match &self.data {
1001 Data::I64(v) => Some(v),
1002 _ => None,
1003 }
1004 }
1005
1006 pub fn as_boxes(&self) -> Option<&[Array]> {
1008 match &self.data {
1009 Data::Box(v) => Some(v),
1010 _ => None,
1011 }
1012 }
1013
1014 pub fn as_f64_slice(&self) -> Option<&[f64]> {
1015 match &self.data {
1016 Data::F64(v) => Some(v),
1017 _ => None,
1018 }
1019 }
1020
1021 pub fn as_ext_slice(&self) -> Option<&[Ext]> {
1023 match &self.data {
1024 Data::Ext(v) => Some(v),
1025 _ => None,
1026 }
1027 }
1028
1029 pub fn as_rat_slice(&self) -> Option<&[Rat]> {
1031 match &self.data {
1032 Data::Rat(v) => Some(v),
1033 _ => None,
1034 }
1035 }
1036
1037 pub fn as_complex_slice(&self) -> Option<&[Cx]> {
1038 match &self.data {
1039 Data::Complex(v) => Some(v),
1040 _ => None,
1041 }
1042 }
1043
1044 pub fn to_complex_vec(&self) -> Option<Vec<Cx>> {
1046 match &self.data {
1047 Data::Bool(v) => Some(v.iter().map(|&x| [x as f64, 0.0]).collect()),
1048 Data::I64(v) => Some(v.iter().map(|&x| [x as f64, 0.0]).collect()),
1049 Data::Ext(v) => Some(v.iter().map(|x| [crate::exact::ext_to_f64(x), 0.0]).collect()),
1050 Data::Rat(v) => Some(v.iter().map(|x| [x.to_f64(), 0.0]).collect()),
1051 Data::F64(v) => Some(v.iter().map(|&x| [x, 0.0]).collect()),
1052 Data::Complex(v) => Some(v.to_vec()),
1053 Data::Char(_) | Data::Symbol(_) | Data::Box(_) => None,
1054 }
1055 }
1056
1057 pub fn to_f64_vec(&self) -> Option<Vec<f64>> {
1059 match &self.data {
1060 Data::Bool(v) => Some(v.iter().map(|&x| x as f64).collect()),
1061 Data::I64(v) => Some(v.iter().map(|&x| x as f64).collect()),
1062 Data::Ext(v) => Some(v.iter().map(crate::exact::ext_to_f64).collect()),
1063 Data::Rat(v) => Some(v.iter().map(Rat::to_f64).collect()),
1064 Data::F64(v) => Some(v.to_vec()),
1065 Data::Complex(_) | Data::Char(_) | Data::Symbol(_) | Data::Box(_) => None,
1068 }
1069 }
1070
1071 pub fn to_i64_vec(&self) -> Option<Vec<i64>> {
1073 match &self.data {
1074 Data::Bool(v) => Some(v.iter().map(|&x| x as i64).collect()),
1075 Data::I64(v) => Some(v.to_vec()),
1076 Data::Ext(v) => v.iter().map(crate::exact::ext_to_i64).collect(),
1079 Data::Rat(v) => {
1080 v.iter().map(|x| x.to_int().as_ref().and_then(crate::exact::ext_to_i64)).collect()
1081 }
1082 Data::F64(v) => {
1083 let mut out = Vec::with_capacity(v.len());
1084 for &x in v.iter() {
1085 if x.fract() != 0.0 || x.abs() >= i64::MAX as f64 {
1086 return None;
1087 }
1088 out.push(x as i64);
1089 }
1090 Some(out)
1091 }
1092 Data::Complex(_) | Data::Char(_) | Data::Symbol(_) | Data::Box(_) => None,
1093 }
1094 }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use super::*;
1100 use std::sync::atomic::{AtomicBool, Ordering};
1101
1102 struct Guard {
1105 values: Vec<i64>,
1106 dropped: Arc<AtomicBool>,
1107 }
1108
1109 impl Drop for Guard {
1110 fn drop(&mut self) {
1111 self.dropped.store(true, Ordering::SeqCst);
1112 }
1113 }
1114
1115 fn foreign_buf(values: Vec<i64>, dropped: Arc<AtomicBool>) -> Buf<i64> {
1116 let guard = Arc::new(Guard { values, dropped });
1117 let ptr = guard.values.as_ptr();
1118 let len = guard.values.len();
1119 unsafe { Buf::foreign(ptr, len, guard) }
1122 }
1123
1124 #[test]
1125 fn owned_buf_derefs_to_its_slice() {
1126 let b: Buf<i64> = vec![1, 2, 3].into();
1127 assert!(!b.is_foreign());
1128 assert_eq!(&b[..], &[1, 2, 3]);
1129 assert_eq!(b.len(), 3);
1130 assert_eq!(b.iter().sum::<i64>(), 6);
1131 }
1132
1133 #[test]
1134 fn empty_buf_is_a_valid_empty_slice() {
1135 let b: Buf<f64> = Buf::new();
1136 assert_eq!(&b[..], &[] as &[f64]);
1137 let f = unsafe { Buf::<f64>::foreign(std::ptr::null(), 0, Arc::new(())) };
1139 assert_eq!(&f[..], &[] as &[f64]);
1140 }
1141
1142 #[test]
1143 fn cloning_an_owned_buf_shares_the_same_memory() {
1144 let b: Buf<i64> = vec![1, 2, 3].into();
1145 let c = b.clone();
1146 assert_eq!(b.as_ptr(), c.as_ptr(), "owned clone copied the elements");
1147 assert_eq!(&c[..], &[1, 2, 3]);
1148 }
1149
1150 #[test]
1151 fn writing_to_a_shared_owned_buf_copies_first() {
1152 let b: Buf<i64> = vec![1, 2, 3].into();
1153 let mut c = b.clone();
1154 c.to_mut()[0] = 99;
1155 assert_eq!(&b[..], &[1, 2, 3], "the other holder saw the write");
1156 assert_eq!(&c[..], &[99, 2, 3]);
1157 assert_ne!(b.as_ptr(), c.as_ptr());
1158 let ptr = c.as_ptr();
1160 c.to_mut()[1] = 98;
1161 assert_eq!(c.as_ptr(), ptr, "unshared write copied");
1162 }
1163
1164 #[test]
1165 fn into_vec_moves_when_sole_holder_and_copies_when_shared() {
1166 let b: Buf<i64> = vec![1, 2, 3].into();
1167 let ptr = b.as_ptr();
1168 let v = b.into_vec();
1169 assert_eq!(v.as_ptr(), ptr, "sole holder copied instead of moving");
1170
1171 let b: Buf<i64> = vec![1, 2, 3].into();
1172 let c = b.clone();
1173 let v = b.into_vec();
1174 assert_eq!(v, vec![1, 2, 3]);
1175 assert_eq!(&c[..], &[1, 2, 3]);
1176 }
1177
1178 #[test]
1179 fn foreign_buf_reads_borrowed_memory_and_keeps_the_owner_alive() {
1180 let dropped = Arc::new(AtomicBool::new(false));
1181 let b = foreign_buf(vec![10, 20, 30], dropped.clone());
1182 assert!(b.is_foreign());
1183 assert_eq!(&b[..], &[10, 20, 30]);
1184 assert!(!dropped.load(Ordering::SeqCst), "owner dropped while borrowed");
1185 drop(b);
1186 assert!(dropped.load(Ordering::SeqCst), "owner leaked after the buffer died");
1187 }
1188
1189 #[test]
1190 fn cloning_a_foreign_buf_shares_the_same_memory() {
1191 let dropped = Arc::new(AtomicBool::new(false));
1192 let b = foreign_buf(vec![1, 2, 3], dropped.clone());
1193 let c = b.clone();
1194 assert!(c.is_foreign());
1195 assert_eq!(b.as_ptr(), c.as_ptr());
1196 drop(b);
1197 assert!(!dropped.load(Ordering::SeqCst), "owner dropped while a clone lives");
1198 assert_eq!(&c[..], &[1, 2, 3]);
1199 }
1200
1201 #[test]
1202 fn slicing_a_foreign_buf_keeps_borrowing() {
1203 let dropped = Arc::new(AtomicBool::new(false));
1204 let b = foreign_buf(vec![1, 2, 3, 4], dropped.clone());
1205 let s = b.slice(1, 3);
1206 assert!(s.is_foreign());
1207 assert_eq!(&s[..], &[2, 3]);
1208 drop(b);
1209 assert_eq!(&s[..], &[2, 3]);
1210 assert!(!dropped.load(Ordering::SeqCst));
1211 }
1212
1213 #[test]
1214 fn mutating_a_foreign_buf_copies_first() {
1215 let dropped = Arc::new(AtomicBool::new(false));
1216 let mut b = foreign_buf(vec![1, 2, 3], dropped.clone());
1217 b.push(4);
1218 assert!(!b.is_foreign());
1219 assert_eq!(&b[..], &[1, 2, 3, 4]);
1220 drop(b);
1222 assert!(dropped.load(Ordering::SeqCst));
1223 }
1224
1225 #[test]
1226 fn copy_on_write_leaves_other_holders_alone() {
1227 let dropped = Arc::new(AtomicBool::new(false));
1228 let b = foreign_buf(vec![1, 2, 3], dropped.clone());
1229 let mut c = b.clone();
1230 c.to_mut()[0] = 99;
1231 assert_eq!(&b[..], &[1, 2, 3]);
1232 assert_eq!(&c[..], &[99, 2, 3]);
1233 }
1234
1235 #[test]
1236 fn foreign_data_slices_without_copying() {
1237 let dropped = Arc::new(AtomicBool::new(false));
1238 let a = Array::new(vec![2, 2], Data::I64(foreign_buf(vec![1, 2, 3, 4], dropped)));
1239 assert!(a.data.is_foreign());
1240 let row = a.item(1);
1241 assert!(row.data.is_foreign());
1242 assert_eq!(row.as_i64_slice(), Some(&[3, 4][..]));
1243 }
1244
1245 #[test]
1246 fn foreign_data_extends_by_copying() {
1247 let dropped = Arc::new(AtomicBool::new(false));
1248 let mut d = Data::I64(foreign_buf(vec![1, 2], dropped));
1249 assert!(d.is_foreign());
1250 assert!(d.extend_from(&Data::I64(vec![3].into())));
1251 assert!(!d.is_foreign());
1252 assert_eq!(d, Data::I64(vec![1, 2, 3].into()));
1253 }
1254}