Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/uu/mktemp/src/mktemp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,28 @@ struct Params {
/// assert_eq!(find_last_contiguous_block_of_xs("aXbXcX"), None);
/// ```
fn find_last_contiguous_block_of_xs(s: &str) -> Option<(usize, usize)> {
let j = s.rfind("XXX")? + 3;
let i = s[..j].rfind(|c| c != 'X').map_or(0, |i| i + 1);
Some((i, j))
let bytes = s.as_bytes();

// Find the index just after the last 'X'.
let mut end = None;
for (idx, &b) in bytes.iter().enumerate() {
if b == b'X' {
end = Some(idx + 1);
}
}
let end = end?;
Comment thread
Xylphy marked this conversation as resolved.
Outdated

// Walk left to find the start of the run of Xs that ends at `end`.
let mut start = end - 1;
while start > 0 && bytes[start - 1] == b'X' {
start -= 1;
}

if end - start >= 3 {
Some((start, end))
} else {
None
}
}

impl Params {
Expand Down
37 changes: 37 additions & 0 deletions tests/by-util/test_mktemp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ static TEST_TEMPLATE7: &str = "XXXtemplate";
static TEST_TEMPLATE8: &str = "tempXXXl/ate";
#[cfg(windows)]
static TEST_TEMPLATE8: &str = "tempXXXl\\ate";
static TEST_TEMPLATE9: &str = "XXX_XX";

#[cfg(not(windows))]
const TMPDIR: &str = "TMPDIR";
Expand Down Expand Up @@ -109,6 +110,11 @@ fn test_mktemp_mktemp() {
.env(TMPDIR, &pathname)
.arg(TEST_TEMPLATE8)
.fails();
scene
.ucmd()
.env(TMPDIR, &pathname)
.arg(TEST_TEMPLATE9)
.fails();
}

#[test]
Expand Down Expand Up @@ -168,6 +174,12 @@ fn test_mktemp_mktemp_t() {
.no_stdout()
.stderr_contains("invalid suffix")
.stderr_contains("contains directory separator");
scene
.ucmd()
.env(TMPDIR, &pathname)
.arg("-t")
.arg(TEST_TEMPLATE9)
.fails();
}

#[test]
Expand Down Expand Up @@ -224,6 +236,12 @@ fn test_mktemp_make_temp_dir() {
.arg("-d")
.arg(TEST_TEMPLATE8)
.fails();
scene
.ucmd()
.env(TMPDIR, &pathname)
.arg("-d")
.arg(TEST_TEMPLATE9)
.fails();
}

#[test]
Expand Down Expand Up @@ -280,6 +298,12 @@ fn test_mktemp_dry_run() {
.arg("-u")
.arg(TEST_TEMPLATE8)
.fails();
scene
.ucmd()
.env(TMPDIR, &pathname)
.arg("-u")
.arg(TEST_TEMPLATE9)
.fails();
}

#[test]
Expand Down Expand Up @@ -367,6 +391,13 @@ fn test_mktemp_suffix() {
.arg("suf")
.arg(TEST_TEMPLATE8)
.fails();
scene
.ucmd()
.env(TMPDIR, &pathname)
.arg("--suffix")
.arg("suf")
.arg(TEST_TEMPLATE9)
.fails();
}

#[test]
Expand Down Expand Up @@ -424,6 +455,12 @@ fn test_mktemp_tmpdir() {
.arg(pathname)
.arg(TEST_TEMPLATE8)
.fails();
scene
.ucmd()
.arg("-p")
.arg(pathname)
.arg(TEST_TEMPLATE9)
.fails();
}

#[test]
Expand Down
Loading