1use crate::vector::ops::{Asum, Axpy, Copy, Dot, Iamax, Nrm2, Scal};
7use num::traits::NumCast;
8use num_complex::{Complex32, Complex64};
9
10pub mod ll;
11pub mod ops;
12
13pub trait Vector<T> {
15 fn inc(&self) -> u32 {
18 1
19 }
20 fn len(&self) -> u32;
22 fn as_ptr(&self) -> *const T;
24 fn as_mut_ptr(&mut self) -> *mut T;
26 fn is_empty(&self) -> bool {
28 self.len() == 0u32
29 }
30}
31
32impl<'a, T> Into<Vec<T>> for &'a dyn Vector<T>
33where
34 T: Copy,
35{
36 fn into(self) -> Vec<T> {
37 let n = self.len() as usize;
38
39 let mut x = Vec::with_capacity(n);
40 unsafe {
41 x.set_len(n);
42 }
43 Copy::copy(self, &mut x);
44
45 x
46 }
47}
48
49pub trait VectorOperations<T>: Sized + Vector<T>
50where
51 T: Copy + Axpy + Scal + Dot + Nrm2 + Asum + Iamax,
52{
53 fn update(&mut self, alpha: &T, x: &dyn Vector<T>) -> &mut Self {
54 Axpy::axpy(alpha, x, self);
55 self
56 }
57
58 fn scale(&mut self, alpha: &T) -> &mut Self {
59 Scal::scal(alpha, self);
60 self
61 }
62
63 fn dot(&self, x: &dyn Vector<T>) -> T {
64 Dot::dot(self, x)
65 }
66
67 fn abs_sum(&self) -> T {
68 Asum::asum(self)
69 }
70
71 fn norm(&self) -> T {
72 Nrm2::nrm2(self)
73 }
74
75 fn max_index(&self) -> usize {
76 Iamax::iamax(self)
77 }
78}
79
80impl<T> Vector<T> for Vec<T> {
81 fn len(&self) -> u32 {
82 let l: Option<u32> = NumCast::from(Vec::len(self));
83 match l {
84 Some(l) => l,
85 None => panic!(),
86 }
87 }
88
89 fn as_ptr(&self) -> *const T {
90 self[..].as_ptr()
91 }
92
93 fn as_mut_ptr(&mut self) -> *mut T {
94 (&mut self[..]).as_mut_ptr()
95 }
96}
97
98impl<T> Vector<T> for [T] {
99 fn len(&self) -> u32 {
100 let l: Option<u32> = NumCast::from(<[T]>::len(self));
101 match l {
102 Some(l) => l,
103 None => panic!(),
104 }
105 }
106
107 fn as_ptr(&self) -> *const T {
108 <[T]>::as_ptr(self)
109 }
110
111 fn as_mut_ptr(&mut self) -> *mut T {
112 <[T]>::as_mut_ptr(self)
113 }
114}
115
116macro_rules! operations_impl(
117 ($v: ident, $($t: ty), +) => (
118 $( impl VectorOperations<$t> for $v<$t> {} )+
119 )
120);
121
122operations_impl!(Vec, f32, f64, Complex32, Complex64);
123