Commit 58313362 authored by Christopher Silva's avatar Christopher Silva

add macro to create functions

parent 841ac5e9
......@@ -4,7 +4,7 @@ use std::fmt;
pub enum Cell {
Int(i32),
Float(f32),
String(String),
Text(String),
}
impl fmt::Display for Cell {
......@@ -12,21 +12,7 @@ impl fmt::Display for Cell {
match self {
Cell::Int(i) => write!(fm, "{}", i),
Cell::Float(f) => write!(fm, "{}", f),
Cell::String(s) => write!(fm, "{}", s),
Cell::Text(s) => write!(fm, "{}", s),
}
}
}
impl Cell {
pub fn new_int(value: i32) -> Self {
Cell::Int(value)
}
pub fn new_float(value: f32) -> Self {
Cell::Float(value)
}
pub fn new_string(value: String) -> Self {
Cell::String(value)
}
}
use std::default::Default;
use crate::cell::Cell;
use Cell::*;
use crate::sheet::Range;
struct Acc {
......@@ -28,18 +29,38 @@ impl Acc {
}
}
pub fn sum(cells: Range) -> Cell {
cells.iter()
.flatten()
.fold(Acc::default(), |mut acc, cell| {
match cell {
Some(Cell::Int(i)) => acc.int += i,
Some(Cell::Float(f)) => {
acc.flag = true;
acc.float += f;
},
_ => {},
}
acc
}).finish()
macro_rules! func {
($name:ident, "r->c", $closure:expr) => {
pub fn $name(cells: Range) -> Cell {
cells.iter()
.flatten()
.fold(Acc::default(), $closure)
.finish()
}
};
($name:ident, "c->c", $closure:expr) => {
pub fn $name(cell: Option<&Cell>) -> Cell {
$closure(cell)
}
};
}
func!(sum, "r->c", |mut acc, cell| {
match cell {
Some(Int(i)) => acc.int += i,
Some(Float(f)) => {
acc.flag = true;
acc.float += f;
},
_ => {},
}
acc
});
func!(trunc, "c->c", |cell| {
match cell {
Some(&Float(f)) => Float(f.trunc()),
_ => Float(0.0),
}
});
......@@ -8,14 +8,14 @@ fn main() {
println!("inserting cells");
for i in 0..200 {
for j in 0..200 {
sheet.write_string(i, j, format!("string {} {}", i, j));
sheet.write_text(i, j, format!("text {} {}", i, j));
}
}
println!("rendering ranges");
for i in 0..100 {
for j in 0..100 {
let rendered = sheet.render_range(i, j, 100, 100);
for i in 0..10 {
for j in 0..10 {
let _rendered = sheet.render_range(i, j, 100, 100);
}
}
......
use std::collections::HashMap;
use crate::cell::Cell;
use Cell::*;
pub type Range<'a> = Vec<Vec<Option<&'a Cell>>>;
pub type RenderedRange = Vec<Vec<String>>;
......@@ -24,15 +25,15 @@ impl Sheet {
}
pub fn write_int(&mut self, r: usize, c: usize, value: i32) {
self.cells.insert((r, c), Cell::Int(value));
self.cells.insert((r, c), Int(value));
}
pub fn write_float(&mut self, r: usize, c: usize, value: f32) {
self.cells.insert((r, c), Cell::Float(value));
self.cells.insert((r, c), Float(value));
}
pub fn write_string(&mut self, r: usize, c: usize, value: String) {
self.cells.insert((r, c), Cell::String(value));
pub fn write_text(&mut self, r: usize, c: usize, value: String) {
self.cells.insert((r, c), Text(value));
}
pub fn range(&self, r: usize, c: usize, h: usize, w: usize) -> Range {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment