tail
Safe HaskellNone
LanguageGHC2021

Control.Concurrent.STM.CircularBuffer

Description

Circular buffer implementation using STM TBMQueue with drop-oldest semantics.

This module provides a circular buffer built on top of Control.Concurrent.STM.TBMQueue that automatically drops the oldest items when the buffer becomes full.

Example usage:

import Control.Concurrent.STM.CircularBuffer qualified as CB

main :: IO ()
main = atomically $ do
  buf <- CB.new 3
  CB.add "first" buf
  CB.add "second" buf
  CB.add "third" buf
  CB.add "fourth" buf  -- Drops "first"
  items <- CB.drain buf
  -- items will be Just ("second" :| ["third", "fourth"])
Synopsis

Documentation

data CircularBuffer a Source #

Circular buffer using TBMQueue - when full, oldest items are dropped

new :: Int -> STM (CircularBuffer a) Source #

Create a new circular buffer with the given capacity.

The buffer will hold at most capacity items. When full, adding new items will cause the oldest items to be dropped.

add :: a -> CircularBuffer a -> STM () Source #

Add an element to the circular buffer.

If the buffer is full, the oldest item will be dropped to make room for the new item.

clone :: HasCallStack => CircularBuffer a -> STM (CircularBuffer a) Source #

Clone the contents of a circular buffer into a new buffer with the same capacity.

This operation drains all items from the source buffer, copies them to a new buffer, and then puts them back into the source buffer. The items maintain their order.

Throws an error if the source buffer is closed.

drain :: CircularBuffer a -> STM (Maybe (NonEmpty a)) Source #

Read all currently available items, blocking for the first item.

This function will block until at least one item is available, then drain all remaining available items without blocking.

Returns Nothing if the queue is closed, or Just items if at least one item is available.

close :: CircularBuffer a -> STM () Source #

Close the buffer to signal end-of-stream.

Once closed, no more items can be added to the buffer, and drain will return Nothing after all remaining items have been drained.