ohsl/vector/
mod.rs

1pub mod arithmetic;
2pub mod functions;
3pub mod operations;
4pub mod vec_f64;
5pub mod vec_cmplx;
6
7use std::{fmt, fs::File, io::Write};
8pub use crate::traits::{Number, Zero, One};
9pub use crate::complex::Complex;
10
11#[derive(PartialEq)]
12pub struct Vector<T> {
13    pub vec: Vec<T>,
14}
15
16pub type Vec64 = Vector<f64>;
17
18impl<T> Vector<T> {
19    /// Create a new vector of unspecified size
20    #[inline]
21    pub const fn empty() -> Self {
22        let vec = Vec::<T>::new();
23        Vector { vec }
24    }
25
26    /// Create a vector from an std::vec::Vec
27    #[inline]
28    pub fn create( vec: Vec<T> ) -> Self {
29        Vector { vec }
30    }
31
32    /// Return the size of the vector 
33    #[inline]
34    pub fn size(&self) -> usize {
35        self.vec.len()
36    }
37}
38
39impl<T: Clone> Vector<T> {
40    /// Create a new vector of specified size
41    #[inline]
42    pub fn new( size: usize, elem: T ) -> Self {
43        let vec = vec![ elem; size ];
44        Vector { vec }
45    }
46}
47
48impl<T: Clone + Number> Vector<T> {
49    /// Create a vector of zeros 
50    #[inline]
51    pub fn zeros( size: usize ) -> Self {
52        let vec = vec![ T::zero(); size ];
53        Vector{ vec }
54    }
55
56    /// Create a vector of ones
57    #[inline]
58    pub fn ones( size: usize ) -> Self {
59        let vec = vec![ T::one(); size ];
60        Vector{ vec }
61    }
62}
63
64impl<T: Clone> Clone for Vector<T> {
65    /// Clone the vector
66    #[inline]
67    fn clone(&self) -> Self {
68        Self::create( self.vec.clone() )
69    }
70}
71
72impl<T: fmt::Display> Vector<T> {
73    /// Print the vector to a file
74    #[inline]
75    pub fn output(&self, filename: &str) {
76        let mut f = File::create(filename).expect("Unable to create file");
77        for i in 0..self.size() {                                                                                                                                                                  
78            writeln!(f, "{}", self.vec[i]).unwrap();                                                                                                                            
79        }
80    }
81}
82
83impl<T> fmt::Debug for Vector<T> where
84    T: fmt::Debug
85{
86    /// Format the output [ v_0, v_1, ... ]
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "{:?}", self.vec )
89    }
90}
91
92impl<T> fmt::Display for Vector<T> where
93    T: fmt::Debug
94{
95    /// Format the output [ v_0, v_1, ... ]
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(f, "{:?}", self.vec )
98    }
99}