diff options
author | pwygab <88221256+merelymyself@users.noreply.github.com> | 2022-09-08 20:29:56 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-09-08 14:29:56 +0200 |
commit | d1e1d0ac3e3d84619121fda58a016207d149a951 (patch) | |
tree | 105a25cd23cd888f496119de45ef499349c0cb60 | |
parent | b398448cd99b146085908ca99e50742f593096b7 (diff) |
remove panic from `lpad` and `rpad`, change truncation behaviour for `lpad` (#6495)
* condense `lpad` and `rpad` into `pad`
* change description
* back to original names, add change
-rw-r--r-- | crates/nu-command/src/strings/str_/lpad.rs | 20 | ||||
-rw-r--r-- | crates/nu-command/src/strings/str_/rpad.rs | 9 |
2 files changed, 25 insertions, 4 deletions
diff --git a/crates/nu-command/src/strings/str_/lpad.rs b/crates/nu-command/src/strings/str_/lpad.rs index 374c02dd9..026fb5525 100644 --- a/crates/nu-command/src/strings/str_/lpad.rs +++ b/crates/nu-command/src/strings/str_/lpad.rs @@ -74,10 +74,10 @@ impl Command for SubCommand { }), }, Example { - description: "Use lpad to truncate a string", + description: "Use lpad to truncate a string to its last three characters", example: "'123456789' | str lpad -l 3 -c '0'", result: Some(Value::String { - val: "123".to_string(), + val: "789".to_string(), span: Span::test_data(), }), }, @@ -105,6 +105,13 @@ fn operate( column_paths: call.rest(engine_state, stack, 0)?, }); + if options.length.expect("this exists") < 0 { + return Err(ShellError::UnsupportedInput( + String::from("The length of the string cannot be negative"), + call.head, + )); + } + let head = call.head; input.map( move |v| { @@ -142,7 +149,14 @@ fn action( let s = *x as usize; if s < val.len() { Value::String { - val: val.chars().take(s).collect::<String>(), + val: val + .chars() + .rev() + .take(s) + .collect::<String>() + .chars() + .rev() + .collect::<String>(), span: head, } } else { diff --git a/crates/nu-command/src/strings/str_/rpad.rs b/crates/nu-command/src/strings/str_/rpad.rs index be5061cb5..2e9f5e463 100644 --- a/crates/nu-command/src/strings/str_/rpad.rs +++ b/crates/nu-command/src/strings/str_/rpad.rs @@ -74,7 +74,7 @@ impl Command for SubCommand { }), }, Example { - description: "Use rpad to truncate a string", + description: "Use rpad to truncate a string to its first three characters", example: "'123456789' | str rpad -l 3 -c '0'", result: Some(Value::String { val: "123".to_string(), @@ -105,6 +105,13 @@ fn operate( column_paths: call.rest(engine_state, stack, 0)?, }); + if options.length.expect("this exists") < 0 { + return Err(ShellError::UnsupportedInput( + String::from("The length of the string cannot be negative"), + call.head, + )); + } + let head = call.head; input.map( move |v| { |