PersistentMap/PersistentOrderedMap/PersistentOrderedMap.cs

43 lines
1.9 KiB
C#

namespace PersistentOrderedMap;
public sealed class PersistentOrderedMap<TK, TV, TStrategy> : BaseOrderedMap<TK, TV, TStrategy> where TStrategy : IKeyStrategy<TK>
{
internal PersistentOrderedMap(Node<TK> root, TStrategy strategy, int count)
: base(root, strategy, count) { }
// ---------------------------------------------------------
// Immutable Write API (Returns new Map)
// ---------------------------------------------------------
public PersistentOrderedMap<TK, TV, TStrategy> Set(TK key, TV value)
{
// OPTIMIZATION: Use OwnerId.None (0).
// This signals EnsureEditable to always copy the root path,
// producing a new tree of nodes that also have OwnerId.None.
var newRoot = BTreeFunctions.Set(Root, key, value, Strategy, OwnerId.None, out bool countChanged);
return new PersistentOrderedMap<TK, TV, TStrategy>(newRoot, Strategy, countChanged ? Count + 1 : Count);
}
public static PersistentOrderedMap<TK, TV, TStrategy> Empty(TStrategy strategy)
{
// Create an empty Leaf Node.
// 'default(OwnerId)' (usually 0) marks this node as Immutable/Persistent.
// This ensures that any subsequent Set/Remove will clone this node
// instead of modifying it in place.
var emptyRoot = new LeafNode<TK, TV>(default(OwnerId), strategy.UsesPrefixes);
return new PersistentOrderedMap<TK, TV, TStrategy>(emptyRoot, strategy, 0);
}
public PersistentOrderedMap<TK, TV, TStrategy> Remove(TK key)
{
var newRoot = BTreeFunctions.Remove<TK,TV, TStrategy>(Root, key, Strategy, OwnerId.None, out bool removed);
if (!removed) return this;
return new PersistentOrderedMap<TK, TV, TStrategy>(newRoot, Strategy, Count - 1);
}
public TransientOrderedMap<TK, TV, TStrategy> ToTransient()
{
return new TransientOrderedMap<TK, TV, TStrategy>(Root, Strategy, Count);
}
}