Reduce again the number of match calls (#7815)

- Reduce the number of match calls (see commit messages)
- A few miscellaneous improvements
This commit is contained in:
Hofer-Julian
2023-01-24 12:23:42 +01:00
committed by GitHub
parent 0bb2e47c98
commit 41306aa7e0
49 changed files with 467 additions and 634 deletions

View File

@ -98,32 +98,26 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
let start: isize = if start.is_empty() || start == "_" {
0
} else {
match start.trim().parse() {
Ok(s) => s,
Err(_) => {
return Err(ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
))
}
}
start.trim().parse().map_err(|_| {
ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
)
})?
};
let end: isize = if end.is_empty() || end == "_" {
isize::max_value()
} else {
match end.trim().parse() {
Ok(s) => s,
Err(_) => {
return Err(ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
))
}
}
end.trim().parse().map_err(|_| {
ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
)
})?
};
Ok((start, end, span))
}

View File

@ -129,18 +129,15 @@ impl Command for Histogram {
let span = call.head;
let data_as_value = input.into_value(span);
// `input` is not a list, here we can return an error.
match data_as_value.as_list() {
Ok(list_value) => run_histogram(
list_value.to_vec(),
column_name,
frequency_column_name,
calc_method,
span,
// Note that as_list() filters out Value::Error here.
data_as_value.expect_span(),
),
Err(e) => Err(e),
}
run_histogram(
data_as_value.as_list()?.to_vec(),
column_name,
frequency_column_name,
calc_method,
span,
// Note that as_list() filters out Value::Error here.
data_as_value.expect_span(),
)
}
}

View File

@ -234,12 +234,7 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
span,
},
Value::Error { error } => Value::String {
val: {
match into_code(error) {
Some(code) => code,
None => "".to_string(),
}
},
val: into_code(error).unwrap_or_default(),
span,
},
Value::Nothing { .. } => Value::String {

View File

@ -107,12 +107,7 @@ impl SQLiteDatabase {
}
pub fn open_connection(&self) -> Result<Connection, rusqlite::Error> {
let conn = match Connection::open(&self.path) {
Ok(conn) => conn,
Err(err) => return Err(err),
};
Ok(conn)
Connection::open(&self.path)
}
pub fn get_tables(&self, conn: &Connection) -> Result<Vec<DbTable>, rusqlite::Error> {
@ -582,18 +577,13 @@ mod test {
}
pub fn open_connection_in_memory() -> Result<Connection, ShellError> {
let db = match Connection::open_in_memory() {
Ok(conn) => conn,
Err(err) => {
return Err(ShellError::GenericError(
"Failed to open SQLite connection in memory".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
))
}
};
Ok(db)
Connection::open_in_memory().map_err(|err| {
ShellError::GenericError(
"Failed to open SQLite connection in memory".into(),
err.to_string(),
Some(Span::test_data()),
None,
Vec::new(),
)
})
}

View File

@ -51,9 +51,8 @@ impl Command for ListDF {
let vals = vals
.into_iter()
.filter_map(|(name, value)| match NuDataFrame::try_from_value(value) {
Ok(df) => Some((name, df)),
Err(_) => None,
.filter_map(|(name, value)| {
NuDataFrame::try_from_value(value).ok().map(|df| (name, df))
})
.map(|(name, df)| {
let name = Value::String {

View File

@ -103,14 +103,13 @@ fn command(
let type_id = match &type_option {
Some(ref t) => Some((t.item.to_owned(), "Invalid type", t.span)),
None => match file.item.extension() {
Some(e) => Some((
None => file.item.extension().map(|e| {
(
e.to_string_lossy().into_owned(),
"Invalid extension",
file.span,
)),
None => None,
},
)
}),
};
match type_id {

View File

@ -71,32 +71,30 @@ pub fn test_dataframe(cmds: Vec<Box<dyn Command + 'static>>) {
let mut stack = Stack::new();
match eval_block(
let result = eval_block(
&engine_state,
&mut stack,
&block,
PipelineData::empty(),
true,
true,
) {
Err(err) => panic!("test eval error in `{}`: {:?}", example.example, err),
Ok(result) => {
let result = result.into_value(Span::test_data());
println!("input: {}", example.example);
println!("result: {:?}", result);
println!("done: {:?}", start.elapsed());
)
.unwrap_or_else(|err| panic!("test eval error in `{}`: {:?}", example.example, err))
.into_value(Span::test_data());
// Note. Value implements PartialEq for Bool, Int, Float, String and Block
// If the command you are testing requires to compare another case, then
// you need to define its equality in the Value struct
if let Some(expected) = example.result {
if result != expected {
panic!(
"the example result is different to expected value: {:?} != {:?}",
result, expected
)
}
}
println!("input: {}", example.example);
println!("result: {:?}", result);
println!("done: {:?}", start.elapsed());
// Note. Value implements PartialEq for Bool, Int, Float, String and Block
// If the command you are testing requires to compare another case, then
// you need to define its equality in the Value struct
if let Some(expected) = example.result {
if result != expected {
panic!(
"the example result is different to expected value: {:?} != {:?}",
result, expected
)
}
}
}

View File

@ -306,22 +306,19 @@ mod test_examples {
engine_state: &mut Box<EngineState>,
) -> Option<Value> {
let (mut block, delta) = parse(src, engine_state);
match block.pipelines.len() {
1 => {
let n_expressions = block.pipelines[0].elements.len();
block.pipelines[0].elements.truncate(&n_expressions - 1);
if block.pipelines.len() == 1 {
let n_expressions = block.pipelines[0].elements.len();
block.pipelines[0].elements.truncate(&n_expressions - 1);
if !block.pipelines[0].elements.is_empty() {
let empty_input = PipelineData::empty();
Some(eval_block(block, empty_input, cwd, engine_state, delta))
} else {
Some(Value::nothing(Span::test_data()))
}
}
_ => {
// E.g. multiple semicolon-separated statements
None
if !block.pipelines[0].elements.is_empty() {
let empty_input = PipelineData::empty();
Some(eval_block(block, empty_input, cwd, engine_state, delta))
} else {
Some(Value::nothing(Span::test_data()))
}
} else {
// E.g. multiple semicolon-separated statements
None
}
}
}

View File

@ -26,10 +26,7 @@ impl NuProgressBar {
}
};
let total_bytes = match total_bytes {
Some(total_size) => total_size,
_ => 0,
};
let total_bytes = total_bytes.unwrap_or_default();
let new_progress_bar = ProgressBar::new(total_bytes);
new_progress_bar.set_style(

View File

@ -45,16 +45,13 @@ pub fn sort_value_in_place(
insensitive: bool,
natural: bool,
) -> Result<(), ShellError> {
match val {
Value::List { vals, span } => {
sort(vals, sort_columns, *span, insensitive, natural)?;
if !ascending {
vals.reverse();
}
Ok(())
if let Value::List { vals, span } = val {
sort(vals, sort_columns, *span, insensitive, natural)?;
if !ascending {
vals.reverse();
}
_ => Ok(()),
}
Ok(())
}
pub fn sort(
@ -102,10 +99,9 @@ pub fn sort(
let mut vals = vec![];
for item in vec.iter() {
for col in &sort_columns {
let val = match item.get_data_by_key(col) {
Some(v) => v,
None => Value::nothing(Span::unknown()),
};
let val = item
.get_data_by_key(col)
.unwrap_or_else(|| Value::nothing(Span::unknown()));
vals.push(val);
}
}