ring-buffer.sl 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. %
  2. % RING-BUFFER.SL - Ring Buffers
  3. %
  4. % Author: Alan Snyder
  5. % Hewlett-Packard/CRC
  6. % Date: 6 July 1982
  7. %
  8. % This file implements general ring buffers.
  9. % This file requires COMMON, NSTRUCT.
  10. % Modifications by William Galway:
  11. % "defun" -> "de" so TAGS can find things.
  12. % "setq" -> "setf"
  13. (defstruct (ring-buffer)
  14. ring-buffer-vector % Elements 1..N are used.
  15. ring-buffer-top-ptr % Elements 1..Top are valid.
  16. ring-buffer-pointer % Element Vector[POINTER] is current.
  17. )
  18. (de ring-buffer-create (number-of-elements)
  19. (let ((rb (make-ring-buffer)))
  20. (setf (ring-buffer-vector rb) (mkvect number-of-elements))
  21. (setf (ring-buffer-top-ptr rb) 0)
  22. (setf (ring-buffer-pointer rb) 0)
  23. rb
  24. ))
  25. (de ring-buffer-push (rb new-element)
  26. (let ((new-pointer (+ (ring-buffer-pointer rb) 1))
  27. (v (ring-buffer-vector rb))
  28. )
  29. (if (> new-pointer (upbv v))
  30. (setf new-pointer 1))
  31. (if (> new-pointer (ring-buffer-top-ptr rb))
  32. (setf (ring-buffer-top-ptr rb) new-pointer))
  33. (setf (ring-buffer-pointer rb) new-pointer)
  34. (setf (getv (ring-buffer-vector rb) new-pointer) new-element)
  35. new-element
  36. ))
  37. (de ring-buffer-top (rb)
  38. % Returns NIL if the buffer is empty.
  39. (let* ((ptr (ring-buffer-pointer rb))
  40. (v (ring-buffer-vector rb))
  41. )
  42. (cond ((= ptr 0) NIL)
  43. (t (getv v ptr)))))
  44. (de ring-buffer-pop (rb)
  45. % Returns NIL if the buffer is empty.
  46. (let* ((ptr (ring-buffer-pointer rb))
  47. (new-ptr (- ptr 1))
  48. (v (ring-buffer-vector rb))
  49. )
  50. (cond ((= ptr 0) NIL)
  51. (t (if (= new-ptr 0) (setf new-ptr (ring-buffer-top-ptr rb)))
  52. (setf (ring-buffer-pointer rb) new-ptr)
  53. (getv v ptr)))))