-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_emitter.zig
More file actions
75 lines (59 loc) · 2.17 KB
/
event_emitter.zig
File metadata and controls
75 lines (59 loc) · 2.17 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const std = @import("std");
const assert = std.debug.assert;
const stdx = @import("stdx");
const EventEmitter = stdx.EventEmitter;
const Calculator = struct {
const Self = @This();
result: i128 = 0,
pub fn onAdd(self: *Self, event: Operation, operand: i128) void {
assert(event == .add);
self.result += operand;
}
pub fn onSubtract(self: *Self, event: Operation, operand: i128) void {
assert(event == .subtract);
self.result -= operand;
}
pub fn onMultiply(self: *Self, event: Operation, operand: i128) void {
assert(event == .multiply);
self.result *= operand;
}
pub fn onDivide(self: *Self, event: Operation, operand: i128) void {
assert(event == .divide);
assert(operand != 0);
self.result = @divFloor(self.result, operand);
}
pub fn onSetLHS(self: *Self, event: Operation, operand: i128) void {
assert(event == .set);
self.result = operand;
}
};
const Operation = enum {
add,
subtract,
multiply,
divide,
set,
};
pub fn main() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var calculator_ee = EventEmitter(Operation, *Calculator, i128).new();
defer calculator_ee.deinit(allocator);
var calculator = Calculator{};
try calculator_ee.addEventListener(allocator, &calculator, .add, Calculator.onAdd);
try calculator_ee.addEventListener(allocator, &calculator, .subtract, Calculator.onSubtract);
try calculator_ee.addEventListener(allocator, &calculator, .multiply, Calculator.onMultiply);
try calculator_ee.addEventListener(allocator, &calculator, .divide, Calculator.onDivide);
try calculator_ee.addEventListener(allocator, &calculator, .set, Calculator.onSetLHS);
calculator_ee.emit(.set, 10);
assert(calculator.result == 10);
calculator_ee.emit(.add, 1);
assert(calculator.result == 11);
calculator_ee.emit(.subtract, 12);
assert(calculator.result == -1);
calculator_ee.emit(.multiply, 100);
assert(calculator.result == -100);
calculator_ee.emit(.divide, -10);
assert(calculator.result == 10);
}