diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/sheet/cell.rs | 5 | ||||
| -rw-r--r-- | src/sheet/loader/mod.rs (renamed from src/sheet/loader.rs) | 24 | ||||
| -rw-r--r-- | src/sheet/loader/native/csv.rs | 19 | ||||
| -rw-r--r-- | src/sheet/loader/native/mod.rs | 2 |
4 files changed, 42 insertions, 8 deletions
diff --git a/src/sheet/cell.rs b/src/sheet/cell.rs index d723732..6973b96 100644 --- a/src/sheet/cell.rs +++ b/src/sheet/cell.rs @@ -57,7 +57,10 @@ impl From<String> for Cell { impl From<&str> for Cell { fn from(value: &str) -> Self { - Cell::String(value.to_string()) + match value.parse::<f64>() { + Ok(n) => Cell::Number(n), + Err(_) => Cell::String(value.to_string()), + } } } diff --git a/src/sheet/loader.rs b/src/sheet/loader/mod.rs index 35b6da2..0e083fe 100644 --- a/src/sheet/loader.rs +++ b/src/sheet/loader/mod.rs @@ -5,8 +5,12 @@ use once_cell::sync::Lazy; use crate::lua::{ownedfunction::OwnedFunction, runnable::Runnable}; +use self::native::csv::load_csv; + use super::{register::SheetId, tablized::Tablized}; +pub mod native; + #[derive(Default)] pub struct Loader { loaders: HashMap<String, Box<dyn Runnable<String, Tablized>>>, @@ -14,18 +18,24 @@ pub struct Loader { impl Loader { pub fn new() -> Self { - Self { - loaders: HashMap::new(), - } + let mut loaders: HashMap<String, Box<dyn Runnable<String, Tablized>>> = HashMap::new(); + + loaders.insert("csv".to_string(), Box::new(load_csv)); + + Self { loaders } } pub fn load_sheet(&self, path: String, lua: &Lua) -> Option<SheetId> { let p = Path::new(&path); - let loader = self.loaders.get(p.extension()?.to_str()?)?; - match loader.run(path, lua) { - Ok(table) => table.to_sheet(lua).ok(), - Err(_) => None, + if p.is_file() { + let loader = self.loaders.get(p.extension()?.to_str()?)?; + return match loader.run(path, lua) { + Ok(table) => table.to_sheet(lua).ok(), + Err(_) => None, + }; } + + return None; } pub fn add(&mut self, extension: String, func: Box<dyn Runnable<String, Tablized>>) { diff --git a/src/sheet/loader/native/csv.rs b/src/sheet/loader/native/csv.rs new file mode 100644 index 0000000..4a8f05d --- /dev/null +++ b/src/sheet/loader/native/csv.rs @@ -0,0 +1,19 @@ +use std::{fs::File, io::BufReader}; + +use crate::sheet::{cell::Cell, tablized::Tablized}; + +pub fn load_csv(path: String) -> Tablized { + let file = File::open(path).unwrap(); + let reader = BufReader::new(file); + let mut csv_reader = csv::Reader::from_reader(reader); + + let mut table = Vec::new(); + + for result in csv_reader.records() { + if let Ok(record) = result { + table.push(record.iter().map(|s| Cell::from(s)).collect::<Vec<Cell>>()) + } + } + + Tablized::Vector(table) +} diff --git a/src/sheet/loader/native/mod.rs b/src/sheet/loader/native/mod.rs new file mode 100644 index 0000000..41ec797 --- /dev/null +++ b/src/sheet/loader/native/mod.rs @@ -0,0 +1,2 @@ + +pub mod csv; |