fix overflow on negative bytes (#7070)

This commit is contained in:
David Matos 2022-11-10 22:33:15 +01:00 committed by GitHub
parent 18d7e64660
commit 312e9bf5d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 5 deletions

View File

@ -74,3 +74,15 @@ fn into_filesize_filesize() {
assert!(actual.out.contains("3.0 KiB"));
}
#[test]
fn into_filesize_negative_filesize() {
let actual = nu!(
cwd: ".", pipeline(
r#"
-3kib | into filesize
"#
));
assert!(actual.out.contains("-3.0 KiB"));
}

View File

@ -3089,7 +3089,7 @@ pub fn format_filesize(num_bytes: i64, format_value: &str, filesize_metric: bool
// Allow the user to specify how they want their numbers formatted
let filesize_format_var = get_filesize_format(format_value, filesize_metric);
let byte = byte_unit::Byte::from_bytes(num_bytes as u128);
let byte = byte_unit::Byte::from_bytes(num_bytes.unsigned_abs() as u128);
let adj_byte =
if filesize_format_var.0 == byte_unit::ByteUnit::B && filesize_format_var.1 == "auto" {
byte.get_appropriate_unit(!filesize_metric)
@ -3102,14 +3102,25 @@ pub fn format_filesize(num_bytes: i64, format_value: &str, filesize_metric: bool
let locale = get_system_locale();
let locale_byte = adj_byte.get_value() as u64;
let locale_byte_string = locale_byte.to_formatted_string(&locale);
if filesize_format_var.1 == "auto" {
format!("{} B", locale_byte_string)
let locale_signed_byte_string = if num_bytes.is_negative() {
format!("-{}", locale_byte_string)
} else {
locale_byte_string
};
if filesize_format_var.1 == "auto" {
format!("{} B", locale_signed_byte_string)
} else {
locale_signed_byte_string
}
}
_ => {
if num_bytes.is_negative() {
format!("-{}", adj_byte.format(1))
} else {
adj_byte.format(1)
}
}
_ => adj_byte.format(1),
}
}

View File

@ -104,3 +104,8 @@ fn floating_add() -> TestResult {
fn precedence_of_or_groups() -> TestResult {
run_test(r#"4 mod 3 == 0 || 5 mod 5 == 0"#, "true")
}
#[test]
fn test_filesize_op() -> TestResult {
run_test("-5kb + 4kb", "-1,000 B")
}