using System.Collections; namespace PersistentOrderedMap; public sealed class PersistentOrderedMap : BaseOrderedMap, IEnumerable, IEnumerable> where TStrategy : IKeyStrategy { internal PersistentOrderedMap(Node root, TStrategy strategy, int count) : base(root, strategy, count) { } // --------------------------------------------------------- // Immutable Write API (Returns new Map) // --------------------------------------------------------- public PersistentOrderedMap Set(K key, V 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(newRoot, _strategy, countChanged ? Count + 1 : Count); } public static PersistentOrderedMap 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(default(OwnerId), strategy.UsesPrefixes); return new PersistentOrderedMap(emptyRoot, strategy, 0); } public PersistentOrderedMap Remove(K key) { var newRoot = BTreeFunctions.Remove(_root, key, _strategy, OwnerId.None, out bool removed); if (!removed) return this; return new PersistentOrderedMap(newRoot, _strategy, Count - 1); } public TransientOrderedMap ToTransient() { return new TransientOrderedMap(_root, _strategy, Count); } }