nushell/src/plugins/sum.rs

94 lines
2.9 KiB
Rust
Raw Normal View History

2019-07-26 20:40:00 +02:00
use indexmap::IndexMap;
use nu::{
serve_plugin, CallInfo, CommandConfig, Plugin, Primitive, ReturnSuccess, ReturnValue,
2019-08-01 03:58:42 +02:00
ShellError, Tag, Tagged, Value,
2019-07-26 20:40:00 +02:00
};
struct Sum {
2019-08-01 03:58:42 +02:00
total: Option<Tagged<Value>>,
2019-07-26 20:40:00 +02:00
}
impl Sum {
fn new() -> Sum {
Sum { total: None }
}
2019-08-01 03:58:42 +02:00
fn sum(&mut self, value: Tagged<Value>) -> Result<(), ShellError> {
2019-07-26 20:40:00 +02:00
match value.item {
Value::Primitive(Primitive::Int(i)) => {
match self.total {
2019-08-01 03:58:42 +02:00
Some(Tagged {
2019-07-26 20:40:00 +02:00
item: Value::Primitive(Primitive::Int(j)),
2019-08-01 03:58:42 +02:00
tag: Tag { span },
2019-07-26 20:40:00 +02:00
}) => {
//TODO: handle overflow
2019-08-01 03:58:42 +02:00
self.total = Some(Tagged::from_item(Value::int(i + j), span));
2019-07-26 20:40:00 +02:00
Ok(())
}
None => {
self.total = Some(value);
Ok(())
}
_ => Err(ShellError::string(format!(
"Could not sum non-integer or unrelated types"
))),
}
}
Value::Primitive(Primitive::Bytes(b)) => {
match self.total {
2019-08-01 03:58:42 +02:00
Some(Tagged {
2019-07-26 20:40:00 +02:00
item: Value::Primitive(Primitive::Bytes(j)),
2019-08-01 03:58:42 +02:00
tag: Tag { span },
2019-07-26 20:40:00 +02:00
}) => {
//TODO: handle overflow
2019-08-01 03:58:42 +02:00
self.total = Some(Tagged::from_item(Value::bytes(b + j), span));
2019-07-26 20:40:00 +02:00
Ok(())
}
None => {
self.total = Some(value);
Ok(())
}
_ => Err(ShellError::string(format!(
"Could not sum non-integer or unrelated types"
))),
}
}
x => Err(ShellError::string(format!(
"Unrecognized type in stream: {:?}",
x
))),
}
}
}
impl Plugin for Sum {
fn config(&mut self) -> Result<CommandConfig, ShellError> {
Ok(CommandConfig {
name: "sum".to_string(),
positional: vec![],
is_filter: true,
is_sink: false,
named: IndexMap::new(),
rest_positional: true,
})
}
fn begin_filter(&mut self, _: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])
2019-07-26 20:40:00 +02:00
}
2019-08-01 03:58:42 +02:00
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
2019-07-26 20:40:00 +02:00
self.sum(input)?;
Ok(vec![])
}
fn end_filter(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
match self.total {
None => Ok(vec![]),
Some(ref v) => Ok(vec![ReturnSuccess::value(v.clone())]),
}
}
}
fn main() {
serve_plugin(&mut Sum::new());
}