mirror of
https://github.com/RGBCube/uutils-coreutils
synced 2025-07-28 03:27:44 +00:00
Merge pull request #5402 from Luv-Ray/short-circuit
`expr`: short-circuit evaluation for `&`
This commit is contained in:
commit
21c8538e0b
2 changed files with 34 additions and 9 deletions
|
@ -166,17 +166,27 @@ impl AstNode {
|
||||||
{
|
{
|
||||||
let mut out = Vec::with_capacity(operands.len());
|
let mut out = Vec::with_capacity(operands.len());
|
||||||
let mut operands = operands.iter();
|
let mut operands = operands.iter();
|
||||||
// check the first value before `|`, stop evaluate and return directly if it is true.
|
|
||||||
// push dummy to pass the check of `len() == 2`
|
|
||||||
if op_type == "|" {
|
|
||||||
if let Some(value) = operands.next() {
|
if let Some(value) = operands.next() {
|
||||||
let value = value.evaluate()?;
|
let value = value.evaluate()?;
|
||||||
out.push(value.clone());
|
out.push(value.clone());
|
||||||
|
// short-circuit evaluation for `|` and `&`
|
||||||
|
// push dummy to pass `assert!(values.len() == 2);`
|
||||||
|
match op_type.as_ref() {
|
||||||
|
"|" => {
|
||||||
if value_as_bool(&value) {
|
if value_as_bool(&value) {
|
||||||
out.push(String::from("dummy"));
|
out.push(String::from("dummy"));
|
||||||
return Ok(out);
|
return Ok(out);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"&" => {
|
||||||
|
if !value_as_bool(&value) {
|
||||||
|
out.push(String::from("dummy"));
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for operand in operands {
|
for operand in operands {
|
||||||
|
|
|
@ -155,6 +155,21 @@ fn test_and() {
|
||||||
.args(&["-14", "&", "1"])
|
.args(&["-14", "&", "1"])
|
||||||
.run()
|
.run()
|
||||||
.stdout_is("-14\n");
|
.stdout_is("-14\n");
|
||||||
|
|
||||||
|
new_ucmd!()
|
||||||
|
.args(&["0", "&", "a", "/", "5"])
|
||||||
|
.run()
|
||||||
|
.stdout_only("0\n");
|
||||||
|
|
||||||
|
new_ucmd!()
|
||||||
|
.args(&["", "&", "a", "/", "5"])
|
||||||
|
.run()
|
||||||
|
.stdout_only("0\n");
|
||||||
|
|
||||||
|
new_ucmd!()
|
||||||
|
.args(&["-1", "&", "10", "/", "5"])
|
||||||
|
.succeeds()
|
||||||
|
.stdout_only("-1\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue