From 61bcf53b33137956de100c2e0b29f781ac033e20 Mon Sep 17 00:00:00 2001 From: Dan Cojocaru Date: Fri, 23 Feb 2024 13:11:02 +0100 Subject: [PATCH] Prevent memory errors on home page --- src/home.zig | 10 +++++++++- src/main.zig | 1 + src/state.zig | 2 ++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/home.zig b/src/home.zig index 33024be..9b4e03e 100644 --- a/src/home.zig +++ b/src/home.zig @@ -72,6 +72,8 @@ fn fetchThread(state: *AppState) !void { } } } + state.home_screen_state.mutex.lock(); + defer state.home_screen_state.mutex.unlock(); if (state.home_screen_state.suggestions.len > 0) { for (state.home_screen_state.suggestions) |suggestion| { allocator.free(suggestion.id); @@ -94,8 +96,14 @@ pub fn render(state: *AppState) !void { } while (raylib.GetCharPressed()) |char| { - hs.station_name.appendAssumeCapacity(@intCast(char)); + if (hs.station_name.items.len < hs.station_name_max_len) { + hs.station_name.appendAssumeCapacity(@intCast(char)); + } } + + state.home_screen_state.mutex.lock(); + defer state.home_screen_state.mutex.unlock(); + while (raylib.GetKeyPressed()) |key| { switch (key) { rl.KEY_BACKSPACE => { diff --git a/src/main.zig b/src/main.zig index 79eb810..5df7526 100644 --- a/src/main.zig +++ b/src/main.zig @@ -32,6 +32,7 @@ pub fn main() !void { .ns_font = raylib.LoadFontEx("./private/ns.ttf", 64, cp, cp_cnt), .home_screen_state = .{ .station_name = std.ArrayListUnmanaged(u8).initBuffer(&station_name_buffer), + .station_name_max_len = station_name_buffer.len - 1, }, .departure_screen_state = .{ .platform = std.ArrayListUnmanaged(u8).initBuffer(&platform_buffer), diff --git a/src/state.zig b/src/state.zig index 8b00391..4584cf1 100644 --- a/src/state.zig +++ b/src/state.zig @@ -13,7 +13,9 @@ pub const HSSuggestion = struct { }; pub const HomeScreenState = struct { + mutex: std.Thread.Mutex = .{}, station_name: std.ArrayListUnmanaged(u8), + station_name_max_len: usize, fetch_thread: ?std.Thread = null, suggestions: []HSSuggestion = &.{}, selection_idx: i8 = 0,