Created
December 14, 2023 10:02
-
-
Save havarnov/806ad4cfdf51ae9aebedd94cbc38fcfe to your computer and use it in GitHub Desktop.
This file contains hidden or 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 RingBuffer<'a> = private { | |
buffer: 'a option array | |
size: int | |
index: int | |
} | |
module RingBuffer = | |
open System | |
let create size = { | |
buffer = Array.create size None | |
size = size | |
index = -1 | |
} | |
let pop () ring = | |
if ring.index = -1 then | |
(None, ring) | |
else | |
let value = Array.get ring.buffer ring.index | |
let buffer = Array.copy ring.buffer | |
Array.set buffer ring.index None | |
let size = Math.Max(0, ring.size - 1) | |
let index = | |
if size = 0 then | |
- 1 | |
elif ring.index = 0 then | |
Array.length ring.buffer | |
else | |
ring.index - 1 | |
let ring = { | |
buffer = buffer | |
index = index | |
size = size | |
} | |
(value, ring) | |
let push value ring = | |
let buffer = Array.copy ring.buffer | |
let bufferLength = Array.length ring.buffer | |
let index = | |
if ring.index + 1 >= bufferLength then | |
0 | |
else | |
ring.index + 1 | |
Array.set buffer index (Some value) | |
let size = Math.Min(ring.size + 1, bufferLength) | |
{ | |
buffer = buffer | |
index = index | |
size = size | |
} | |
let ring = | |
RingBuffer.create 2 | |
|> RingBuffer.push 1 | |
|> RingBuffer.push 2 | |
|> RingBuffer.push 3 | |
|> RingBuffer.push 4 | |
|> RingBuffer.push 5 | |
|> RingBuffer.pop () | |
|> snd | |
|> RingBuffer.push 7 | |
printfn "%A" ring |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment