Created
August 15, 2019 13:56
-
-
Save yodiz/fc8e1ab96465720116ec8415a20d36c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type CircularBuffer<'b>(bufferSize) = | |
let buffer : 'b option array = Array.init bufferSize (fun _ -> None) | |
let mutable currentIndex = bufferSize - 1 | |
let lockObj = System.Object() | |
member x.Add item = | |
lock (lockObj) | |
(fun () -> | |
let newIndex = | |
if currentIndex = bufferSize - 1 then | |
0 | |
else currentIndex + 1 | |
buffer.[newIndex] <- Some item | |
currentIndex <- newIndex | |
) | |
member x.GetBuffer () = | |
let rec getItem n i items = | |
let i = if i < 0 then bufferSize - 1 else i | |
match n >= bufferSize, buffer.[i] with | |
|false, None | |
|true,_ -> items | |
|_, Some s -> getItem (n+1) (i-1) (s::items) | |
lock (lockObj) | |
(fun () -> | |
getItem 0 currentIndex [] | |
) | |
member x.GetCurrent () = buffer.[currentIndex] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment