Skip to content

Instantly share code, notes, and snippets.

@skejeton
Created September 20, 2022 12:12
Show Gist options
  • Save skejeton/f727435ac38ae18cd5cae467e7f0432c to your computer and use it in GitHub Desktop.
Save skejeton/f727435ac38ae18cd5cae467e7f0432c to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <stdlib.h>
#include "../../lib/umka/src/umka_api.h"
#include <string.h>
#ifdef __unix__
#include <dirent.h>
// 0 : DirectoryPath : str
// R : DirPtr : ^void
void ToedExtern_OpenDir(UmkaStackSlot p[], UmkaStackSlot *r) {
r->ptrVal = opendir(p[0].ptrVal);
}
// 0 : IsDirectory : ^uint
// 1 : DirectoryName : ^str
// 2 : DirPtr : ^void
// R : IsGoing : uint
void ToedExtern_ReadDir(UmkaStackSlot p[], UmkaStackSlot *r) {
struct dirent *entry = readdir(p[2].ptrVal);
if (entry != NULL) {
*(uint64_t*)p[0].ptrVal = entry->d_type == DT_DIR;
*(char**)p[1].ptrVal = (void*)entry->d_name;
}
r->uintVal = entry ? 1 : 0;
}
// 0 : DirPtr : ^void
void ToedExtern_CloseDir(UmkaStackSlot p[], UmkaStackSlot *r) {
closedir(p[0].ptrVal);
}
#else
#error "Unsupported platform."
#endif
fn ToedExtern_OpenDir*(path: str): ^void;
fn ToedExtern_ReadDir*(dir: ^void, o_name: ^str, o_isdir: ^uint): uint;
fn ToedExtern_CloseDir*(dir: ^void)
import ("external.um")
type Entry* = struct {
name: str
isDir: bool
}
type EntryReader* = struct {
dir: ^void
}
fn (r: ^EntryReader) next*(o_entry: ^Entry): bool {
var (name: str; isDir: uint)
ok := external.ToedExtern_ReadDir(r.dir, &name, &isDir)
// Add empty string to force umka to make a new copy.
o_entry.name = ""+name
o_entry.isDir = isDir != 0
return ok != 0
}
fn (r: ^EntryReader) readAll*(): []Entry {
entries := []Entry{}
var (entry: Entry)
for r.next(&entry) {
entries = append(entries, entry)
}
return entries
}
fn (r: ^EntryReader) close*() {
external.ToedExtern_CloseDir(r.dir)
}
fn openDir*(path: str): EntryReader {
return EntryReader{external.ToedExtern_OpenDir(path)}
}
fn readAll*(path: str): []Entry {
r := openDir(path)
v := r.readAll()
r.close()
return v
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment