Skip to content

Commit

Permalink
Added another pointer example (#277)
Browse files Browse the repository at this point in the history
  • Loading branch information
chung-leong committed Apr 12, 2024
1 parent d043119 commit 6cb8273
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
26 changes: 26 additions & 0 deletions docs/examples/pointer-example-3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { printDirectoryTree } from './pointer-example-3.zig';

printDirectoryTree({
name: 'root',
entries: [
{ file: { name: 'README', data: 'Hello world' } },
{
dir: {
name: 'images',
entries: [
{ file: { name: 'cat.jpg', data: new ArrayBuffer(8000) } },
{ file: { name: 'lobster.jpg', data: new ArrayBuffer(16000) } },
]
}
},
{
dir: {
name: 'src',
entries: [
{ file: { name: 'index.js', data: 'while (true) alert("You suck!")' } },
{ dir: { name: 'empty', entries: [] } },
]
}
}
]
});
8 changes: 8 additions & 0 deletions docs/examples/pointer-example-3.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
root/
README (11)
images/
cat.jpg (8000)
lobster.jpg (16000)
src/
index.js (31)
empty/
40 changes: 40 additions & 0 deletions docs/examples/pointer-example-3.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const std = @import("std");

pub const File = struct {
name: []const u8,
data: []const u8,
};
pub const Directory = struct {
name: []const u8,
entries: []const DirectoryEntry,
};
pub const DirectoryEntry = union(enum) {
file: File,
dir: Directory,
};

fn indent(depth: u32) void {
for (0..depth) |_| {
std.debug.print(" ", .{});
}
}

fn printFile(file: File, depth: u32) void {
indent(depth);
std.debug.print("{s} ({d})\n", .{ file.name, file.data.len });
}

fn printDirectory(dir: Directory, depth: u32) void {
indent(depth);
std.debug.print("{s}/\n", .{dir.name});
for (dir.entries) |entry| {
switch (entry) {
.file => |f| printFile(f, depth + 1),
.dir => |d| printDirectory(d, depth + 1),
}
}
}

pub fn printDirectoryTree(dir: Directory) void {
printDirectory(dir, 0);
}

0 comments on commit 6cb8273

Please sign in to comment.