Skip to content

Commit 94c772c

Browse files
committed
sort: support percent arguments to -S option
Add support for parsing percent arguments to the `-S` option. The given percentage specifies a percentage of the total physical memory. For Linux, the total physical memory is read from `/proc/meminfo`. The feature is not yet implemented for other systems. In order to implement the feature, the `uucore::parser::parse_size` function was updated to recognize strings of the form `NNN%`. Fixes #3500
1 parent 39847a7 commit 94c772c

File tree

3 files changed

+97
-2
lines changed

3 files changed

+97
-2
lines changed

src/uu/sort/src/sort.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ impl GlobalSettings {
288288
// GNU sort (8.32) invalid: b, B, 1B, p, e, z, y
289289
let size = Parser::default()
290290
.with_allow_list(&[
291-
"b", "k", "K", "m", "M", "g", "G", "t", "T", "P", "E", "Z", "Y",
291+
"b", "k", "K", "m", "M", "g", "G", "t", "T", "P", "E", "Z", "Y", "%",
292292
])
293293
.with_default_unit("K")
294294
.with_b_byte_count(true)

src/uucore/src/lib/parser/parse_size.rs

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,70 @@
88
99
use std::error::Error;
1010
use std::fmt;
11-
use std::num::IntErrorKind;
11+
#[cfg(target_os = "linux")]
12+
use std::io::BufRead;
13+
use std::num::{IntErrorKind, ParseIntError};
1214

1315
use crate::display::Quotable;
1416

17+
/// Error arising from trying to compute system memory.
18+
enum SystemError {
19+
IOError,
20+
ParseError,
21+
NotFound,
22+
}
23+
24+
impl From<std::io::Error> for SystemError {
25+
fn from(_: std::io::Error) -> Self {
26+
Self::IOError
27+
}
28+
}
29+
30+
impl From<ParseIntError> for SystemError {
31+
fn from(_: ParseIntError) -> Self {
32+
Self::ParseError
33+
}
34+
}
35+
36+
/// Get the total number of bytes of physical memory.
37+
///
38+
/// The information is read from the `/proc/meminfo` file.
39+
///
40+
/// # Errors
41+
///
42+
/// If there is a problem reading the file or finding the appropriate
43+
/// entry in the file.
44+
#[cfg(target_os = "linux")]
45+
fn total_physical_memory() -> Result<u128, SystemError> {
46+
// On Linux, the `/proc/meminfo` file has a table with information
47+
// about memory usage. For example,
48+
//
49+
// MemTotal: 7811500 kB
50+
// MemFree: 1487876 kB
51+
// MemAvailable: 3857232 kB
52+
// ...
53+
//
54+
// We just need to extract the number of `MemTotal`
55+
let table = std::fs::read("/proc/meminfo")?;
56+
for line in table.lines() {
57+
let line = line?;
58+
if line.starts_with("MemTotal:") && line.ends_with("kB") {
59+
let num_kilobytes: u128 = line[9..line.len() - 2].trim().parse()?;
60+
let num_bytes = 1024 * num_kilobytes;
61+
return Ok(num_bytes);
62+
}
63+
}
64+
Err(SystemError::NotFound)
65+
}
66+
67+
/// Get the total number of bytes of physical memory.
68+
///
69+
/// TODO Implement this for non-Linux systems.
70+
#[cfg(not(target_os = "linux"))]
71+
fn total_physical_memory() -> Result<u128, SystemError> {
72+
Err(SystemError::NotFound)
73+
}
74+
1575
/// Parser for sizes in SI or IEC units (multiples of 1000 or 1024 bytes).
1676
///
1777
/// The [`Parser::parse`] function performs the parse.
@@ -133,6 +193,16 @@ impl<'parser> Parser<'parser> {
133193
}
134194
}
135195

196+
// Special case: for percentage, just compute the given fraction
197+
// of the total physical memory on the machine, if possible.
198+
if unit == "%" {
199+
let number: u128 = Self::parse_number(&numeric_string, 10, size)?;
200+
return match total_physical_memory() {
201+
Ok(total) => Ok((number / 100) * total),
202+
Err(_) => Err(ParseSizeError::PhysicalMem(size.to_string())),
203+
};
204+
}
205+
136206
// Compute the factor the unit represents.
137207
// empty string means the factor is 1.
138208
//
@@ -688,4 +758,16 @@ mod tests {
688758
assert_eq!(Ok(94722), parse_size_u64("0x17202"));
689759
assert_eq!(Ok(44251 * 1024), parse_size_u128("0xACDBK"));
690760
}
761+
762+
#[test]
763+
#[cfg(target_os = "linux")]
764+
fn parse_percent() {
765+
assert!(parse_size_u64("0%").is_ok());
766+
assert!(parse_size_u64("50%").is_ok());
767+
assert!(parse_size_u64("100%").is_ok());
768+
assert!(parse_size_u64("100000%").is_ok());
769+
assert!(parse_size_u64("-1%").is_err());
770+
assert!(parse_size_u64("1.0%").is_err());
771+
assert!(parse_size_u64("0x1%").is_err());
772+
}
691773
}

tests/by-util/test_sort.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ fn test_helper(file_name: &str, possible_args: &[&str]) {
2929

3030
#[test]
3131
fn test_buffer_sizes() {
32+
#[cfg(target_os = "linux")]
33+
let buffer_sizes = ["0", "50K", "50k", "1M", "100M", "0%", "10%"];
34+
// TODO Percentage sizes are not yet supported beyond Linux.
35+
#[cfg(not(target_os = "linux"))]
3236
let buffer_sizes = ["0", "50K", "50k", "1M", "100M"];
3337
for buffer_size in &buffer_sizes {
3438
TestScenario::new(util_name!())
@@ -73,6 +77,15 @@ fn test_invalid_buffer_size() {
7377
.code_is(2)
7478
.stderr_only("sort: invalid suffix in --buffer-size argument '100f'\n");
7579

80+
// TODO Percentage sizes are not yet supported beyond Linux.
81+
#[cfg(target_os = "linux")]
82+
new_ucmd!()
83+
.arg("-S")
84+
.arg("0x123%")
85+
.fails()
86+
.code_is(2)
87+
.stderr_only("sort: invalid --buffer-size argument '0x123%'\n");
88+
7689
new_ucmd!()
7790
.arg("-n")
7891
.arg("-S")

0 commit comments

Comments
 (0)