Permalink
Browse files

Added a circular buffer data structure

  • Loading branch information...
1 parent a03c69b commit 9041af29188e886b634209e80038722d28c54115 @pereckerdal committed Apr 29, 2010
Showing with 44 additions and 0 deletions.
  1. +44 −0 ds/circular.scm
View
44 ds/circular.scm
@@ -0,0 +1,44 @@
+;; A very simple and non-evolved, fixed-size circular buffer based on a vector
+
+(export make-circular-buffer
+ circular-buffer-length
+ circular-buffer-fill!
+ circular-buffer-push!
+ circular-buffer-first
+ circular-buffer-last)
+
+(define-type circular-buffer
+ constructor: make-circular-buffer-internal
+ (vec read-only:)
+ pos)
+
+(define (make-circular-buffer size #!optional (init 0))
+ (make-circular-buffer-internal (make-vector size init)
+ 0))
+
+(define (circular-buffer-length buf)
+ (vector-length
+ (circular-buffer-vec buf)))
+
+(define (circular-buffer-fill! buf val)
+ (vector-fill! (circular-buffer-vec buf)
+ val))
+
+(define (circular-buffer-push! buf val)
+ (let* ((vec (circular-buffer-vec buf))
+ (new-pos (modulo (+ 1 (circular-buffer-pos buf))
+ (vector-length vec))))
+ (circular-buffer-pos-set! buf new-pos)
+ (vector-set! vec new-pos val)))
+
+(define (circular-buffer-ref buf pos)
+ (let ((vec (circular-buffer-vec buf)))
+ (vector-ref vec
+ (modulo pos
+ (vector-length vec)))))
+
+(define (circular-buffer-first buf)
+ (circular-buffer-ref buf 0))
+
+(define (circular-buffer-last buf)
+ (circular-buffer-ref buf -1))

0 comments on commit 9041af2

Please sign in to comment.