Table of Contents

Class SwiftSparseMap<T>

Namespace
SwiftCollections
Assembly
SwiftCollections.dll

Represents a high-performance sparse map that stores values indexed by externally supplied integer keys. Provides O(1) Add, Remove, Contains, and lookup operations while maintaining densely packed storage for cache-friendly iteration.

[JsonConverter(typeof(StateJsonConverterFactory))]
[MemoryPackable(GenerateType.Object)]
public sealed class SwiftSparseMap<T> : IStateBacked<SwiftSparseMapState<T>>, ISwiftCloneable<T>, IEnumerable<KeyValuePair<int, T>>, IEnumerable, IMemoryPackable<SwiftSparseMap<T>>, IMemoryPackFormatterRegister

Type Parameters

T

Value type stored by key.

Inheritance
SwiftSparseMap<T>
Implements
IStateBacked<SwiftSparseMapState<T>>
IMemoryPackable<SwiftSparseMap<T>>
IMemoryPackFormatterRegister
Inherited Members
Extension Methods

Remarks

Unlike SwiftBucket<T>, which internally assigns and manages item indices, SwiftSparseMap<T> is externally keyed. The caller supplies the integer key (for example, an entity ID or handle) used to index the value.

Internally, the container maintains:

  • A sparse lookup table mapping keys to dense indices.
  • A dense array of keys.
  • A dense array of values.

Removal uses a swap-back strategy to keep dense storage contiguous. As a result, iteration order is not guaranteed to remain stable.

Keys are used as direct indices into the sparse lookup table, so memory usage scales with the highest stored key rather than the number of stored values. This container is intended for compact, non-negative IDs such as entity handles or slot indices. It is not a good fit for arbitrary hashes or widely spaced keys; for those workloads prefer SwiftDictionary<TKey, TValue>.

Constructors

SwiftSparseMap()

Initializes a new instance of the SwiftSparseMap class with default sparse and dense capacities.

public SwiftSparseMap()

SwiftSparseMap(SwiftSparseMapState<T>)

Initializes a new instance of the SwiftSparseMap class using the specified state.

[MemoryPackConstructor]
public SwiftSparseMap(SwiftSparseMapState<T> state)

Parameters

state SwiftSparseMapState<T>

The state object that provides the initial configuration and data for the map. Cannot be null.

SwiftSparseMap(int, int)

Initializes a new sparse map with the specified sparse and dense capacities.

public SwiftSparseMap(int sparseCapacity, int denseCapacity)

Parameters

sparseCapacity int

Initial sparse lookup capacity. This should track the highest expected key plus one, not the number of stored values.

denseCapacity int

Initial dense storage capacity for values.

Fields

DefaultDenseCapacity

Represents the default initial capacity for dense collections.

public const int DefaultDenseCapacity = 8

Field Value

int

DefaultSparseCapacity

Represents the default initial capacity for sparse collections.

public const int DefaultSparseCapacity = 8

Field Value

int

Properties

Count

Gets the number of elements contained in the collection.

[JsonIgnore]
[MemoryPackIgnore]
public int Count { get; }

Property Value

int

DenseCapacity

Capacity of the dense arrays (Keys/Values storage).

[JsonIgnore]
[MemoryPackIgnore]
public int DenseCapacity { get; }

Property Value

int

DenseKeys

Returns the dense keys array (valid range: [0..Count)).

[JsonIgnore]
[MemoryPackIgnore]
public int[] DenseKeys { get; }

Property Value

int[]

Remarks

Prefer collection APIs. Direct key mutation must preserve the dense/sparse lookup invariants; invalid edits may fail fast.

DenseValues

Returns the dense values array (valid range: [0..Count)).

[JsonIgnore]
[MemoryPackIgnore]
public T[] DenseValues { get; }

Property Value

T[]

IsSynchronized

Gets a value indicating whether access to the collection is synchronized (thread safe).

[JsonIgnore]
[MemoryPackIgnore]
public bool IsSynchronized { get; }

Property Value

bool

this[int]

Gets/sets the value for a key. Setting:

  • overwrites if present
  • inserts if not present
[JsonIgnore]
[MemoryPackIgnore]
public T this[int key] { get; set; }

Parameters

key int

Property Value

T

Keys

Gets a span containing the keys currently stored in the collection.

[JsonIgnore]
[MemoryPackIgnore]
public Span<int> Keys { get; }

Property Value

Span<int>

Remarks

The returned span provides a view of the underlying key data and reflects the current state of the collection. Prefer collection APIs. Direct key mutation must preserve the dense/sparse lookup invariants; invalid edits may fail fast. The span is only valid as long as the underlying collection is not modified.

SparseCapacity

Capacity of the sparse array (max key+1 that can be mapped without resizing). Memory usage grows with this capacity.

[JsonIgnore]
[MemoryPackIgnore]
public int SparseCapacity { get; }

Property Value

int

State

Gets or sets the current state of the sparse map, including the used dense keys and values.

[JsonInclude]
[MemoryPackInclude]
public SwiftSparseMapState<T> State { get; }

Property Value

SwiftSparseMapState<T>

Remarks

