From 6cb8273cceacc5624181fd1d99bf6b3642719e7c Mon Sep 17 00:00:00 2001 From: Chung Leong Date: Fri, 12 Apr 2024 16:58:51 +0200 Subject: [PATCH] Added another pointer example (#277) --- docs/examples/pointer-example-3.js | 26 +++++++++++++++++++ docs/examples/pointer-example-3.txt | 8 ++++++ docs/examples/pointer-example-3.zig | 40 +++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 docs/examples/pointer-example-3.js create mode 100644 docs/examples/pointer-example-3.txt create mode 100644 docs/examples/pointer-example-3.zig diff --git a/docs/examples/pointer-example-3.js b/docs/examples/pointer-example-3.js new file mode 100644 index 00000000..7934e15a --- /dev/null +++ b/docs/examples/pointer-example-3.js @@ -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: [] } }, + ] + } + } + ] +}); diff --git a/docs/examples/pointer-example-3.txt b/docs/examples/pointer-example-3.txt new file mode 100644 index 00000000..340172fa --- /dev/null +++ b/docs/examples/pointer-example-3.txt @@ -0,0 +1,8 @@ +root/ + README (11) + images/ + cat.jpg (8000) + lobster.jpg (16000) + src/ + index.js (31) + empty/ diff --git a/docs/examples/pointer-example-3.zig b/docs/examples/pointer-example-3.zig new file mode 100644 index 00000000..9fffd79a --- /dev/null +++ b/docs/examples/pointer-example-3.zig @@ -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); +}