summaryrefslogtreecommitdiff
path: root/src/sketch/request.zig
blob: 0b8b4006d2a8bb1a6eb643d27c0bb7509131e714 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//! 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));
}