//! Requests from `update` that `draw` carries out once. `update` sees only //! State and input, so when a key should do something to Session or Store //! (start the microphone, open a dialog, seek a stream), State holds the //! request and Session remembers which ones it has handled: //! //! // State //! seek: sk.Request(f32) = .{}, //! // Session //! seek: sk.Handled = .{}, //! //! // update //! if (in.pressed(.home)) s.seek.send(0); //! // draw //! if (ss.seek.take(s.seek)) |to| cursor = to * len; const std = @import("std"); /// A request carrying `T`, starting at `T`'s zero value. pub fn Request(comptime T: type) type { return struct { value: T = std.mem.zeroes(T), /// Bumped by every `send`, so the same value can be asked for twice. serial: u32 = 0, pub const Value = T; pub fn send(r: *@This(), value: T) void { r.value = value; r.serial +%= 1; } }; } /// Which request a Session has carried out. pub const Handled = struct { serial: ?u32 = null, /// The request's value if it is new to this Session. A fresh Session (a /// restart, or Session's layout changed) counts earlier requests as /// handled: nothing re-fires from saved state, as `Input.started` asks /// of `update`. So take every request on every frame, even when its /// value will be ignored: the first take only catches up. pub fn take(h: *Handled, request: anytype) ?@TypeOf(request).Value { defer h.serial = request.serial; const last = h.serial orelse return null; return if (last == request.serial) null else request.value; } }; test "a request is taken once, and none from before the session" { var r: Request(f32) = .{}; r.send(0.5); var h: Handled = .{}; try std.testing.expectEqual(@as(?f32, null), h.take(r)); r.send(0.25); try std.testing.expectEqual(@as(?f32, 0.25), h.take(r)); try std.testing.expectEqual(@as(?f32, null), h.take(r)); r.send(0.25); try std.testing.expectEqual(@as(?f32, 0.25), h.take(r)); }