From cebf1f09dff0925b5056bc49c5c43751a168dc30 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Thu, 10 Jun 2021 01:54:10 +0900 Subject: [PATCH 1/2] get_groups_gnu sort with rotate_right --- src/uucore/src/lib/features/entries.rs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/uucore/src/lib/features/entries.rs b/src/uucore/src/lib/features/entries.rs index b94abbe4f..75bf245e4 100644 --- a/src/uucore/src/lib/features/entries.rs +++ b/src/uucore/src/lib/features/entries.rs @@ -95,15 +95,18 @@ pub fn get_groups() -> IOResult> { /// history of a process and its parents could affect the details of /// the result.) pub fn get_groups_gnu(arg_id: Option) -> IOResult> { - let mut groups = get_groups()?; + let groups = get_groups()?; let egid = arg_id.unwrap_or_else(crate::features::process::getegid); - if !groups.is_empty() && *groups.first().unwrap() == egid { - return Ok(groups); - } else if let Some(index) = groups.iter().position(|&x| x == egid) { - groups.remove(index); + Ok(sort_groups(groups, egid)) +} + +fn sort_groups(mut groups: Vec, egid: gid_t) -> Vec { + if let Some(index) = groups.iter().position(|&x| x == egid) { + groups[..index + 1].rotate_right(1); + } else { + groups.insert(0, egid); } - groups.insert(0, egid); - Ok(groups) + groups } #[derive(Copy, Clone)] @@ -308,6 +311,15 @@ pub fn grp2gid(name: &str) -> IOResult { mod test { use super::*; + #[test] + fn test_sort_groups() { + assert_eq!(sort_groups(vec![1, 2, 3], 4), vec![4, 1, 2, 3]); + assert_eq!(sort_groups(vec![1, 2, 3], 3), vec![3, 1, 2]); + assert_eq!(sort_groups(vec![1, 2, 3], 2), vec![2, 1, 3]); + assert_eq!(sort_groups(vec![1, 2, 3], 1), vec![1, 2, 3]); + assert_eq!(sort_groups(vec![1, 2, 3], 0), vec![0, 1, 2, 3]); + } + #[test] fn test_entries_get_groups_gnu() { if let Ok(mut groups) = get_groups() { From 23f655e2a514ee2730601f7ac184d84763e8e07e Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Thu, 10 Jun 2021 11:15:01 +0900 Subject: [PATCH 2/2] Use inclusive range Co-authored-by: Michael Debertol --- src/uucore/src/lib/features/entries.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/uucore/src/lib/features/entries.rs b/src/uucore/src/lib/features/entries.rs index 75bf245e4..7d8c78a2f 100644 --- a/src/uucore/src/lib/features/entries.rs +++ b/src/uucore/src/lib/features/entries.rs @@ -102,7 +102,7 @@ pub fn get_groups_gnu(arg_id: Option) -> IOResult> { fn sort_groups(mut groups: Vec, egid: gid_t) -> Vec { if let Some(index) = groups.iter().position(|&x| x == egid) { - groups[..index + 1].rotate_right(1); + groups[..=index].rotate_right(1); } else { groups.insert(0, egid); }