Skip to content

Commit 7d70434

Browse files
committed
auto merge of #13720 : aturon/rust/walk_dir-perf, r=alexcrichton
The `walk_dir` iterator was simulating a queue using a vector (in particular, using `shift`), leading to O(n^2) performance. Since the order was not well-specified (see issue #13411), the simplest fix is to use the vector as a stack (and thus yield a depth-first traversal). This patch does exactly that, and adds a test checking for depth-first behavior. Note that the underlying `readdir` function does not specify any particular order, nor does the system call it uses. Closes #13411.
2 parents 3485d90 + b536d2b commit 7d70434

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/libstd/io/fs.rs

+29-2
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,8 @@ pub fn readdir(path: &Path) -> IoResult<Vec<Path>> {
491491

492492
/// Returns an iterator which will recursively walk the directory structure
493493
/// rooted at `path`. The path given will not be iterated over, and this will
494-
/// perform iteration in a top-down order.
494+
/// perform iteration in some top-down order. The contents of unreadable
495+
/// subdirectories are ignored.
495496
pub fn walk_dir(path: &Path) -> IoResult<Directories> {
496497
Ok(Directories { stack: try!(readdir(path)) })
497498
}
@@ -503,7 +504,7 @@ pub struct Directories {
503504

504505
impl Iterator<Path> for Directories {
505506
fn next(&mut self) -> Option<Path> {
506-
match self.stack.shift() {
507+
match self.stack.pop() {
507508
Some(path) => {
508509
if path.is_dir() {
509510
match readdir(&path) {
@@ -970,6 +971,32 @@ mod test {
970971
check!(rmdir(dir));
971972
})
972973

974+
iotest!(fn file_test_walk_dir() {
975+
let tmpdir = tmpdir();
976+
let dir = &tmpdir.join("walk_dir");
977+
check!(mkdir(dir, io::UserRWX));
978+
979+
let dir1 = &dir.join("01/02/03");
980+
check!(mkdir_recursive(dir1, io::UserRWX));
981+
check!(File::create(&dir1.join("04")));
982+
983+
let dir2 = &dir.join("11/12/13");
984+
check!(mkdir_recursive(dir2, io::UserRWX));
985+
check!(File::create(&dir2.join("14")));
986+
987+
let mut files = check!(walk_dir(dir));
988+
let mut cur = [0u8, .. 2];
989+
for f in files {
990+
let stem = f.filestem_str().unwrap();
991+
let root = stem[0] - ('0' as u8);
992+
let name = stem[1] - ('0' as u8);
993+
assert!(cur[root as uint] < name);
994+
cur[root as uint] = name;
995+
}
996+
997+
check!(rmdir_recursive(dir));
998+
})
999+
9731000
iotest!(fn recursive_mkdir() {
9741001
let tmpdir = tmpdir();
9751002
let dir = tmpdir.join("d1/d2");

0 commit comments

Comments
 (0)