From cde92a9fb98f3b16b0537845fc244eb6e469a030 Mon Sep 17 00:00:00 2001 From: Thibaut Brandscheid Date: Fri, 6 Dec 2019 16:28:26 +0100 Subject: [PATCH] Fix most Clippy performance warnings command used: cargo clippy -- -W clippy::perf --- crates/nu-source/src/meta.rs | 4 +- crates/nu-source/src/pretty.rs | 2 +- src/cli.rs | 10 ++-- src/commands/classified/external.rs | 14 ++--- src/commands/command.rs | 2 +- src/commands/enter.rs | 2 +- src/commands/evaluate_by.rs | 2 +- src/commands/fetch.rs | 16 +++--- src/commands/from_bson.rs | 4 +- src/commands/from_ini.rs | 2 +- src/commands/from_sqlite.rs | 2 +- src/commands/from_xml.rs | 6 +-- src/commands/get.rs | 6 +-- src/commands/group_by.rs | 2 +- src/commands/help.rs | 14 ++--- src/commands/histogram.rs | 8 +-- src/commands/map_max_by.rs | 4 +- src/commands/open.rs | 18 +++---- src/commands/pick.rs | 2 +- src/commands/pivot.rs | 2 +- src/commands/post.rs | 16 +++--- src/commands/range.rs | 20 ++++--- src/commands/reduce_by.rs | 4 +- src/commands/reject.rs | 2 +- src/commands/save.rs | 4 +- src/commands/split_column.rs | 11 +--- src/commands/t_sort_by.rs | 8 +-- src/commands/to_bson.rs | 53 ++++++++++--------- src/commands/to_delimited_data.rs | 39 +++++++------- src/commands/to_json.rs | 2 +- src/commands/to_sqlite.rs | 2 +- src/commands/to_toml.rs | 2 +- src/commands/which_.rs | 2 +- src/context.rs | 4 +- src/data/base.rs | 6 +-- src/data/base/property_get.rs | 16 +++--- src/data/base/shape.rs | 35 +++++++------ src/data/command.rs | 2 +- src/data/dict.rs | 4 +- src/data/primitive.rs | 33 ++++++------ src/data/value.rs | 2 +- src/deserializer.rs | 22 ++++---- src/evaluate/evaluator.rs | 6 +-- src/evaluate/operator.rs | 4 +- src/format/entries.rs | 2 +- src/format/generic.rs | 5 +- src/format/table.rs | 81 +++++++++++++++-------------- src/plugins/format.rs | 2 +- src/plugins/inc.rs | 58 +++++++++------------ src/plugins/parse.rs | 4 +- src/plugins/str.rs | 30 +++++------ src/shell/completer.rs | 6 +-- src/shell/filesystem_shell.rs | 20 ++++--- src/shell/help_shell.rs | 17 +++--- src/shell/value_shell.rs | 14 +++-- src/stream.rs | 2 +- src/utils.rs | 8 +-- 57 files changed, 320 insertions(+), 350 deletions(-) diff --git a/crates/nu-source/src/meta.rs b/crates/nu-source/src/meta.rs index ea89b5df5..70012cc63 100644 --- a/crates/nu-source/src/meta.rs +++ b/crates/nu-source/src/meta.rs @@ -38,7 +38,7 @@ impl Spanned { pub fn items<'a, U>( items: impl Iterator>, ) -> impl Iterator { - items.into_iter().map(|item| &item.item[..]) + items.map(|item| &item.item[..]) } } @@ -156,7 +156,7 @@ impl Tagged { Tagged { item: self.item, - tag: tag, + tag, } } diff --git a/crates/nu-source/src/pretty.rs b/crates/nu-source/src/pretty.rs index 12b201c84..b340e3930 100644 --- a/crates/nu-source/src/pretty.rs +++ b/crates/nu-source/src/pretty.rs @@ -316,7 +316,7 @@ impl DebugDocBuilder { result = result + item; } - result.into() + result } fn styled(string: impl std::fmt::Display, style: ShellStyle) -> DebugDocBuilder { diff --git a/src/cli.rs b/src/cli.rs index 0daed4e1f..8f44c377e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -38,7 +38,7 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel let request = JsonRpc::new("config", Vec::::new()); let request_raw = serde_json::to_string(&request)?; - stdin.write(format!("{}\n", request_raw).as_bytes())?; + stdin.write_all(format!("{}\n", request_raw).as_bytes())?; let path = dunce::canonicalize(path)?; let mut input = String::new(); @@ -58,7 +58,7 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel let name = params.name.clone(); let fname = fname.to_string(); - if let Some(_) = context.get_command(&name) { + if context.get_command(&name).is_some() { trace!("plugin {:?} already loaded.", &name); } else { if params.is_filter { @@ -222,7 +222,7 @@ impl History { p.push(FNAME); p }) - .unwrap_or(PathBuf::from(FNAME)) + .unwrap_or_else(|_| PathBuf::from(FNAME)) } } @@ -609,8 +609,8 @@ fn classify_pipeline( context: &Context, source: &Text, ) -> Result { - let mut pipeline_list = vec![pipeline.clone()]; - let mut iterator = TokensIterator::all(&mut pipeline_list, source.clone(), pipeline.span()); + let pipeline_list = vec![pipeline.clone()]; + let mut iterator = TokensIterator::all(&pipeline_list, source.clone(), pipeline.span()); let result = expand_syntax( &PipelineShape, diff --git a/src/commands/classified/external.rs b/src/commands/classified/external.rs index 9211b20dd..463d50c3d 100644 --- a/src/commands/classified/external.rs +++ b/src/commands/classified/external.rs @@ -68,7 +68,7 @@ pub(crate) async fn run_external_command( trace!(target: "nu::run::external", "-> {}", command.name); trace!(target: "nu::run::external", "inputs = {:?}", inputs); - let mut arg_string = format!("{}", command.name); + let mut arg_string = command.name.to_owned(); for arg in command.args.iter() { arg_string.push_str(&arg); } @@ -170,11 +170,11 @@ pub(crate) async fn run_external_command( if let Ok(mut popen) = popen { match stream_next { StreamNext::Last => { - let _ = popen.detach(); + popen.detach(); loop { match popen.poll() { None => { - let _ = std::thread::sleep(std::time::Duration::new(0, 100000000)); + std::thread::sleep(std::time::Duration::new(0, 100_000_000)); } _ => { let _ = popen.terminate(); @@ -185,12 +185,12 @@ pub(crate) async fn run_external_command( Ok(ClassifiedInputStream::new()) } StreamNext::External => { - let _ = popen.detach(); + popen.detach(); let stdout = popen.stdout.take().unwrap(); Ok(ClassifiedInputStream::from_stdout(stdout)) } StreamNext::Internal => { - let _ = popen.detach(); + popen.detach(); let stdout = popen.stdout.take().unwrap(); let file = futures::io::AllowStdIo::new(stdout); let stream = Framed::new(file, LinesCodec {}); @@ -201,10 +201,10 @@ pub(crate) async fn run_external_command( } } } else { - return Err(ShellError::labeled_error( + Err(ShellError::labeled_error( "Command not found", "command not found", name_tag, - )); + )) } } diff --git a/src/commands/command.rs b/src/commands/command.rs index 9be654ce0..691a90bf1 100644 --- a/src/commands/command.rs +++ b/src/commands/command.rs @@ -566,7 +566,7 @@ impl WholeStreamCommand for FnFilterCommand { ); match func(args) { - Err(err) => return OutputStream::from(vec![Err(err)]).values, + Err(err) => OutputStream::from(vec![Err(err)]).values, Ok(stream) => stream.values, } }); diff --git a/src/commands/enter.rs b/src/commands/enter.rs index bbd9ceac0..d49989664 100644 --- a/src/commands/enter.rs +++ b/src/commands/enter.rs @@ -47,7 +47,7 @@ impl PerItemCommand for Enter { let tag_clone = tag.clone(); if location.starts_with("help") { - let spec = location_string.split(":").collect::>(); + let spec = location_string.split(':').collect::>(); let (_, command) = (spec[0], spec[1]); diff --git a/src/commands/evaluate_by.rs b/src/commands/evaluate_by.rs index 2b77cca80..79a06ee1b 100644 --- a/src/commands/evaluate_by.rs +++ b/src/commands/evaluate_by.rs @@ -94,7 +94,7 @@ pub fn evaluate( .. } => { let datasets: Vec<_> = datasets - .into_iter() + .iter() .map(|subsets| match subsets { Value { value: UntaggedValue::Table(subsets), diff --git a/src/commands/fetch.rs b/src/commands/fetch.rs index ddb0587a1..b98625f63 100644 --- a/src/commands/fetch.rs +++ b/src/commands/fetch.rs @@ -129,7 +129,7 @@ pub async fn fetch( location: &str, span: Span, ) -> Result<(Option, UntaggedValue, Tag), ShellError> { - if let Err(_) = url::Url::parse(location) { + if url::Url::parse(location).is_err() { return Err(ShellError::labeled_error( "Incomplete or incorrect url", "expected a full url", @@ -275,19 +275,17 @@ pub async fn fetch( } None => Ok(( None, - UntaggedValue::string(format!("No content type found")), + UntaggedValue::string("No content type found".to_owned()), Tag { span, anchor: Some(AnchorLocation::Url(location.to_string())), }, )), }, - Err(_) => { - return Err(ShellError::labeled_error( - "URL could not be opened", - "url not found", - span, - )); - } + Err(_) => Err(ShellError::labeled_error( + "URL could not be opened", + "url not found", + span, + )), } } diff --git a/src/commands/from_bson.rs b/src/commands/from_bson.rs index 1ad11f44c..cac3f52ff 100644 --- a/src/commands/from_bson.rs +++ b/src/commands/from_bson.rs @@ -30,7 +30,7 @@ impl WholeStreamCommand for FromBSON { } } -fn bson_array(input: &Vec, tag: Tag) -> Result, ShellError> { +fn bson_array(input: &[Bson], tag: Tag) -> Result, ShellError> { let mut out = vec![]; for value in input { @@ -81,7 +81,7 @@ fn convert_bson_value_to_nu_value(v: &Bson, tag: impl Into) -> Result, tag: impl Into) -> Value { let mut second = TaggedDictBuilder::new(tag); - for (key, value) in v.into_iter() { + for (key, value) in v.iter() { second.insert_untagged(key.clone(), Primitive::String(value.clone())); } diff --git a/src/commands/from_sqlite.rs b/src/commands/from_sqlite.rs index 0bd1bd51d..afff666f9 100644 --- a/src/commands/from_sqlite.rs +++ b/src/commands/from_sqlite.rs @@ -97,7 +97,7 @@ fn convert_sqlite_row_to_nu_value( convert_sqlite_value_to_nu_value(row.get_raw(i), tag.clone()), ); } - return Ok(collected.into_value()); + Ok(collected.into_value()) } fn convert_sqlite_value_to_nu_value(value: ValueRef, tag: impl Into + Clone) -> Value { diff --git a/src/commands/from_xml.rs b/src/commands/from_xml.rs index 83e8edd6b..be8f45180 100644 --- a/src/commands/from_xml.rs +++ b/src/commands/from_xml.rs @@ -45,11 +45,7 @@ fn from_node_to_value<'a, 'd>(n: &roxmltree::Node<'a, 'd>, tag: impl Into) value: UntaggedValue::Primitive(Primitive::String(f)), .. } => { - if f.trim() == "" { - false - } else { - true - } + !f.trim().is_empty() // non-whitespace characters? } _ => true, }) diff --git a/src/commands/get.rs b/src/commands/get.rs index 8de42c339..92b1568f5 100644 --- a/src/commands/get.rs +++ b/src/commands/get.rs @@ -70,7 +70,7 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result Result {} } - return error; + error }), ) } @@ -100,7 +100,7 @@ pub fn get( GetArgs { rest: mut fields }: GetArgs, RunnableContext { input, .. }: RunnableContext, ) -> Result { - if fields.len() == 0 { + if fields.is_empty() { let stream = async_stream! { let values = input.values; pin_mut!(values); diff --git a/src/commands/group_by.rs b/src/commands/group_by.rs index 60ad2875e..55afb1fe5 100644 --- a/src/commands/group_by.rs +++ b/src/commands/group_by.rs @@ -84,7 +84,7 @@ pub fn group( possible_matches.sort(); - if possible_matches.len() > 0 { + if !possible_matches.is_empty() { return Err(ShellError::labeled_error( "Unknown column", format!("did you mean '{}'?", possible_matches[0].1), diff --git a/src/commands/help.rs b/src/commands/help.rs index 0d438acd2..fb612b976 100644 --- a/src/commands/help.rs +++ b/src/commands/help.rs @@ -82,16 +82,16 @@ impl PerItemCommand for Help { } if signature.rest_positional.is_some() { - one_liner.push_str(&format!(" ...args",)); + one_liner.push_str(" ...args"); } - if signature.named.len() > 0 { + if !signature.named.is_empty() { one_liner.push_str("{flags} "); } long_desc.push_str(&format!("\nUsage:\n > {}\n", one_liner)); - if signature.positional.len() > 0 || signature.rest_positional.is_some() { + if !signature.positional.is_empty() || signature.rest_positional.is_some() { long_desc.push_str("\nparameters:\n"); for positional in signature.positional { match positional.0 { @@ -117,7 +117,7 @@ impl PerItemCommand for Help { )); } } - if signature.named.len() > 0 { + if !signature.named.is_empty() { long_desc.push_str("\nflags:\n"); for (flag, ty) in signature.named { match ty.0 { @@ -125,7 +125,7 @@ impl PerItemCommand for Help { long_desc.push_str(&format!( " --{}{} {}\n", flag, - if ty.1.len() > 0 { ":" } else { "" }, + if !ty.1.is_empty() { ":" } else { "" }, ty.1 )); } @@ -134,7 +134,7 @@ impl PerItemCommand for Help { " --{} <{}> (required parameter){} {}\n", flag, m.display(), - if ty.1.len() > 0 { ":" } else { "" }, + if !ty.1.is_empty() { ":" } else { "" }, ty.1 )); } @@ -143,7 +143,7 @@ impl PerItemCommand for Help { " --{} <{}>{} {}\n", flag, o.display(), - if ty.1.len() > 0 { ":" } else { "" }, + if !ty.1.is_empty() { ":" } else { "" }, ty.1 )); } diff --git a/src/commands/histogram.rs b/src/commands/histogram.rs index da550fbee..1fcd7f932 100644 --- a/src/commands/histogram.rs +++ b/src/commands/histogram.rs @@ -88,7 +88,7 @@ pub fn histogram( let column = (*column_name).clone(); if let Value { value: UntaggedValue::Table(start), .. } = datasets.get(0).unwrap() { - for percentage in start.into_iter() { + for percentage in start.iter() { let mut fact = TaggedDictBuilder::new(&name); let value: Tagged = group_labels.get(idx).unwrap().clone(); @@ -99,7 +99,7 @@ pub fn histogram( fact.insert_untagged(&frequency_column_name, UntaggedValue::string(string)); } - idx = idx + 1; + idx += 1; yield ReturnSuccess::value(fact.into_value()); } @@ -121,14 +121,14 @@ fn percentages(values: &Value, max: Value, tag: impl Into) -> Result { let datasets: Vec<_> = datasets - .into_iter() + .iter() .map(|subsets| match subsets { Value { value: UntaggedValue::Table(data), .. } => { let data = - data.into_iter() + data.iter() .map(|d| match d { Value { value: UntaggedValue::Primitive(Primitive::Int(n)), diff --git a/src/commands/map_max_by.rs b/src/commands/map_max_by.rs index f2aa3650a..fcea4603a 100644 --- a/src/commands/map_max_by.rs +++ b/src/commands/map_max_by.rs @@ -84,13 +84,13 @@ pub fn map_max( .. } => { let datasets: Vec<_> = datasets - .into_iter() + .iter() .map(|subsets| match subsets { Value { value: UntaggedValue::Table(data), .. } => { - let data = data.into_iter().fold(0, |acc, value| match value { + let data = data.iter().fold(0, |acc, value| match value { Value { value: UntaggedValue::Primitive(Primitive::Int(n)), .. diff --git a/src/commands/open.rs b/src/commands/open.rs index 7b504e9ab..1abc7c462 100644 --- a/src/commands/open.rs +++ b/src/commands/open.rs @@ -44,7 +44,7 @@ fn run( ) -> Result { let shell_manager = &raw_args.shell_manager; let cwd = PathBuf::from(shell_manager.path()); - let full_path = PathBuf::from(cwd); + let full_path = cwd; let path = call_info.args.nth(0).ok_or_else(|| { ShellError::labeled_error( @@ -243,20 +243,18 @@ pub async fn fetch( } } }, - Err(_) => { - return Err(ShellError::labeled_error( - "File could not be opened", - "file not found", - span, - )); - } + Err(_) => Err(ShellError::labeled_error( + "File could not be opened", + "file not found", + span, + )), } } else { - return Err(ShellError::labeled_error( + Err(ShellError::labeled_error( "File could not be opened", "file not found", span, - )); + )) } } diff --git a/src/commands/pick.rs b/src/commands/pick.rs index a33fbda3b..a4a35aa26 100644 --- a/src/commands/pick.rs +++ b/src/commands/pick.rs @@ -39,7 +39,7 @@ fn pick( PickArgs { rest: fields }: PickArgs, RunnableContext { input, name, .. }: RunnableContext, ) -> Result { - if fields.len() == 0 { + if fields.is_empty() { return Err(ShellError::labeled_error( "Pick requires columns to pick", "needs parameter", diff --git a/src/commands/pivot.rs b/src/commands/pivot.rs index 14373bd4c..a1cff062e 100644 --- a/src/commands/pivot.rs +++ b/src/commands/pivot.rs @@ -92,7 +92,7 @@ pub fn pivot(args: PivotArgs, context: RunnableContext) -> Result, password: Option, - headers: &Vec, + headers: &[HeaderKind], tag: Tag, registry: &CommandRegistry, raw_args: &RawCommandArgs, @@ -435,20 +435,18 @@ pub async fn post( } None => Ok(( None, - UntaggedValue::string(format!("No content type found")), + UntaggedValue::string("No content type found".to_owned()), Tag { anchor: Some(AnchorLocation::Url(location.to_string())), span: tag.span, }, )), }, - Err(_) => { - return Err(ShellError::labeled_error( - "URL could not be opened", - "url not found", - tag, - )); - } + Err(_) => Err(ShellError::labeled_error( + "URL could not be opened", + "url not found", + tag, + )), } } else { Err(ShellError::labeled_error( diff --git a/src/commands/range.rs b/src/commands/range.rs index c110e21fa..edb355451 100644 --- a/src/commands/range.rs +++ b/src/commands/range.rs @@ -42,7 +42,7 @@ fn range( RangeArgs { area: rows }: RangeArgs, RunnableContext { input, name, .. }: RunnableContext, ) -> Result { - match rows.item.find(".") { + match rows.item.find('.') { Some(value) => { let (first, last) = rows.item.split_at(value); let first = match first.parse::() { @@ -59,7 +59,7 @@ fn range( } } }; - let last = match last.trim_start_matches(".").parse::() { + let last = match last.trim_start_matches('.').parse::() { Ok(postion) => postion, Err(_) => { if last == ".." { @@ -73,16 +73,14 @@ fn range( } } }; - return Ok(OutputStream::from_input( + Ok(OutputStream::from_input( input.values.skip(first).take(last - first + 1), - )); - } - None => { - return Err(ShellError::labeled_error( - "No correct formatted range found", - "format: ..", - name, - )); + )) } + None => Err(ShellError::labeled_error( + "No correct formatted range found", + "format: ..", + name, + )), } } diff --git a/src/commands/reduce_by.rs b/src/commands/reduce_by.rs index 81afc3d82..4c978a88d 100644 --- a/src/commands/reduce_by.rs +++ b/src/commands/reduce_by.rs @@ -118,7 +118,7 @@ pub fn reduce( .. } => { let datasets: Vec<_> = datasets - .into_iter() + .iter() .map(|subsets| { let mut acc = 0; match subsets { @@ -127,7 +127,7 @@ pub fn reduce( .. } => { let data = data - .into_iter() + .iter() .map(|d| { if let Value { value: UntaggedValue::Table(x), diff --git a/src/commands/reject.rs b/src/commands/reject.rs index 519a0d371..c3c7da7c6 100644 --- a/src/commands/reject.rs +++ b/src/commands/reject.rs @@ -38,7 +38,7 @@ fn reject( RejectArgs { rest: fields }: RejectArgs, RunnableContext { input, name, .. }: RunnableContext, ) -> Result { - if fields.len() == 0 { + if fields.is_empty() { return Err(ShellError::labeled_error( "Reject requires fields", "needs parameter", diff --git a/src/commands/save.rs b/src/commands/save.rs index d7c58f3d3..2285b433a 100644 --- a/src/commands/save.rs +++ b/src/commands/save.rs @@ -226,10 +226,10 @@ fn save( Ok(OutputStream::new(stream)) } -fn string_from(input: &Vec) -> String { +fn string_from(input: &[Value]) -> String { let mut save_data = String::new(); - if input.len() > 0 { + if !input.is_empty() { let mut first = true; for i in input.iter() { if !first { diff --git a/src/commands/split_column.rs b/src/commands/split_column.rs index 1773dc937..643c9323c 100644 --- a/src/commands/split_column.rs +++ b/src/commands/split_column.rs @@ -74,7 +74,7 @@ fn split_column( let positional: Vec<_> = rest.iter().map(|f| f.item.clone()).collect(); // If they didn't provide column names, make up our own - if positional.len() == 0 { + if positional.is_empty() { let mut gen_columns = vec![]; for i in 0..split_result.len() { gen_columns.push(format!("Column{}", i + 1)); @@ -85,15 +85,6 @@ fn split_column( dict.insert_untagged(v.clone(), Primitive::String(k.into())); } - ReturnSuccess::value(dict.into_value()) - } else if split_result.len() == positional.len() { - let mut dict = TaggedDictBuilder::new(&v.tag); - for (&k, v) in split_result.iter().zip(positional.iter()) { - dict.insert_untagged( - v, - UntaggedValue::Primitive(Primitive::String(k.into())), - ); - } ReturnSuccess::value(dict.into_value()) } else { let mut dict = TaggedDictBuilder::new(&v.tag); diff --git a/src/commands/t_sort_by.rs b/src/commands/t_sort_by.rs index 99b780d14..cd96cc9be 100644 --- a/src/commands/t_sort_by.rs +++ b/src/commands/t_sort_by.rs @@ -128,7 +128,7 @@ pub fn columns_sorted( keys.into_iter().map(|k| k.tagged(&origin_tag)).collect() } - _ => vec![format!("default").tagged(&origin_tag)], + _ => vec!["default".to_owned().tagged(&origin_tag)], } } @@ -197,12 +197,12 @@ pub fn t_sort( outer.push_value(UntaggedValue::Table(i).into_value(&origin_tag)); } - return Ok(UntaggedValue::Table(outer.list).into_value(&origin_tag)); + Ok(UntaggedValue::Table(outer.list).into_value(&origin_tag)) } - Some(_) => return Ok(UntaggedValue::nothing().into_value(&origin_tag)), + Some(_) => Ok(UntaggedValue::nothing().into_value(&origin_tag)), } } - None => return Ok(UntaggedValue::nothing().into_value(&origin_tag)), + None => Ok(UntaggedValue::nothing().into_value(&origin_tag)), } } #[cfg(test)] diff --git a/src/commands/to_bson.rs b/src/commands/to_bson.rs index a21c96a98..3fdc7e89b 100644 --- a/src/commands/to_bson.rs +++ b/src/commands/to_bson.rs @@ -94,10 +94,9 @@ fn object_value_to_bson(o: &Dictionary) -> Result { Some((options, tagged_opts_value)) if options == "$options" => { let r: Result = tagged_regex_value.try_into(); let opts: Result = tagged_opts_value.try_into(); - if r.is_err() || opts.is_err() { - generic_object_value_to_bson(o) - } else { - Ok(Bson::RegExp(r.unwrap(), opts.unwrap())) + match (r, opts) { + (Ok(r), Ok(opts)) => Ok(Bson::RegExp(r, opts)), + _ => generic_object_value_to_bson(o), } } _ => generic_object_value_to_bson(o), @@ -107,14 +106,16 @@ fn object_value_to_bson(o: &Dictionary) -> Result { Some((scope, tagged_scope_value)) if scope == "$scope" => { let js: Result = tagged_javascript_value.try_into(); let s: Result<&Dictionary, _> = tagged_scope_value.try_into(); - if js.is_err() || s.is_err() { - generic_object_value_to_bson(o) - } else { - if let Bson::Document(doc) = object_value_to_bson(s.unwrap())? { - Ok(Bson::JavaScriptCodeWithScope(js.unwrap(), doc)) - } else { - generic_object_value_to_bson(o) + + match (js, s) { + (Ok(js), Ok(s)) => { + if let Bson::Document(doc) = object_value_to_bson(s)? { + Ok(Bson::JavaScriptCodeWithScope(js, doc)) + } else { + generic_object_value_to_bson(o) + } } + _ => generic_object_value_to_bson(o), } } None => { @@ -130,10 +131,10 @@ fn object_value_to_bson(o: &Dictionary) -> Result { } Some((timestamp, tagged_timestamp_value)) if timestamp == "$timestamp" => { let ts: Result = tagged_timestamp_value.try_into(); - if ts.is_err() { - generic_object_value_to_bson(o) + if let Ok(ts) = ts { + Ok(Bson::TimeStamp(ts)) } else { - Ok(Bson::TimeStamp(ts.unwrap())) + generic_object_value_to_bson(o) } } Some((binary_subtype, tagged_binary_subtype_value)) @@ -154,30 +155,32 @@ fn object_value_to_bson(o: &Dictionary) -> Result { } Some((object_id, tagged_object_id_value)) if object_id == "$object_id" => { let obj_id: Result = tagged_object_id_value.try_into(); - if obj_id.is_err() { - generic_object_value_to_bson(o) - } else { - let obj_id = ObjectId::with_string(&obj_id.unwrap()); - if obj_id.is_err() { - generic_object_value_to_bson(o) + + if let Ok(obj_id) = obj_id { + let obj_id = ObjectId::with_string(&obj_id); + + if let Ok(obj_id) = obj_id { + Ok(Bson::ObjectId(obj_id)) } else { - Ok(Bson::ObjectId(obj_id.unwrap())) + generic_object_value_to_bson(o) } + } else { + generic_object_value_to_bson(o) } } Some((symbol, tagged_symbol_value)) if symbol == "$symbol" => { let sym: Result = tagged_symbol_value.try_into(); - if sym.is_err() { - generic_object_value_to_bson(o) + if let Ok(sym) = sym { + Ok(Bson::Symbol(sym)) } else { - Ok(Bson::Symbol(sym.unwrap())) + generic_object_value_to_bson(o) } } _ => generic_object_value_to_bson(o), } } -fn get_binary_subtype<'a>(tagged_value: &'a Value) -> Result { +fn get_binary_subtype(tagged_value: &Value) -> Result { match &tagged_value.value { UntaggedValue::Primitive(Primitive::String(s)) => Ok(match s.as_ref() { "generic" => BinarySubtype::Generic, diff --git a/src/commands/to_delimited_data.rs b/src/commands/to_delimited_data.rs index 0e7414557..053ef60d3 100644 --- a/src/commands/to_delimited_data.rs +++ b/src/commands/to_delimited_data.rs @@ -29,7 +29,7 @@ fn from_value_to_delimited_string( wtr.write_record(fields).expect("can not write."); wtr.write_record(values).expect("can not write."); - return Ok(String::from_utf8(wtr.into_inner().map_err(|_| { + let v = String::from_utf8(wtr.into_inner().map_err(|_| { ShellError::labeled_error( "Could not convert record", "original value", @@ -42,7 +42,8 @@ fn from_value_to_delimited_string( "original value", &tagged_value.tag, ) - })?); + })?; + Ok(v) } UntaggedValue::Table(list) => { let mut wtr = WriterBuilder::new() @@ -68,8 +69,7 @@ fn from_value_to_delimited_string( } wtr.write_record(&row).expect("can not write"); } - - return Ok(String::from_utf8(wtr.into_inner().map_err(|_| { + let v = String::from_utf8(wtr.into_inner().map_err(|_| { ShellError::labeled_error( "Could not convert record", "original value", @@ -82,9 +82,10 @@ fn from_value_to_delimited_string( "original value", &tagged_value.tag, ) - })?); + })?; + Ok(v) } - _ => return to_string_tagged_value(tagged_value), + _ => to_string_tagged_value(tagged_value), } } @@ -98,7 +99,7 @@ pub fn clone_tagged_value(v: &Value) -> Value { UntaggedValue::Primitive(Primitive::Nothing) } UntaggedValue::Primitive(Primitive::Boolean(b)) => { - UntaggedValue::Primitive(Primitive::Boolean(b.clone())) + UntaggedValue::Primitive(Primitive::Boolean(*b)) } UntaggedValue::Primitive(Primitive::Decimal(f)) => { UntaggedValue::Primitive(Primitive::Decimal(f.clone())) @@ -110,10 +111,10 @@ pub fn clone_tagged_value(v: &Value) -> Value { UntaggedValue::Primitive(Primitive::Path(x.clone())) } UntaggedValue::Primitive(Primitive::Bytes(b)) => { - UntaggedValue::Primitive(Primitive::Bytes(b.clone())) + UntaggedValue::Primitive(Primitive::Bytes(*b)) } UntaggedValue::Primitive(Primitive::Date(d)) => { - UntaggedValue::Primitive(Primitive::Date(d.clone())) + UntaggedValue::Primitive(Primitive::Date(*d)) } UntaggedValue::Row(o) => UntaggedValue::Row(o.clone()), UntaggedValue::Table(l) => UntaggedValue::Table(l.clone()), @@ -135,17 +136,15 @@ fn to_string_tagged_value(v: &Value) -> Result { UntaggedValue::Primitive(Primitive::Decimal(_)) => Ok(v.as_string()?.to_string()), UntaggedValue::Primitive(Primitive::Int(_)) => Ok(v.as_string()?.to_string()), UntaggedValue::Primitive(Primitive::Path(_)) => Ok(v.as_string()?.to_string()), - UntaggedValue::Table(_) => return Ok(String::from("[Table]")), - UntaggedValue::Row(_) => return Ok(String::from("[Row]")), - UntaggedValue::Primitive(Primitive::Line(s)) => return Ok(s.to_string()), - UntaggedValue::Primitive(Primitive::String(s)) => return Ok(s.to_string()), - _ => { - return Err(ShellError::labeled_error( - "Unexpected value", - "", - v.tag.clone(), - )) - } + UntaggedValue::Table(_) => Ok(String::from("[Table]")), + UntaggedValue::Row(_) => Ok(String::from("[Row]")), + UntaggedValue::Primitive(Primitive::Line(s)) => Ok(s.to_string()), + UntaggedValue::Primitive(Primitive::String(s)) => Ok(s.to_string()), + _ => Err(ShellError::labeled_error( + "Unexpected value", + "", + v.tag.clone(), + )), } } diff --git a/src/commands/to_json.rs b/src/commands/to_json.rs index 8c460ce4d..dfa4aef5c 100644 --- a/src/commands/to_json.rs +++ b/src/commands/to_json.rs @@ -94,7 +94,7 @@ pub fn value_to_json_value(v: &Value) -> Result { }) } -fn json_list(input: &Vec) -> Result, ShellError> { +fn json_list(input: &[Value]) -> Result, ShellError> { let mut out = vec![]; for value in input { diff --git a/src/commands/to_sqlite.rs b/src/commands/to_sqlite.rs index 3b4d84dbb..6b76a7cb0 100644 --- a/src/commands/to_sqlite.rs +++ b/src/commands/to_sqlite.rs @@ -70,7 +70,7 @@ fn comma_concat(acc: String, current: String) -> String { } } -fn get_columns(rows: &Vec) -> Result { +fn get_columns(rows: &[Value]) -> Result { match &rows[0].value { UntaggedValue::Row(d) => Ok(d .entries diff --git a/src/commands/to_toml.rs b/src/commands/to_toml.rs index 16091a2cf..351602677 100644 --- a/src/commands/to_toml.rs +++ b/src/commands/to_toml.rs @@ -82,7 +82,7 @@ pub fn value_to_toml_value(v: &Value) -> Result { }) } -fn collect_values(input: &Vec) -> Result, ShellError> { +fn collect_values(input: &[Value]) -> Result, ShellError> { let mut out = vec![]; for value in input { diff --git a/src/commands/which_.rs b/src/commands/which_.rs index 933f1b77d..13ad3a7ec 100644 --- a/src/commands/which_.rs +++ b/src/commands/which_.rs @@ -38,7 +38,7 @@ pub fn which(args: CommandArgs, registry: &CommandRegistry) -> Result 0 { + if !v.is_empty() { match &v[0] { Value { value: UntaggedValue::Primitive(Primitive::String(s)), diff --git a/src/context.rs b/src/context.rs index 369694413..b6f0d2a81 100644 --- a/src/context.rs +++ b/src/context.rs @@ -45,7 +45,7 @@ impl CommandRegistry { pub(crate) fn get_command(&self, name: &str) -> Option> { let registry = self.registry.lock().unwrap(); - registry.get(name).map(|c| c.clone()) + registry.get(name).cloned() } pub(crate) fn expect_command(&self, name: &str) -> Arc { @@ -175,7 +175,7 @@ impl Context { self.registry.expect_command(name) } - pub(crate) fn run_command<'a>( + pub(crate) fn run_command( &mut self, command: Arc, name_tag: Tag, diff --git a/src/data/base.rs b/src/data/base.rs index 6ffe6fd9b..7f3a7c055 100644 --- a/src/data/base.rs +++ b/src/data/base.rs @@ -40,7 +40,7 @@ interfaces!(Block: dyn ObjectHash); #[typetag::serde] impl EvaluateTrait for Block { fn invoke(&self, scope: &Scope) -> Result { - if self.expressions.len() == 0 { + if self.expressions.is_empty() { return Ok(UntaggedValue::nothing().into_value(&self.tag)); } @@ -189,8 +189,8 @@ fn coerce_compare_primitive( (Line(left), String(right)) => CompareValues::String(left.clone(), right.clone()), (String(left), Line(right)) => CompareValues::String(left.clone(), right.clone()), (Line(left), Line(right)) => CompareValues::String(left.clone(), right.clone()), - (Date(left), Date(right)) => CompareValues::Date(left.clone(), right.clone()), - (Date(left), Duration(right)) => CompareValues::DateDuration(left.clone(), right.clone()), + (Date(left), Date(right)) => CompareValues::Date(*left, *right), + (Date(left), Duration(right)) => CompareValues::DateDuration(*left, *right), _ => return Err((left.type_name(), right.type_name())), }) } diff --git a/src/data/base/property_get.rs b/src/data/base/property_get.rs index 13b3733fa..31c8ccfdd 100644 --- a/src/data/base/property_get.rs +++ b/src/data/base/property_get.rs @@ -144,7 +144,7 @@ pub(crate) fn get_data_by_member(value: &Value, name: &PathMember) -> Result Option { let mut new_obj = value.clone(); - let split_path: Vec<_> = path.split(".").collect(); + let split_path: Vec<_> = path.split('.').collect(); if let UntaggedValue::Row(ref mut o) = new_obj.value { let mut current = o; @@ -256,9 +256,10 @@ pub fn insert_data_at_member( ) -> Result<(), ShellError> { match &mut value.value { UntaggedValue::Row(dict) => match &member.unspanned { - UnspannedPathMember::String(key) => Ok({ + UnspannedPathMember::String(key) => { dict.insert_data_at_key(key, new_value); - }), + Ok(()) + } UnspannedPathMember::Int(_) => Err(ShellError::type_error( "column name", "integer".spanned(member.span), @@ -269,7 +270,7 @@ pub fn insert_data_at_member( "list index", "string".spanned(member.span), )), - UnspannedPathMember::Int(int) => Ok({ + UnspannedPathMember::Int(int) => { let int = int.to_usize().ok_or_else(|| { ShellError::range_error( ExpectedRange::Usize, @@ -279,7 +280,8 @@ pub fn insert_data_at_member( })?; insert_data_at_index(array, int.tagged(member.span), new_value.clone())?; - }), + Ok(()) + } }, other => match &member.unspanned { UnspannedPathMember::String(_) => Err(ShellError::type_error( @@ -473,7 +475,7 @@ pub(crate) fn get_data_by_key(value: &Value, name: Spanned<&str>) -> Option 0 { + if !out.is_empty() { Some(UntaggedValue::Table(out).into_value(name.span)) } else { None diff --git a/src/data/base/shape.rs b/src/data/base/shape.rs index 4683202ea..a4e968947 100644 --- a/src/data/base/shape.rs +++ b/src/data/base/shape.rs @@ -196,7 +196,7 @@ impl<'a> PrettyDebug for DebugEntry<'a> { fn pretty(&self) -> DebugDocBuilder { (b::key(match self.key { Column::String(string) => string.clone(), - Column::Value => format!(""), + Column::Value => "".to_owned(), }) + b::delimit("(", self.value.pretty(), ")").as_kind()) } } @@ -251,7 +251,7 @@ impl InlineShape { Primitive::ColumnPath(path) => InlineShape::ColumnPath(path.clone()), Primitive::Pattern(pattern) => InlineShape::Pattern(pattern.clone()), Primitive::Boolean(boolean) => InlineShape::Boolean(*boolean), - Primitive::Date(date) => InlineShape::Date(date.clone()), + Primitive::Date(date) => InlineShape::Date(*date), Primitive::Duration(duration) => InlineShape::Duration(*duration), Primitive::Path(path) => InlineShape::Path(path.clone()), Primitive::Binary(_) => InlineShape::Binary, @@ -329,23 +329,26 @@ impl PrettyDebug for FormatInlineShape { (b::primitive(format!("{}", byte.get_value())) + b::space() + b::kind("B")) .group() } - _ => b::primitive(format!("{}", byte.format(1))), + _ => b::primitive(byte.format(1).to_string()), } } - InlineShape::String(string) => b::primitive(format!("{}", string)), - InlineShape::Line(string) => b::primitive(format!("{}", string)), + InlineShape::String(string) => b::primitive(string), + InlineShape::Line(string) => b::primitive(string), InlineShape::ColumnPath(path) => { b::intersperse(path.iter().map(|member| member.pretty()), b::keyword(".")) } InlineShape::Pattern(pattern) => b::primitive(pattern), - InlineShape::Boolean(boolean) => b::primitive(match (boolean, column) { - (true, None) => format!("Yes"), - (false, None) => format!("No"), - (true, Some(Column::String(s))) if !s.is_empty() => format!("{}", s), - (false, Some(Column::String(s))) if !s.is_empty() => format!(""), - (true, Some(_)) => format!("Yes"), - (false, Some(_)) => format!("No"), - }), + InlineShape::Boolean(boolean) => b::primitive( + match (boolean, column) { + (true, None) => "Yes", + (false, None) => "No", + (true, Some(Column::String(s))) if !s.is_empty() => s, + (false, Some(Column::String(s))) if !s.is_empty() => "", + (true, Some(_)) => "Yes", + (false, Some(_)) => "No", + } + .to_owned(), + ), InlineShape::Date(date) => b::primitive(date.humanize()), InlineShape::Duration(duration) => { b::description(format_primitive(&Primitive::Duration(*duration), None)) @@ -443,12 +446,12 @@ where None => { self.values.insert(key, { let mut group = G::new(); - group.merge(value.into()); + group.merge(value); group }); } Some(group) => { - group.merge(value.into()); + group.merge(value); } } } @@ -514,7 +517,7 @@ impl Shape { d.iter() .map(|c| match c { Column::String(s) => s.clone(), - Column::Value => format!(""), + Column::Value => "".to_owned(), }) .join(", ") ), diff --git a/src/data/command.rs b/src/data/command.rs index 003af27e5..91c52bc0e 100644 --- a/src/data/command.rs +++ b/src/data/command.rs @@ -53,7 +53,7 @@ fn signature_dict(signature: Signature, tag: impl Into) -> Value { sig.push_value(for_spec(arg.0.name(), "argument", is_required, &tag)); } - if let Some(_) = signature.rest_positional { + if signature.rest_positional.is_some() { let is_required = false; sig.push_value(for_spec("rest", "argument", is_required, &tag)); } diff --git a/src/data/dict.rs b/src/data/dict.rs index afdff355a..8e03b151b 100644 --- a/src/data/dict.rs +++ b/src/data/dict.rs @@ -16,7 +16,7 @@ impl<'a> PrettyDebug for DebugEntry<'a> { } pub trait DictionaryExt { - fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value>; + fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value>; fn keys(&self) -> indexmap::map::Keys; fn get_data_by_key(&self, name: Spanned<&str>) -> Option; @@ -25,7 +25,7 @@ pub trait DictionaryExt { } impl DictionaryExt for Dictionary { - fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value> { + fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value> { match self.entries.get(desc) { Some(v) => MaybeOwned::Borrowed(v), None => MaybeOwned::Owned( diff --git a/src/data/primitive.rs b/src/data/primitive.rs index 5bda3ccbf..cd4267905 100644 --- a/src/data/primitive.rs +++ b/src/data/primitive.rs @@ -29,15 +29,15 @@ pub fn format_primitive(primitive: &Primitive, field_name: Option<&String>) -> S match byte.get_unit() { byte_unit::ByteUnit::B => format!("{} B ", byte.get_value()), - _ => format!("{}", byte.format(1)), + _ => byte.format(1).to_string(), } } Primitive::Duration(sec) => format_duration(*sec), - Primitive::Int(i) => format!("{}", i), - Primitive::Decimal(decimal) => format!("{}", decimal), - Primitive::Pattern(s) => format!("{}", s), - Primitive::String(s) => format!("{}", s), - Primitive::Line(s) => format!("{}", s), + Primitive::Int(i) => i.to_string(), + Primitive::Decimal(decimal) => decimal.to_string(), + Primitive::Pattern(s) => s.to_string(), + Primitive::String(s) => s.to_owned(), + Primitive::Line(s) => s.to_owned(), Primitive::ColumnPath(p) => { let mut members = p.iter(); let mut f = String::new(); @@ -57,15 +57,16 @@ pub fn format_primitive(primitive: &Primitive, field_name: Option<&String>) -> S f } Primitive::Boolean(b) => match (b, field_name) { - (true, None) => format!("Yes"), - (false, None) => format!("No"), - (true, Some(s)) if !s.is_empty() => format!("{}", s), - (false, Some(s)) if !s.is_empty() => format!(""), - (true, Some(_)) => format!("Yes"), - (false, Some(_)) => format!("No"), - }, - Primitive::Binary(_) => format!(""), - Primitive::Date(d) => format!("{}", d.humanize()), + (true, None) => "Yes", + (false, None) => "No", + (true, Some(s)) if !s.is_empty() => s, + (false, Some(s)) if !s.is_empty() => "", + (true, Some(_)) => "Yes", + (false, Some(_)) => "No", + } + .to_owned(), + Primitive::Binary(_) => "".to_owned(), + Primitive::Date(d) => d.humanize().to_string(), } } @@ -83,7 +84,7 @@ fn format_duration(sec: u64) -> String { let (days, hours) = (hours / 24, hours % 24); match (days, hours, minutes, seconds) { - (0, 0, 0, 1) => format!("1 sec"), + (0, 0, 0, 1) => "1 sec".to_owned(), (0, 0, 0, s) => format!("{} secs", s), (0, 0, m, s) => format!("{}:{:02}", m, s), (0, h, m, s) => format!("{}:{:02}:{:02}", h, m, s), diff --git a/src/data/value.rs b/src/data/value.rs index 574267406..8c8da375b 100644 --- a/src/data/value.rs +++ b/src/data/value.rs @@ -22,7 +22,7 @@ pub fn date_from_str(s: Tagged<&str>) -> Result { } pub fn compare_values( - operator: &Operator, + operator: Operator, left: &UntaggedValue, right: &UntaggedValue, ) -> Result { diff --git a/src/deserializer.rs b/src/deserializer.rs index 5f366d68c..366efdbbe 100644 --- a/src/deserializer.rs +++ b/src/deserializer.rs @@ -43,11 +43,11 @@ impl<'de> ConfigDeserializer<'de> { Some(UntaggedValue::Table(positional).into_untagged_value()) // TODO: correct tag } else { if self.call.args.has(name) { - self.call.args.get(name).map(|x| x.clone()) + self.call.args.get(name).cloned() } else { let position = self.position; self.position += 1; - self.call.args.nth(position).map(|x| x.clone()) + self.call.args.nth(position).cloned() } }; @@ -316,7 +316,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut ConfigDeserializer<'de> { let json_cursor = std::io::Cursor::new(json.into_bytes()); let mut json_de = serde_json::Deserializer::from_reader(json_cursor); let r = json_de.deserialize_struct(name, fields, visitor)?; - return Ok(r); + Ok(r) } trace!( @@ -409,12 +409,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut ConfigDeserializer<'de> { .. } => visit::, _>(string.tagged(tag), name, fields, visitor), - other => { - return Err(ShellError::type_error( - name, - other.type_name().spanned(other.span()), - )) - } + other => Err(ShellError::type_error( + name, + other.type_name().spanned(other.span()), + )), } } fn deserialize_enum( @@ -471,7 +469,7 @@ impl<'a, 'de: 'a, I: Iterator> de::SeqAccess<'de> for SeqDeseriali } fn size_hint(&self) -> Option { - return self.vals.size_hint().1; + self.vals.size_hint().1 } } @@ -493,7 +491,7 @@ impl<'a, 'de: 'a> de::SeqAccess<'de> for StructDeserializer<'a, 'de> { where T: de::DeserializeSeed<'de>, { - if self.fields.len() == 0 { + if self.fields.is_empty() { return Ok(None); } @@ -505,7 +503,7 @@ impl<'a, 'de: 'a> de::SeqAccess<'de> for StructDeserializer<'a, 'de> { } fn size_hint(&self) -> Option { - return Some(self.fields.len()); + Some(self.fields.len()) } } diff --git a/src/evaluate/evaluator.rs b/src/evaluate/evaluator.rs index 730a9a350..32e462af9 100644 --- a/src/evaluate/evaluator.rs +++ b/src/evaluate/evaluator.rs @@ -40,7 +40,7 @@ pub(crate) fn evaluate_baseline_expr( trace!("left={:?} right={:?}", left.value, right.value); - match apply_operator(binary.op(), &left, &right) { + match apply_operator(**binary.op(), &left, &right) { Ok(result) => Ok(result.into_value(tag)), Err((left_type, right_type)) => Err(ShellError::coerce_error( left_type.spanned(binary.left().span), @@ -83,7 +83,7 @@ pub(crate) fn evaluate_baseline_expr( possible_matches.sort(); - if possible_matches.len() > 0 { + if !possible_matches.is_empty() { return Err(ShellError::labeled_error( "Unknown column", format!("did you mean '{}'?", possible_matches[0].1), @@ -174,7 +174,7 @@ fn evaluate_reference( x => Ok(scope .vars .get(x) - .map(|v| v.clone()) + .cloned() .unwrap_or_else(|| UntaggedValue::nothing().into_value(tag))), }, } diff --git a/src/evaluate/operator.rs b/src/evaluate/operator.rs index 8880630bc..7bbe7940b 100644 --- a/src/evaluate/operator.rs +++ b/src/evaluate/operator.rs @@ -4,11 +4,11 @@ use nu_protocol::{Primitive, ShellTypeName, UntaggedValue, Value}; use std::ops::Not; pub fn apply_operator( - op: &Operator, + op: Operator, left: &Value, right: &Value, ) -> Result { - match *op { + match op { Operator::Equal | Operator::NotEqual | Operator::LessThan diff --git a/src/format/entries.rs b/src/format/entries.rs index 0584ce469..6ead501fe 100644 --- a/src/format/entries.rs +++ b/src/format/entries.rs @@ -35,7 +35,7 @@ impl EntriesView { impl RenderView for EntriesView { fn render_view(&self, _host: &mut dyn Host) -> Result<(), ShellError> { - if self.entries.len() == 0 { + if self.entries.is_empty() { return Ok(()); } diff --git a/src/format/generic.rs b/src/format/generic.rs index fdf3f203b..cc469f0d6 100644 --- a/src/format/generic.rs +++ b/src/format/generic.rs @@ -16,7 +16,10 @@ impl RenderView for GenericView<'_> { fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> { let tag = &self.value.tag; match &self.value.value { - UntaggedValue::Primitive(p) => Ok(host.stdout(&format_primitive(p, None))), + UntaggedValue::Primitive(p) => { + host.stdout(&format_primitive(p, None)); + Ok(()) + } UntaggedValue::Table(l) => { let view = TableView::from_list(l, 0); diff --git a/src/format/table.rs b/src/format/table.rs index 2d3583822..fc4eab8e6 100644 --- a/src/format/table.rs +++ b/src/format/table.rs @@ -30,7 +30,7 @@ impl TableView { for value in values { let descs = value.data_descriptors(); - if descs.len() == 0 { + if descs.is_empty() { if !ret.contains(&value_column) { ret.push("".to_string()); } @@ -46,13 +46,13 @@ impl TableView { } pub fn from_list(values: &[Value], starting_idx: usize) -> Option { - if values.len() == 0 { + if values.is_empty() { return None; } let mut headers = TableView::merge_descriptors(values); - if headers.len() == 0 { + if headers.is_empty() { headers.push("".to_string()); } @@ -68,10 +68,10 @@ impl TableView { value: UntaggedValue::Row(..), .. } => ( - format_leaf(&UntaggedValue::nothing()).plain_string(100000), + format_leaf(&UntaggedValue::nothing()).plain_string(100_000), style_leaf(&UntaggedValue::nothing()), ), - _ => (format_leaf(value).plain_string(100000), style_leaf(value)), + _ => (format_leaf(value).plain_string(100_000), style_leaf(value)), } } else { match value { @@ -81,12 +81,12 @@ impl TableView { } => { let data = value.get_data(d); ( - format_leaf(data.borrow()).plain_string(100000), + format_leaf(data.borrow()).plain_string(100_000), style_leaf(data.borrow()), ) } _ => ( - format_leaf(&UntaggedValue::nothing()).plain_string(100000), + format_leaf(&UntaggedValue::nothing()).plain_string(100_000), style_leaf(&UntaggedValue::nothing()), ), } @@ -96,7 +96,7 @@ impl TableView { if values.len() > 1 { // Indices are black, bold, right-aligned: - row.insert(0, (format!("{}", (starting_idx + idx).to_string()), "Fdbr")); + row.insert(0, ((starting_idx + idx).to_string(), "Fdbr")); } entries.push(row); @@ -105,22 +105,21 @@ impl TableView { let mut max_per_column = vec![]; if values.len() > 1 { - headers.insert(0, format!("#")); + headers.insert(0, "#".to_owned()); } - for head in 0..headers.len() { + for i in 0..headers.len() { let mut current_col_max = 0; - for row in 0..values.len() { - let value_length = entries[row][head].0.chars().count(); + let iter = entries.iter().take(values.len()); + + for entry in iter { + let value_length = entry[i].0.chars().count(); if value_length > current_col_max { current_col_max = value_length; } } - max_per_column.push(std::cmp::max( - current_col_max, - headers[head].chars().count(), - )); + max_per_column.push(std::cmp::max(current_col_max, headers[i].chars().count())); } // Different platforms want different amounts of buffer, not sure why @@ -132,13 +131,14 @@ impl TableView { // If we have too many columns, truncate the table if max_num_of_columns < headers.len() { headers.truncate(max_num_of_columns); - for row in 0..entries.len() { - entries[row].truncate(max_num_of_columns); + + for entry in &mut entries { + entry.truncate(max_num_of_columns); } - headers.push("...".to_string()); - for row in 0..entries.len() { - entries[row].push(("...".to_string(), "c")); // ellipsis is centred + headers.push("...".to_owned()); + for entry in &mut entries { + entry.push(("...".to_owned(), "c")); // ellipsis is centred } } @@ -149,22 +149,23 @@ impl TableView { let mut num_overages = 0; let mut underage_sum = 0; let mut overage_separator_sum = 0; - for idx in 0..headers.len() { - if max_per_column[idx] > max_naive_column_width { + let iter = max_per_column.iter().enumerate().take(headers.len()); + for (i, &column_max) in iter { + if column_max > max_naive_column_width { num_overages += 1; - if idx != (headers.len() - 1) { + if i != (headers.len() - 1) { overage_separator_sum += 3; } - if idx == 0 { + if i == 0 { overage_separator_sum += 1; } } else { - underage_sum += max_per_column[idx]; + underage_sum += column_max; // if column isn't last, add 3 for its separator - if idx != (headers.len() - 1) { + if i != (headers.len() - 1) { underage_sum += 3; } - if idx == 0 { + if i == 0 { underage_sum += 1; } } @@ -180,24 +181,25 @@ impl TableView { // This width isn't quite right, as we're rounding off some of our space num_overages = 0; overage_separator_sum = 0; - for idx in 0..headers.len() { - if max_per_column[idx] > max_naive_column_width { - if max_per_column[idx] <= max_column_width { - underage_sum += max_per_column[idx]; + let iter = max_per_column.iter().enumerate().take(headers.len()); + for (i, &column_max) in iter { + if column_max > max_naive_column_width { + if column_max <= max_column_width { + underage_sum += column_max; // if column isn't last, add 3 for its separator - if idx != (headers.len() - 1) { + if i != (headers.len() - 1) { underage_sum += 3; } - if idx == 0 { + if i == 0 { underage_sum += 1; } } else { // Column is still too large, so let's count it num_overages += 1; - if idx != (headers.len() - 1) { + if i != (headers.len() - 1) { overage_separator_sum += 3; } - if idx == 0 { + if i == 0 { overage_separator_sum += 1; } } @@ -214,8 +216,9 @@ impl TableView { for head in 0..headers.len() { if max_per_column[head] > max_naive_column_width { headers[head] = fill(&headers[head], max_column_width); - for row in 0..entries.len() { - entries[row][head].0 = fill(&entries[row][head].0, max_column_width); + + for entry in &mut entries { + entry[head].0 = fill(&entry[head].0, max_column_width); } } } @@ -226,7 +229,7 @@ impl TableView { impl RenderView for TableView { fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> { - if self.entries.len() == 0 { + if self.entries.is_empty() { return Ok(()); } diff --git a/src/plugins/format.rs b/src/plugins/format.rs index 974514033..40ea58ca6 100644 --- a/src/plugins/format.rs +++ b/src/plugins/format.rs @@ -21,7 +21,7 @@ fn format(input: &str) -> IResult<&str, Vec> { let mut loop_input = input; loop { let (input, before) = take_while(|c| c != '{')(loop_input)?; - if before.len() > 0 { + if !before.is_empty() { output.push(FormatCommand::Text(before.to_string())); } if input != "" { diff --git a/src/plugins/inc.rs b/src/plugins/inc.rs index da143e01e..574413c3f 100644 --- a/src/plugins/inc.rs +++ b/src/plugins/inc.rs @@ -90,13 +90,13 @@ impl Inc { } UntaggedValue::Table(values) => { if values.len() == 1 { - return Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?]) - .into_value(value.tag())); + Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?]) + .into_value(value.tag())) } else { - return Err(ShellError::type_error( + Err(ShellError::type_error( "incrementable value", value.type_name().spanned(value.span()), - )); + )) } } @@ -108,20 +108,16 @@ impl Inc { &f, Box::new(move |(obj_source, column_path_tried, _)| { match did_you_mean(&obj_source, &column_path_tried) { - Some(suggestions) => { - return ShellError::labeled_error( - "Unknown column", - format!("did you mean '{}'?", suggestions[0].1), - span_for_spanned_list(fields.iter().map(|p| p.span)), - ) - } - None => { - return ShellError::labeled_error( - "Unknown column", - "row does not contain this column", - span_for_spanned_list(fields.iter().map(|p| p.span)), - ) - } + Some(suggestions) => ShellError::labeled_error( + "Unknown column", + format!("did you mean '{}'?", suggestions[0].1), + span_for_spanned_list(fields.iter().map(|p| p.span)), + ), + None => ShellError::labeled_error( + "Unknown column", + "row does not contain this column", + span_for_spanned_list(fields.iter().map(|p| p.span)), + ), } }), ); @@ -133,14 +129,12 @@ impl Inc { &f, replacement.value.clone().into_untagged_value(), ) { - Some(v) => return Ok(v), - None => { - return Err(ShellError::labeled_error( - "inc could not find field to replace", - "column name", - value.tag(), - )) - } + Some(v) => Ok(v), + None => Err(ShellError::labeled_error( + "inc could not find field to replace", + "column name", + value.tag(), + )), } } None => Err(ShellError::untagged_runtime_error( @@ -201,13 +195,11 @@ impl Plugin for Inc { } match &self.error { - Some(reason) => { - return Err(ShellError::untagged_runtime_error(format!( - "{}: {}", - reason, - Inc::usage() - ))) - } + Some(reason) => Err(ShellError::untagged_runtime_error(format!( + "{}: {}", + reason, + Inc::usage() + ))), None => Ok(vec![]), } } diff --git a/src/plugins/parse.rs b/src/plugins/parse.rs index 400a7e8c7..7a1fed829 100644 --- a/src/plugins/parse.rs +++ b/src/plugins/parse.rs @@ -22,7 +22,7 @@ fn parse(input: &str) -> IResult<&str, Vec> { let mut loop_input = input; loop { let (input, before) = take_while(|c| c != '{')(loop_input)?; - if before.len() > 0 { + if !before.is_empty() { output.push(ParseCommand::Text(before.to_string())); } if input != "" { @@ -73,7 +73,7 @@ fn build_regex(commands: &[ParseCommand]) -> String { } } - return output; + output } struct Parse { regex: Regex, diff --git a/src/plugins/str.rs b/src/plugins/str.rs index 5ac748618..4b819dc4b 100644 --- a/src/plugins/str.rs +++ b/src/plugins/str.rs @@ -126,7 +126,7 @@ impl Str { _ => v[0].trim().parse().unwrap(), }; let end: usize = match v[1] { - "" => usize::max_value().clone(), + "" => usize::max_value(), _ => v[1].trim().parse().unwrap(), }; if start > end { @@ -169,14 +169,12 @@ impl Str { &f, Box::new(move |(obj_source, column_path_tried, error)| { match did_you_mean(&obj_source, &column_path_tried) { - Some(suggestions) => { - return ShellError::labeled_error( - "Unknown column", - format!("did you mean '{}'?", suggestions[0].1), - span_for_spanned_list(fields.iter().map(|p| p.span)), - ) - } - None => return error, + Some(suggestions) => ShellError::labeled_error( + "Unknown column", + format!("did you mean '{}'?", suggestions[0].1), + span_for_spanned_list(fields.iter().map(|p| p.span)), + ), + None => error, } }), ); @@ -188,7 +186,7 @@ impl Str { &f, replacement.value.clone().into_untagged_value(), ) { - Some(v) => return Ok(v), + Some(v) => Ok(v), None => Err(ShellError::labeled_error( "str could not find field to replace", "column name", @@ -293,13 +291,11 @@ impl Plugin for Str { } match &self.error { - Some(reason) => { - return Err(ShellError::untagged_runtime_error(format!( - "{}: {}", - reason, - Str::usage() - ))) - } + Some(reason) => Err(ShellError::untagged_runtime_error(format!( + "{}: {}", + reason, + Str::usage() + ))), None => Ok(vec![]), } } diff --git a/src/shell/completer.rs b/src/shell/completer.rs index 79a4b7879..27aeaed15 100644 --- a/src/shell/completer.rs +++ b/src/shell/completer.rs @@ -28,11 +28,11 @@ impl NuCompleter { completion.replacement = completion.replacement.replace("\\(", "("); } - if completion.replacement.contains(" ") || completion.replacement.contains("(") { - if !completion.replacement.starts_with("\"") { + if completion.replacement.contains(' ') || completion.replacement.contains('(') { + if !completion.replacement.starts_with('\"') { completion.replacement = format!("\"{}", completion.replacement); } - if !completion.replacement.ends_with("\"") { + if !completion.replacement.ends_with('\"') { completion.replacement = format!("{}\"", completion.replacement); } } diff --git a/src/shell/filesystem_shell.rs b/src/shell/filesystem_shell.rs index 15aaaec83..8a6cc06fc 100644 --- a/src/shell/filesystem_shell.rs +++ b/src/shell/filesystem_shell.rs @@ -104,7 +104,7 @@ impl Shell for FilesystemShell { //If it's not a glob, try to display the contents of the entry if it's a directory let lossy_path = full_path.to_string_lossy(); - if !lossy_path.contains("*") && !lossy_path.contains("?") { + if !lossy_path.contains('*') && !lossy_path.contains('?') { let entry = Path::new(&full_path); if entry.is_dir() { let entries = std::fs::read_dir(&entry); @@ -344,7 +344,7 @@ impl Shell for FilesystemShell { new_dst.push(fragment); } - Ok((PathBuf::from(&source_file), PathBuf::from(new_dst))) + Ok((PathBuf::from(&source_file), new_dst)) }; let sources = sources.paths_applying_with(strategy)?; @@ -418,7 +418,7 @@ impl Shell for FilesystemShell { new_dst.push(fragment); } - Ok((PathBuf::from(&source_file), PathBuf::from(new_dst))) + Ok((PathBuf::from(&source_file), new_dst)) }; let sources = sources.paths_applying_with(strategy)?; @@ -530,7 +530,7 @@ impl Shell for FilesystemShell { ) -> Result { let full_path = PathBuf::from(path); - if directories.len() == 0 { + if directories.is_empty() { return Err(ShellError::labeled_error( "mkdir requires directory paths", "needs parameter", @@ -861,13 +861,11 @@ impl Shell for FilesystemShell { } } else { if destination.exists() { - if !sources.iter().all(|x| { - if let Ok(entry) = x.as_ref() { - entry.is_file() - } else { - false - } - }) { + let is_file = |x: &Result| { + x.as_ref().map(|entry| entry.is_file()).unwrap_or_default() + }; + + if !sources.iter().all(is_file) { return Err(ShellError::labeled_error( "Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)", "Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)", diff --git a/src/shell/help_shell.rs b/src/shell/help_shell.rs index 9dafccd34..dfccb6d58 100644 --- a/src/shell/help_shell.rs +++ b/src/shell/help_shell.rs @@ -108,13 +108,11 @@ impl HelpShell { impl Shell for HelpShell { fn name(&self) -> String { let anchor_name = self.value.anchor_name(); - format!( - "{}", - match anchor_name { - Some(x) => format!("{{{}}}", x), - None => format!("<{}>", self.value.type_name()), - } - ) + + match anchor_name { + Some(x) => format!("{{{}}}", x), + None => format!("<{}>", self.value.type_name()), + } } fn homedir(&self) -> Option { @@ -140,10 +138,7 @@ impl Shell for HelpShell { _context: &RunnableContext, _full: bool, ) -> Result { - Ok(self - .commands() - .map(|x| ReturnSuccess::value(x)) - .to_output_stream()) + Ok(self.commands().map(ReturnSuccess::value).to_output_stream()) } fn cd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result { diff --git a/src/shell/value_shell.rs b/src/shell/value_shell.rs index 5e34fd99a..84cab9d3b 100644 --- a/src/shell/value_shell.rs +++ b/src/shell/value_shell.rs @@ -76,13 +76,11 @@ impl ValueShell { impl Shell for ValueShell { fn name(&self) -> String { let anchor_name = self.value.anchor_name(); - format!( - "{}", - match anchor_name { - Some(x) => format!("{{{}}}", x), - None => format!("<{}>", self.value.type_name()), - } - ) + + match anchor_name { + Some(x) => format!("{{{}}}", x), + None => format!("<{}>", self.value.type_name()), + } } fn homedir(&self) -> Option { @@ -124,7 +122,7 @@ impl Shell for ValueShell { Ok(self .members_under(full_path.as_path()) - .map(|x| ReturnSuccess::value(x)) + .map(ReturnSuccess::value) .to_output_stream()) } diff --git a/src/stream.rs b/src/stream.rs index fcc430d6c..a33377e9f 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -142,7 +142,7 @@ impl From> for OutputStream { OutputStream { values: input .into_iter() - .map(|i| ReturnSuccess::value(i)) + .map(ReturnSuccess::value) .collect::>() .boxed(), } diff --git a/src/utils.rs b/src/utils.rs index 349ea6652..dc9fed32e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -22,7 +22,7 @@ pub fn did_you_mean(obj_source: &Value, field_tried: &PathMember) -> Option 0 { + if !possible_matches.is_empty() { possible_matches.sort(); Some(possible_matches) } else { @@ -96,7 +96,7 @@ impl Div<&str> for &AbsolutePath { type Output = AbsolutePath; fn div(self, rhs: &str) -> Self::Output { - let parts = rhs.split("/"); + let parts = rhs.split('/'); let mut result = self.inner.clone(); for part in parts { @@ -133,7 +133,7 @@ impl> Div for &RelativePath { type Output = RelativePath; fn div(self, rhs: T) -> Self::Output { - let parts = rhs.as_ref().split("/"); + let parts = rhs.as_ref().split('/'); let mut result = self.inner.clone(); for part in parts { @@ -276,7 +276,7 @@ impl FileStructure { } pub fn contains_files(&self) -> bool { - self.resources.len() > 0 + !self.resources.is_empty() } pub fn paths_applying_with(