commit
597a363673
|
@ -453,6 +453,8 @@ pub const Dir = struct {
|
|||
|
||||
pub const Error = IteratorError;
|
||||
|
||||
/// Memory such as file names referenced in this returned entry becomes invalid
|
||||
/// with subsequent calls to `next`, as well as when this `Dir` is deinitialized.
|
||||
pub fn next(self: *Self) Error!?Entry {
|
||||
start_over: while (true) {
|
||||
const w = os.windows;
|
||||
|
|
|
@ -3,10 +3,53 @@ const testing = std.testing;
|
|||
const builtin = std.builtin;
|
||||
const fs = std.fs;
|
||||
const mem = std.mem;
|
||||
const wasi = std.os.wasi;
|
||||
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
const Dir = std.fs.Dir;
|
||||
const File = std.fs.File;
|
||||
const tmpDir = testing.tmpDir;
|
||||
|
||||
test "Dir.Iterator" {
|
||||
var tmp_dir = tmpDir(.{ .iterate = true });
|
||||
defer tmp_dir.cleanup();
|
||||
|
||||
// First, create a couple of entries to iterate over.
|
||||
const file = try tmp_dir.dir.createFile("some_file", .{});
|
||||
file.close();
|
||||
|
||||
try tmp_dir.dir.makeDir("some_dir");
|
||||
|
||||
var arena = ArenaAllocator.init(testing.allocator);
|
||||
defer arena.deinit();
|
||||
|
||||
var entries = std.ArrayList(Dir.Entry).init(&arena.allocator);
|
||||
|
||||
// Create iterator.
|
||||
var iter = tmp_dir.dir.iterate();
|
||||
while (try iter.next()) |entry| {
|
||||
// We cannot just store `entry` as on Windows, we're re-using the name buffer
|
||||
// which means we'll actually share the `name` pointer between entries!
|
||||
const name = try arena.allocator.dupe(u8, entry.name);
|
||||
try entries.append(Dir.Entry{ .name = name, .kind = entry.kind });
|
||||
}
|
||||
|
||||
testing.expect(entries.items.len == 2); // note that the Iterator skips '.' and '..'
|
||||
testing.expect(contains(&entries, Dir.Entry{ .name = "some_file", .kind = Dir.Entry.Kind.File }));
|
||||
testing.expect(contains(&entries, Dir.Entry{ .name = "some_dir", .kind = Dir.Entry.Kind.Directory }));
|
||||
}
|
||||
|
||||
fn entry_eql(lhs: Dir.Entry, rhs: Dir.Entry) bool {
|
||||
return mem.eql(u8, lhs.name, rhs.name) and lhs.kind == rhs.kind;
|
||||
}
|
||||
|
||||
fn contains(entries: *const std.ArrayList(Dir.Entry), el: Dir.Entry) bool {
|
||||
for (entries.items) |entry| {
|
||||
if (entry_eql(entry, el)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
test "readAllAlloc" {
|
||||
var tmp_dir = tmpDir(.{});
|
||||
defer tmp_dir.cleanup();
|
||||
|
@ -237,7 +280,7 @@ test "fs.copyFile" {
|
|||
try expectFileContents(tmp.dir, dest_file2, data);
|
||||
}
|
||||
|
||||
fn expectFileContents(dir: fs.Dir, file_path: []const u8, data: []const u8) !void {
|
||||
fn expectFileContents(dir: Dir, file_path: []const u8, data: []const u8) !void {
|
||||
const contents = try dir.readFileAlloc(testing.allocator, file_path, 1000);
|
||||
defer testing.allocator.free(contents);
|
||||
|
||||
|
|
Loading…
Reference in New Issue