Login
7 branches 0 tags
Ben (Win10) Fixed MacOS releases e11cffc 3 years ago 584 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 new #nil]
       [for-in [cur yield-queue]
               [if [[car cur]]
                   [[cdr cur]]
                   [set! new [cons cur new]]]]
       [set! yield-queue new]]

[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]]]