Compare commits

..

No commits in common. "26f342e51888300c065fb614c7d4a60246ffd8b0" and "53a369952e1ebc4948495aca05655757f241178f" have entirely different histories.

4 changed files with 119 additions and 183 deletions

View File

@ -11,9 +11,7 @@ const sys = @import("./sys.zig");
/// Entry point. /// Entry point.
/// ///
pub fn main() anyerror!void { pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; return nosuspend await async sys.runGraphics(anyerror, run);
return nosuspend await async sys.runGraphics(gpa.allocator(), anyerror, run);
} }
test { test {

View File

@ -1,17 +1,11 @@
const io = @import("./io.zig"); const io = @import("./io.zig");
const std = @import("std"); const std = @import("std");
///
/// Returns a fixed-size stack type of `Element`s.
///
pub fn Fixed(comptime Element: type) type { pub fn Fixed(comptime Element: type) type {
return struct { return struct {
filled: usize = 0, filled: usize = 0,
buffer: []Element, buffer: []Element,
///
/// Stack type.
///
const Self = @This(); const Self = @This();
/// ///
@ -63,8 +57,8 @@ pub fn Fixed(comptime Element: type) type {
/// ///
/// Attempts to push `element` into `self`, returning a [FixedPushError] if it failed. /// Attempts to push `element` into `self`, returning a [FixedPushError] if it failed.
/// ///
pub fn push(self: *Self, element: Element) PushError!void { pub fn push(self: *Self, element: Element) FixedPushError!void {
if (self.filled == self.buffer.len) return error.OutOfMemory; if (self.filled == self.buffer.len) return error.Overflow;
self.buffer[self.filled] = element; self.buffer[self.filled] = element;
self.filled += 1; self.filled += 1;
@ -74,10 +68,10 @@ pub fn Fixed(comptime Element: type) type {
/// Attempts to push all of `elements` into `self`, returning a [FixedPushError] if it /// Attempts to push all of `elements` into `self`, returning a [FixedPushError] if it
/// failed. /// failed.
/// ///
pub fn pushAll(self: *Self, elements: []const u8) PushError!void { pub fn pushAll(self: *Self, elements: []const u8) FixedPushError!void {
const filled = (self.filled + elements.len); const filled = (self.filled + elements.len);
if (filled > self.buffer.len) return error.OutOfMemory; if (filled > self.buffer.len) return error.Overflow;
std.mem.copy(u8, self.buffer[self.filled ..], elements); std.mem.copy(u8, self.buffer[self.filled ..], elements);
@ -87,9 +81,15 @@ pub fn Fixed(comptime Element: type) type {
} }
/// ///
/// Potential errors that may occur while trying to push one or more elements into a stack. /// Potential errors that may occur while trying to push one or more elements into a stack of a
/// known maximum size.
/// ///
pub const PushError = std.mem.Allocator.Error; /// [FinitePushError.Overflow] is returned if the stack does not have sufficient capacity to hold a
/// given set of elements.
///
pub const FixedPushError = error {
Overflow,
};
test { test {
const testing = std.testing; const testing = std.testing;
@ -103,8 +103,8 @@ test {
try testing.expectEqual(stack.pop(), 69); try testing.expectEqual(stack.pop(), 69);
try stack.pushAll(&.{42, 10, 95, 0}); try stack.pushAll(&.{42, 10, 95, 0});
try testing.expectEqual(stack.count(), 4); try testing.expectEqual(stack.count(), 4);
try testing.expectError(PushError.OutOfMemory, stack.push(1)); try testing.expectError(FixedPushError.Overflow, stack.push(1));
try testing.expectError(PushError.OutOfMemory, stack.pushAll(&.{1, 11, 11})); try testing.expectError(FixedPushError.Overflow, stack.pushAll(&.{1, 11, 11}));
stack.clear(); stack.clear();

View File

@ -35,7 +35,6 @@ pub const AppContext = opaque {
/// Internal state of the event loop hidden from the API consumer. /// Internal state of the event loop hidden from the API consumer.
/// ///
const Implementation = struct { const Implementation = struct {
user_path_prefix: [*]u8,
data_file_system: FileSystem, data_file_system: FileSystem,
user_file_system: FileSystem, user_file_system: FileSystem,
message_semaphore: *ext.SDL_sem, message_semaphore: *ext.SDL_sem,
@ -105,7 +104,6 @@ pub const AppContext = opaque {
ext.SDL_DestroyMutex(implementation.message_mutex); ext.SDL_DestroyMutex(implementation.message_mutex);
ext.SDL_DestroySemaphore(implementation.message_semaphore); ext.SDL_DestroySemaphore(implementation.message_semaphore);
ext.SDL_free(implementation.user_path_prefix);
} }
/// ///
@ -136,25 +134,14 @@ pub const AppContext = opaque {
/// ///
/// Returns the created [Implementation] value on success or [InitError] on failure. /// Returns the created [Implementation] value on success or [InitError] on failure.
/// ///
fn init(allocator: std.mem.Allocator, fn init(data_archive_file_access: FileAccess,
data_archive_file_access: FileAccess) InitError!Implementation { user_path_prefix: []const u8) InitError!Implementation {
const user_path_prefix = ext.SDL_GetPrefPath("ona", "ona") orelse
return error.OutOfMemory;
return Implementation{ return Implementation{
.user_file_system = .{.native = .{.path_prefix =
user_path_prefix[0 .. std.mem.len(user_path_prefix)]}},
.message_semaphore = ext.SDL_CreateSemaphore(0) orelse return error.OutOfSemaphores, .message_semaphore = ext.SDL_CreateSemaphore(0) orelse return error.OutOfSemaphores,
.message_mutex = ext.SDL_CreateMutex() orelse return error.OutOfMutexes, .message_mutex = ext.SDL_CreateMutex() orelse return error.OutOfMutexes,
.user_path_prefix = user_path_prefix, .data_file_system = .{.archive = .{.file_access = data_archive_file_access}},
.user_file_system = .{.native = .{.path_prefix = user_path_prefix}},
.data_file_system = .{.archive = .{
.file_access = data_archive_file_access,
.index_cache = try FileSystem.ArchiveIndexCache.init(allocator),
}},
.message_thread = null, .message_thread = null,
}; };
} }
@ -364,7 +351,7 @@ pub const FileSystem = union(enum) {
archive: struct { archive: struct {
file_access: FileAccess, file_access: FileAccess,
index_cache: ArchiveIndexCache, index_cache: *table.Dynamic([]const u8, ArchiveEntry, table.string_context),
entry_table: [max_open_entries]ArchiveEntry = entry_table: [max_open_entries]ArchiveEntry =
std.mem.zeroes([max_open_entries]ArchiveEntry), std.mem.zeroes([max_open_entries]ArchiveEntry),
@ -381,8 +368,6 @@ pub const FileSystem = union(enum) {
cursor: u64, cursor: u64,
}; };
const ArchiveIndexCache = table.Hashed([]const u8, oar.Entry, table.string_context);
/// ///
/// Platform-agnostic mechanism for referencing files and directories on a [FileSystem]. /// Platform-agnostic mechanism for referencing files and directories on a [FileSystem].
/// ///
@ -462,23 +447,23 @@ pub const FileSystem = union(enum) {
.archive => |*archive| { .archive => |*archive| {
if (mode != .readonly) return error.ModeUnsupported; if (mode != .readonly) return error.ModeUnsupported;
for (archive.entry_table) |*entry| if (entry.using == null) { for (archive.entry_table) |_, index| {
const entry_path = path.buffer[0 .. path.length]; if (archive.entry_table[index].using == null) {
const archive_path = path.buffer[0 .. path.length];
entry.* = .{
.header = find_header: {
if (archive.index_cache.lookup(entry_path)) |header|
break: find_header header.*;
const entry_header = archive.index_cache.lookup(archive_path) orelse {
const header = oar.Entry.find(archive.file_access, const header = oar.Entry.find(archive.file_access,
entry_path) catch return error.FileNotFound; archive_path) catch return error.FileNotFound;
archive.index_cache.insert(archive_path, header) catch {
// If caching fails... oh well... // If caching fails... oh well...
archive.index_cache.insert(entry_path, header) catch {}; };
break: find_header header; break header;
}, };
archive.entry_table[index] = .{
.header = entry_header,
.using = &archive.file_access, .using = &archive.file_access,
.cursor = 0, .cursor = 0,
}; };
@ -542,7 +527,7 @@ pub const FileSystem = union(enum) {
}; };
return FileAccess{ return FileAccess{
.context = entry, .context = &archive.entry_table[index],
.implementation = &.{ .implementation = &.{
.close = Implementation.close, .close = Implementation.close,
@ -553,7 +538,8 @@ pub const FileSystem = union(enum) {
.seekToEnd = Implementation.seekToEnd, .seekToEnd = Implementation.seekToEnd,
}, },
}; };
}; }
}
return error.OutOfFiles; return error.OutOfFiles;
}, },
@ -819,7 +805,7 @@ pub const RunError = error {
/// Should an error from `run` occur, an `Error` is returned, otherwise a [RunError] is returned if /// Should an error from `run` occur, an `Error` is returned, otherwise a [RunError] is returned if
/// the underlying runtime fails and is logged. /// the underlying runtime fails and is logged.
/// ///
pub fn runGraphics(allocator: std.mem.Allocator, comptime Error: anytype, pub fn runGraphics(comptime Error: anytype,
comptime run: GraphicsRunner(Error)) (RunError || Error)!void { comptime run: GraphicsRunner(Error)) (RunError || Error)!void {
if (ext.SDL_Init(ext.SDL_INIT_EVERYTHING) != 0) { if (ext.SDL_Init(ext.SDL_INIT_EVERYTHING) != 0) {
@ -855,6 +841,14 @@ pub fn runGraphics(allocator: std.mem.Allocator, comptime Error: anytype,
defer ext.SDL_DestroyRenderer(renderer); defer ext.SDL_DestroyRenderer(renderer);
const user_path_prefix = ext.SDL_GetPrefPath("ona", "ona") orelse {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to load user path");
return error.InitFailure;
};
defer ext.SDL_free(user_path_prefix);
var cwd_file_system = FileSystem{.native =.{.path_prefix = "./"}}; var cwd_file_system = FileSystem{.native =.{.path_prefix = "./"}};
var data_archive_file_access = try (try cwd_file_system. var data_archive_file_access = try (try cwd_file_system.
@ -862,7 +856,9 @@ pub fn runGraphics(allocator: std.mem.Allocator, comptime Error: anytype,
defer data_archive_file_access.close(); defer data_archive_file_access.close();
var app_context = AppContext.Implementation.init(allocator, data_archive_file_access) catch |err| { var app_context = AppContext.Implementation.init(data_archive_file_access,
user_path_prefix[0 .. std.mem.len(user_path_prefix)]) catch |err| {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, switch (err) { ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, switch (err) {
error.OutOfMemory => "Failed to allocate necessary memory", error.OutOfMemory => "Failed to allocate necessary memory",
error.OutOfMutexes => "Failed to create file-system work lock", error.OutOfMutexes => "Failed to create file-system work lock",

View File

@ -1,119 +1,61 @@
const std = @import("std"); const std = @import("std");
/// pub fn Dynamic(comptime Key: type, comptime Value: type, comptime key_context: KeyContext(Key)) type {
/// Returns a hash-backed table type of `Value`s indexed by `Key` and using `key_context` as the key
/// context.
///
pub fn Hashed(comptime Key: type, comptime Value: type,
comptime key_context: KeyContext(Key)) type {
const Allocator = std.mem.Allocator;
return struct { return struct {
allocator: Allocator, load_maximum: f32,
load_limit: f32, buckets_used: usize,
buckets: []Bucket, buckets: []Bucket,
filled: usize,
/// ///
/// A slot in the hash table. ///
/// ///
const Bucket = struct { const Bucket = struct {
maybe_entry: ?struct { maybe_entry: ?struct {
key: Key, key: Key,
value: Value, value: Value,
} = null, },
maybe_next_index: ?usize = null, maybe_next_index: ?usize,
}; };
/// ///
/// Hash table type. ///
/// ///
const Self = @This(); const Self = @This();
/// ///
/// Searches for `key` to delete it, returning the deleted value or `null` if no matching
/// key was found.
/// ///
pub fn remove(self: Self, key: Key) ?Value { ///
var bucket = &(self.buckets[@mod(key_context.hash(key), self.buckets.len)]); pub fn delete(self: Self, key: Key) bool {
_ = key;
if (bucket.maybe_entry) |*entry| if (key_context.equals(entry.key, key)) { _ = self;
defer entry.value = null;
self.filled -= 1;
return entry.value;
};
while (bucket.maybe_next_index) |index| {
bucket = &(self.buckets[index]);
if (bucket.maybe_entry) |*entry| if (key_context.equals(entry.key, key)) {
defer entry.value = null;
self.filled -= 1;
return entry.value;
};
}
return null;
}
pub fn init(allocator: Allocator) Allocator.Error!Self {
return Self{
.buckets = try allocator.alloc(Bucket, 4),
.filled = 0,
.allocator = allocator,
.load_limit = 0.75,
};
} }
/// ///
/// Attempts to insert the value at `key` to be `value` in `self`, returning an
/// [InsertError] if it fails.
/// ///
pub fn insert(self: *Self, key: Key, value: Value) InsertError!void { ///
if (self.loadFactor() >= self.load_limit) { pub fn insert(self: Self, key: Key, value: Value) InsertError!void {
const old_buckets = self.buckets; if ((@intToFloat(f32, self.buckets_used) / @intToFloat(
f32, self.buckets.len)) >= self.load_maximum) try self.rehash();
defer self.allocator.free(old_buckets);
self.buckets = try self.allocator.alloc(Bucket, old_buckets.len * 2);
for (old_buckets) |bucket, index| self.buckets[index] = bucket;
}
var hash = @mod(key_context.hash(key), self.buckets.len); var hash = @mod(key_context.hash(key), self.buckets.len);
while (true) { while (true) {
const bucket = &(self.buckets[hash]); const bucket = &(self.buckets[hash]);
if (key_context.equals((bucket.maybe_entry orelse { const entry = &(bucket.maybe_entry orelse {
bucket.maybe_entry = .{ bucket.maybe_entry = .{
.key = key, .key = key,
.value = value .value = value
}; };
});
self.filled += 1; if (key_context.equals(entry.key, key)) return error.KeyExists;
break; hash = @mod(hashHash(hash), self.buckets.len);
}).key, key)) return error.KeyExists;
hash = @mod(hash + 1, self.buckets.len);
} }
} }
///
/// Returns the current load factor of `self`, which is derived from the number of capacity
/// that has been filled.
///
pub fn loadFactor(self: Self) f32 {
return @intToFloat(f32, self.filled) / @intToFloat(f32, self.buckets.len);
}
/// ///
/// Searches for a value indexed with `key` in `self`, returning it or `null` if no matching /// Searches for a value indexed with `key` in `self`, returning it or `null` if no matching
/// entry was found. /// entry was found.
@ -139,7 +81,7 @@ pub fn Hashed(comptime Key: type, comptime Value: type,
/// ///
/// ///
/// ///
pub const InsertError = std.mem.Allocator.Error || error { pub const InsertError = std.mem.Allocator || error {
KeyExists, KeyExists,
}; };