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
use std::error::Error;

type DataInteger = i32;
type DataText = String;

#[derive(Debug)]
struct Column<T> {
    name: String,
    data: Vec<T>,
}

#[derive(Debug)]
pub struct DataFrame {
    columns: Vec<DataColumn>,
}

#[derive(Debug)]
enum DataColumn {
    IntegerDataColumn(Column<DataInteger>),
    TextDataColumn(Column<DataText>),
}

#[derive(Debug)]
struct DataFrameError {
    msg: String,
}

impl DataFrameError {
    fn create(msg: &str) -> Box<dyn Error> {
        Box::new(DataFrameError {
            msg: msg.to_owned(),
        })
    }
}

impl std::fmt::Display for DataFrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.msg)
    }
}

impl Error for DataFrameError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        // Generic error, underlying cause isn't tracked.
        None
    }
}

impl DataFrame {
    pub fn new(
        column_names: Vec<String>,
        data: Vec<DataCell>,
    ) -> Result<DataFrame, Box<dyn Error>> {
        let num_cols = column_names.len();
        let mut column_types = vec![];

        // Figure out the column types from the data
        for i in 0..num_cols {
            if i >= data.len() {
                // Default to integer
                column_types.push(DataTypes::Integer);
            } else {
                column_types.push(data[i].data_type());
            }
        }

        if data.len() % num_cols != 0 {
            return Err(DataFrameError::create(
                "length of data provided did not match expected number of columns",
            ));
        }

        // create columns based on column types
        let mut cols = Vec::<DataColumn>::new();
        for (i, v) in column_types.iter().enumerate() {
            match v {
                DataTypes::Integer => {
                    cols.push(DataColumn::IntegerDataColumn(Column::<DataInteger> {
                        name: column_names[i].clone(),
                        data: vec![],
                    }))
                }
                DataTypes::Text => cols.push(DataColumn::TextDataColumn(Column::<DataText> {
                    name: column_names[i].clone(),
                    data: vec![],
                })),
            }
        }

        // Go through each data cell and if they can be added to the appropriate column, do it
        for (i, cell) in data.iter().enumerate() {
            let col_index = i % num_cols;
            match &mut cols[col_index] {
                DataColumn::IntegerDataColumn(col) => match &cell {
                    DataCell::IntegerDataCell(val) => col.data.push(val.clone()),
                    _ => {
                        return Err(DataFrameError::create(
                            "data cell type did not match integer column type",
                        ))
                    }
                },
                DataColumn::TextDataColumn(col) => match &cell {
                    DataCell::TextDataCell(val) => col.data.push(val.clone()),
                    _ => {
                        return Err(DataFrameError::create(
                            "data cell type did not match text column type",
                        ))
                    }
                },
            }
        }

        Ok(DataFrame { columns: cols })
    }
}

#[derive(Debug)]
enum DataTypes {
    Integer,
    Text,
}

#[derive(Debug)]
pub enum DataCell {
    IntegerDataCell(DataInteger),
    TextDataCell(DataText),
}

impl DataCell {
    fn data_type(&self) -> DataTypes {
        match self {
            DataCell::IntegerDataCell(_) => DataTypes::Integer,
            DataCell::TextDataCell(_) => DataTypes::Text,
        }
    }
}

impl From<DataInteger> for DataCell {
    fn from(v: DataInteger) -> Self {
        DataCell::IntegerDataCell(v)
    }
}

impl From<DataText> for DataCell {
    fn from(v: DataText) -> Self {
        DataCell::TextDataCell(v)
    }
}

impl From<&str> for DataCell {
    fn from(v: &str) -> Self {
        DataCell::TextDataCell(v.to_owned())
    }
}

#[macro_export]
macro_rules! data {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::<DataCell>::new();
            $(
                temp_vec.push(DataCell::from($x));
            )*
            temp_vec
        }
    };
}

#[macro_export]
macro_rules! columns {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::<String>::new();
            $(
                temp_vec.push($x.to_owned());
            )*
            temp_vec
        }
    };
}