Login
7 branches 0 tags
Benjamin Vincent Schulenburg Rewrote the readme a bit e90d4aa 3 years ago 439 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]

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

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

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

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

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