Skip to content

Commit 9db21a9

Browse files
Nekrolmsylvestre
authored andcommitted
Remove extra lookups and memory allocations from tsort graph construction
1 parent c862fc0 commit 9db21a9

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/uu/tsort/src/tsort.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@ enum TsortError {
4242

4343
impl UError for TsortError {}
4444

45-
46-
4745
#[uucore::main]
4846
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
4947
let matches = uucore::clap_localization::handle_clap_result(uu_app(), args)?;
@@ -65,17 +63,23 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
6563

6664
// Create the directed graph from pairs of tokens in the input data.
6765
let mut g = Graph::new(input.to_string_lossy().to_string());
68-
69-
let mut edgetokens = data.split_whitespace();
70-
66+
// Input is considered to be in the format
67+
// From1 To1 From2 To2 ...
68+
// with tokens separated by whitespaces
69+
let mut edge_tokens = data.split_whitespace();
70+
// Note: this is equivalent to iterating over edge_tokens.chunks(2)
71+
// but chunks() exists only for slices and would require unnecessary Vec allocation.
72+
// Itertools::chunks() is not used due to unnecessary overhead for internal RefCells
7173
loop {
72-
let Some(a) = edgetokens.next() else {
74+
// Try take next pair of tokens
75+
let Some(from) = edge_tokens.next() else {
76+
// no more tokens -> end of input. Graph constructed
7377
break;
7478
};
75-
let Some(b) = edgetokens.next() else {
79+
let Some(to) = edge_tokens.next() else {
7680
return Err(TsortError::NumTokensOdd(input.to_string_lossy().to_string()).into());
7781
};
78-
g.add_edge(a, b);
82+
g.add_edge(from, to);
7983
}
8084

8185
g.run_tsort();

0 commit comments

Comments
 (0)