Login
7 branches 0 tags
Ben (X220/Parabola) Big refactoring, mostly surrounding the GC 4f57ee7 3 years ago 651 Commits
nujel / stdlib / concurrency / async.nuj
;; Nujel - Copyright (C) 2020-2021 - Benjamin Vincent Schulenburg
;; This project uses the MIT license, a copy should be included under /LICENSE
;;
;; Contains everything related to the yield/coroutine system

[def yield-queue #nil]

[defn yield [pred fun] "Evaluates FUN once PRED is true"
  [set! yield-queue [cons [cons pred fun] yield-queue]] #t]

[defn yield-run []
  "Executes pending coroutines if their predicate evaluates to #t"
  [def old yield-queue]
  [set! yield-queue #nil]
  [for-in [cur old]
          [if [[car cur]]
              [[cdr cur]]
              [set! yield-queue [cons cur yield-queue]]]]]

[defn timeout [milliseconds]
  "Returns a function that evaluates to true once MILLISECONDS have passed"
  [def goal [+ [time/milliseconds] milliseconds]]
  [fn []
      [> [time/milliseconds] goal]]]

[defn event-bind [event id handler]
  "Bind handler to be evaluated when event-name fires, overwriting whichever handler has been associated with id before."
  [tree/set! event id handler]]

[defmacro event-clear [event]
  "Clears all event handlers for event-name"
  `[set! ~event @[]]]

[defn event-fire [event val]
  "Applies ...val to all event handlers associated with event-name"
  [for-in [h [tree/values event]]
          [h val]]]