stack.scm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. ;; Atomic stack
  2. ;;;; Copyright (C) 2016 Andy Wingo <wingo@pobox.com>
  3. ;;;; Copyright (C) 2017 Christopher Allan Webber <cwebber@dustycloud.org>
  4. ;;;;
  5. ;;;; This library is free software; you can redistribute it and/or
  6. ;;;; modify it under the terms of the GNU Lesser General Public
  7. ;;;; License as published by the Free Software Foundation; either
  8. ;;;; version 3 of the License, or (at your option) any later version.
  9. ;;;;
  10. ;;;; This library is distributed in the hope that it will be useful,
  11. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. ;;;; Lesser General Public License for more details.
  14. ;;;;
  15. ;;;; You should have received a copy of the GNU Lesser General Public
  16. ;;;; License along with this library; if not, write to the Free Software
  17. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. (define-module (fibers stack)
  19. #:use-module (ice-9 atomic)
  20. #:use-module (ice-9 match)
  21. #:export (make-empty-stack
  22. stack-empty?
  23. stack-push!
  24. stack-push-list!
  25. stack-pop!
  26. stack-pop-all!
  27. stack-filter!))
  28. (define (make-empty-stack)
  29. (make-atomic-box '()))
  30. (define (stack-empty? stack)
  31. (match (atomic-box-ref stack)
  32. (() #t)
  33. (_ #f)))
  34. (define-inlinable (update! box f)
  35. (let spin ((x (atomic-box-ref box)))
  36. (call-with-values (lambda () (f x))
  37. (lambda (x* ret)
  38. (if (eq? x x*)
  39. ret
  40. (let ((x** (atomic-box-compare-and-swap! box x x*)))
  41. (if (eq? x x**)
  42. ret
  43. (spin x**))))))))
  44. (define (stack-push! sbox elt)
  45. (update! sbox (lambda (stack) (values (cons elt stack) #f))))
  46. (define (stack-push-list! sbox elts)
  47. (update! sbox (lambda (stack) (values (append elts stack) #f))))
  48. (define* (stack-pop! sbox #:optional default)
  49. (update! sbox (lambda (stack)
  50. (match stack
  51. ((elt . stack) (values stack elt))
  52. (_ (values stack default))))))
  53. (define (stack-pop-all! sbox)
  54. (atomic-box-swap! sbox '()))
  55. (define (stack-filter! sbox pred)
  56. (update! sbox (lambda (stack)
  57. (values (filter pred stack) #f))))