The state includes only the active elements in the map. Setting this property replaces the current contents with the provided state. The setter is intended for internal use, such as serialization or deserialization scenarios.

SyncRoot

Gets an object that can be used to synchronize access to the collection.

[JsonIgnore]
[MemoryPackIgnore]
public object SyncRoot { get; }

Property Value

object

Remarks

Use this object to lock the collection during multithreaded operations to ensure thread safety. The returned object is unique to this collection instance.

Values

Gets a span containing the current values in the collection.

[JsonIgnore]
[MemoryPackIgnore]
public Span<T> Values { get; }

Property Value

Span<T>

Remarks

The returned span reflects the live contents of the collection up to the current count. Modifying the span will update the underlying collection data. The span length is equal to the number of elements currently stored.

Methods

Add(int, T)

Adds or overwrites (same behavior as indexer set).

public void Add(int key, T value)

Parameters

key int
value T

Clear()

Removes all keys and values from the collection.

public void Clear()

Remarks

After calling this method, the collection will be empty and its Count property will be zero. This method does not reduce the capacity of the underlying storage.

CloneTo(ICollection<T>)

Clones the entire ISwiftCloneable<T> into a new target ICollection<T>, ensuring that the target list is an exact copy. Clears the target list first to match the structure and state of the source list exactly.

public void CloneTo(ICollection<T> output)

Parameters

output ICollection<T>

ContainsKey(int)

Determines whether the collection contains the specified key.

public bool ContainsKey(int key)

Parameters

key int

The key to locate in the collection.

Returns

bool

true if the collection contains an element with the specified key; otherwise, false.

CopyKeysTo(SwiftList<int>)

Replaces the destination list contents with this map's keys in dense iteration order.

public void CopyKeysTo(SwiftList<int> destination)

Parameters

destination SwiftList<int>

The caller-owned list that receives the keys.

Remarks

The destination list is reused and only grows when its current capacity is smaller than Count. Use CopySortedKeysTo(SwiftList<int>) when stable ascending key order is required.

CopySortedKeysTo(SwiftList<int>)

Replaces the destination list contents with this map's keys sorted in ascending order.

public void CopySortedKeysTo(SwiftList<int> destination)

Parameters

destination SwiftList<int>

The caller-owned list that receives the sorted keys.

Remarks

This method is intended for reusable hot-path scratch buffers that need deterministic key order without constructing a persistent sorted collection.

EnsureDenseCapacity(int)

Ensures that the internal dense storage has at least the specified capacity, expanding it if necessary.

public void EnsureDenseCapacity(int capacity)

Parameters

capacity int

The minimum number of elements that the dense storage must be able to hold. Must be non-negative.

Remarks

If the current capacity is less than the specified value, the internal storage is resized to accommodate at least that many elements. Existing elements are preserved. The capacity is increased to the next power of two greater than or equal to the requested capacity for performance reasons.

EnsureSparseCapacity(int)

Ensures that the internal sparse array has a capacity at least as large as the specified value.

public void EnsureSparseCapacity(int capacity)

Parameters

capacity int

The minimum required capacity for the internal sparse array. Must be non-negative.

Remarks

If the current capacity is less than the specified value, the internal storage is resized to accommodate at least that many elements. Existing elements are preserved. The capacity is increased to the next power of two greater than or equal to the requested capacity for performance reasons.

GetDense(out int[], out T[], out int)

Retrieves the dense representation of the collection as parallel arrays of keys and values, along with the number of elements contained.

public void GetDense(out int[] keys, out T[] values, out int count)

Parameters

keys int[]

When this method returns, contains an array of keys representing the dense mapping. The array length is at least as large as the number of elements returned in count.

values T[]

When this method returns, contains an array of values corresponding to the keys in keys. The array length is at least as large as the number of elements returned in count.

count int

When this method returns, contains the number of valid key-value pairs in the dense arrays.

Remarks

The arrays returned may be larger than the actual number of elements. Only the first count entries in each array are valid and should be used.

GetEnumerator()

public SwiftSparseMap<T>.SwiftSparseMapEnumerator GetEnumerator()

Returns

SwiftSparseMap<T>.SwiftSparseMapEnumerator

Remove(int)

Removes the element with the specified key from the collection, if it exists.

public bool Remove(int key)

Parameters

key int

The key of the element to remove. Must be a non-negative integer within the valid range of keys.

Returns

bool

true if the element is successfully found and removed; otherwise, false.

TrimExcess()

Reduces the memory usage of the collection by resizing internal storage to fit the current number of elements as closely as possible.

public void TrimExcess()

Remarks

Call this method to minimize the collection's memory footprint after removing a significant number of elements. This operation may improve memory efficiency but can be an expensive operation if the collection is large. The method does not affect the logical contents of the collection.

TryAdd(int, T)

Adds a key/value only if the key is not present. Returns false if already present.

public bool TryAdd(int key, T value)

Parameters

key int
value T

Returns

bool

TryGetValue(int, out T)

Attempts to retrieve the value associated with the specified key.

public bool TryGetValue(int key, out T value)

Parameters

key int

The key whose associated value is to be retrieved.

value T

When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type parameter T. This parameter is passed uninitialized.

Returns

bool

true if the key was found and its value was retrieved; otherwise, false.