| 1 | @[heap] |
| 2 | struct Chan[T] { |
| 3 | c chan T |
| 4 | } |
| 5 | |
| 6 | pub type EventListener[T] = fn (T) ! |
| 7 | |
| 8 | pub type Check[T] = fn (T) bool |
| 9 | |
| 10 | struct EventWaiter[T] { |
| 11 | check ?Check[T] |
| 12 | c Chan[T] |
| 13 | } |
| 14 | |
| 15 | pub struct EventController[T] { |
| 16 | mut: |
| 17 | id int |
| 18 | wait_fors map[int]EventWaiter[T] |
| 19 | listeners map[int]EventListener[T] |
| 20 | } |
| 21 | |
| 22 | fn (mut ec EventController[T]) generate_id() int { |
| 23 | return ec.id++ |
| 24 | } |
| 25 | |
| 26 | pub fn (ec EventController[T]) emit(e T) bool { |
| 27 | for i, w in ec.wait_fors { |
| 28 | mut b := false |
| 29 | c := w.check |
| 30 | if c != none { |
| 31 | b = c(e) |
| 32 | } else { |
| 33 | b = true |
| 34 | } |
| 35 | println('${i} passed: ${b}') |
| 36 | return b |
| 37 | } |
| 38 | return false |
| 39 | } |
| 40 | |
| 41 | struct Foo {} |
| 42 | |
| 43 | struct Bar {} |
| 44 | |
| 45 | fn use[T](z EventController[T]) bool { |
| 46 | return z.emit(T{}) |
| 47 | } |
| 48 | |
| 49 | fn test_main() { |
| 50 | assert use(EventController[Foo]{ |
| 51 | wait_fors: { |
| 52 | 0: EventWaiter[Foo]{ |
| 53 | check: fn (t Foo) bool { |
| 54 | return false |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | }) == false |
| 59 | assert use(EventController[Bar]{ |
| 60 | wait_fors: { |
| 61 | 0: EventWaiter[Bar]{} |
| 62 | } |
| 63 | }) == true |
| 64 | } |
| 65 | |