Table of Contents

SegmentedBuffer<T> Class

Definition

Namespace
Bodu.Collections.Generic
Assembly
Bodu.Collections.dll
Package
Bodu.Collections 1.0.0
Source
SegmentedBuffer{T}.cs

Represents an append-only segmented buffer that grows efficiently by allocating fixed-size chunks (segments) of memory.

public sealed class SegmentedBuffer<T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

Type Parameters

T

The type of elements stored in the buffer.

Inheritance
SegmentedBuffer<T>
Implements
Inherited Members
Extension Methods

Examples

// Buffer a streamed sequence whose length is unknown, then random-access it by index.
var buffer = new SegmentedBuffer<int>(segmentSize: 512);
foreach (int value in ReadStream())
    buffer.Add(value);

Console.WriteLine($"Buffered {buffer.Count} values");
int first = buffer[0];
int last  = buffer[buffer.Count - 1];

Remarks

SegmentedBuffer<T> is designed for high-performance buffering scenarios where the number of elements is not known in advance and large contiguous memory allocations (e.g., via List<T>) may lead to excessive memory copying or large object heap allocations.

This class avoids resizing overhead by allocating small fixed-size segments (e.g., 512 items) as needed, ensuring consistent append performance even as the buffer grows. All elements are stored in order and are accessible via zero-based index.

Common usage scenarios include caching enumerator results, buffering streamed data, or logging events without knowing the upper bound in advance.

Constructors

SegmentedBuffer()

Initializes a new instance of the SegmentedBuffer<T> class using the default segment size.

public SegmentedBuffer()

Remarks

The default segment size is 512 items. New segments are allocated only as needed.

SegmentedBuffer(int)

Initializes a new instance of the SegmentedBuffer<T> class using the specified segment size.

public SegmentedBuffer(int segmentSize)

Parameters

segmentSize int

The number of elements per segment.

Remarks

A smaller segment size reduces memory per segment but may incur higher overhead for larger data sets. Larger segment sizes reduce segment management cost but increase memory fragmentation.

Exceptions

ArgumentOutOfRangeException

Thrown if segmentSize is less than 1.

Properties

Count

Gets the number of elements contained in the buffer.

public int Count { get; }

Property Value

int

Remarks

The value returned reflects the total number of elements added via Add(T).

this[int]

Gets or sets the element at the specified zero-based index.

public T this[int index] { get; set; }

Parameters

index int

The zero-based index of the element to retrieve or assign.

Property Value

T

The element at the specified index.

Remarks

This property provides O(1) access to buffered items, backed by segmented storage.

Exceptions

ArgumentOutOfRangeException

Thrown if index is less than 0 or greater than or equal to Count.

Methods

Add(T)

Adds an element to the end of the buffer.

public void Add(T item)

Parameters

item T

The item to add to the buffer.

Remarks

This operation executes in amortized constant time and does not require reallocation or copying of existing elements.

Clear()

Removes all elements from the buffer, releasing the allocated segments.

public void Clear()

Remarks

The structural version is bumped when the buffer was non-empty, so any in-flight enumerator fails fast on its next step. Clearing an already-empty buffer is a no-op and does not invalidate active enumerators.

CopyTo(T[], int)

Copies the buffer's elements to array in insertion order, starting at arrayIndex.

public void CopyTo(T[] array, int arrayIndex)

Parameters

array T[]

The destination array. Must not be null.

arrayIndex int

The zero-based starting index in array.

Exceptions

ArgumentNullException

array is null.

ArgumentOutOfRangeException

arrayIndex is negative.

ArgumentException

The destination is too small to hold the contents starting at arrayIndex.

GetEnumerator()

Returns an enumerator that iterates through the buffer.

public IEnumerator<T> GetEnumerator()

Returns

IEnumerator<T>

An enumerator that can be used to iterate through the buffer contents in insertion order.

Remarks

Enumeration yields elements in the order they were added. The enumerator is fail-fast: if the buffer is modified - by Add(T) or by assignment through the indexer - after enumeration begins, the next iteration step throws InvalidOperationException.

Exceptions

InvalidOperationException

The buffer was modified after enumeration began.

ToArray()

Returns a new array containing the buffer's elements in insertion order.

public T[] ToArray()

Returns

T[]

A freshly allocated array of length Count.

TrimExcess()

Reduces the internal segment-list capacity to the number of allocated segments, releasing the spare segment references without touching the buffered elements or their segment layout.

public void TrimExcess()

Remarks

The append-only segment layout means no data segment is ever over-allocated; this method trims only the spare capacity of the list that tracks the segments. The structural version is bumped so any in-flight enumerator fails fast on its next step.

Explicit Interface Implementations

IEnumerable.GetEnumerator()

Returns an enumerator that iterates through a collection.

IEnumerator IEnumerable.GetEnumerator()

Returns

IEnumerator

An IEnumerator object that can be used to iterate through the collection.

Applies to

ProductVersions
.NET8, 10