Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Persistent) Hash array mapped trie #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Cornucopia.BitOperations/BitOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,19 @@ public static int Log2(ulong value)

return 32 + Log2(hi);
}

public static int PopCount(uint value)
{
const uint c1 = 0x_55555555u;
const uint c2 = 0x_33333333u;
const uint c3 = 0x_0F0F0F0Fu;
const uint c4 = 0x_01010101u;

value -= (value >> 1) & c1;
value = (value & c2) + ((value >> 2) & c2);
value = (((value + (value >> 4)) & c3) * c4) >> 24;

return (int) value;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Diagnostics.Contracts" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup>

</Project>
81 changes: 81 additions & 0 deletions src/Cornucopia.DataStructures/Persistent/HamtDictionary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Cornucopia.DataStructures.Persistent
{
public struct HamtDictionary<TKey, TValue>
{
private HashArrayMappedTrie<KeyValuePair<TKey, TValue>, KeyComparer> _trie;

public HamtDictionary(IEqualityComparer<TKey> keyComparer)
{
this._trie = new(new(keyComparer));
this.Count = 0;
}

public int Count { get; private set; }

public bool ContainsKey(TKey key)
{
return this._trie.Contains(new(key, default!));
}

public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
var pair = new KeyValuePair<TKey, TValue>(key, default!);
if (this._trie.TryGetFirst(ref pair))
{
value = pair.Value;
return true;
}

value = default;
return false;
}

public TValue this[TKey key]
{
get
{
var pair = new KeyValuePair<TKey, TValue>(key, default!);
if (this._trie.TryGetFirst(ref pair))
{
return pair.Value;
}

throw new KeyNotFoundException();
}
set
{
var pair = new KeyValuePair<TKey, TValue>(key, value);
if (this._trie.Contains(pair))
{
return;
}

this._trie.Add(pair);
this.Count++;
}
}

private readonly struct KeyComparer : IEqualityComparer<KeyValuePair<TKey, TValue>>
{
private readonly IEqualityComparer<TKey> _keyComparer;

public KeyComparer(IEqualityComparer<TKey> keyComparer)
{
this._keyComparer = keyComparer;
}

public bool Equals(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
{
return this._keyComparer.Equals(x.Key, y.Key);
}

public int GetHashCode(KeyValuePair<TKey, TValue> obj)
{
return obj.Key is null ? 0 : this._keyComparer.GetHashCode(obj.Key);
}
}
}
}
219 changes: 219 additions & 0 deletions src/Cornucopia.DataStructures/Persistent/HashArrayMappedTrie.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace Cornucopia.DataStructures.Persistent
{
public readonly struct HashArrayMappedTrie<T, TComparer>
where TComparer : struct, IEqualityComparer<T>
{
private readonly TComparer _comparer;
private readonly HashEntry[] _mainArray;
private readonly uint _mainMap;

public HashArrayMappedTrie(TComparer comparer)
{
this._comparer = comparer;
#if NETCOREAPP3_1
this._mainArray = Array.Empty<HashEntry>();
#else
this._mainArray = new HashEntry[0];
#endif
this._mainMap = 0;
}

private HashArrayMappedTrie(TComparer comparer, HashEntry[] mainArray, uint mainMap)
{
this._comparer = comparer;
this._mainArray = mainArray;
this._mainMap = mainMap;
}

public HashArrayMappedTrie<T, TComparer> Add(T item)
{
var hashCode = this.GetHashCode(item);
var (map, array) = this.Add(this._mainArray, this._mainMap, item, hashCode, 0);
return new(this._comparer, array, map);
}

public bool Contains(T item)
{
var hashCode = this.GetHashCode(item);
var node = this.Find(hashCode);
if (node == null)
{
return false;
}

if (node is T singleValue)
{
return this._comparer.Equals(singleValue, item);
}

var array = (T[]) node;
foreach (var value in array)
{
if (this._comparer.Equals(value, item))
{
return true;
}
}

return false;
}

public bool TryGetFirst(ref T item)
{
var hashCode = this.GetHashCode(item);
var node = this.Find(hashCode);
if (node == null)
{
return false;
}

if (node is T singleValue)
{
if (this._comparer.Equals(singleValue, item))
{
item = singleValue;
return true;
}

return false;
}

var array = (T[]) node;
foreach (var value in array)
{
if (this._comparer.Equals(value, item))
{
item = value;
return true;
}
}

return false;
}

private uint GetHashCode(T item)
{
return item is null ? 0 : (uint) this._comparer.GetHashCode(item);
}

private static int? GetIndex(uint map, uint hashCode)
{
var bit = 1u << (int) hashCode;
if ((map & bit) == 0)
{
return null;
}

return BitOperations.PopCount(map & (bit - 1));
}

private static int GetInsertIndex(ref uint map, uint hashCode)
{
var bit = 1u << (int) hashCode;
map |= bit;
return BitOperations.PopCount(map & (bit - 1));
}

private (uint map, HashEntry[] array) Add(HashEntry[] array, uint map, in T item, uint hashCode, int shift)
{
var idx = GetIndex(map, hashCode >> shift);
if (!idx.HasValue)
{
var insertIndex = GetInsertIndex(ref map, hashCode >> shift);
var newTable = new HashEntry[array.Length + 1];
Array.Copy(array, 0, newTable, 0, insertIndex);
newTable[insertIndex] = new HashEntry(hashCode, item);
Array.Copy(array, insertIndex, newTable, insertIndex + 1, array.Length - insertIndex);
return (map, newTable);
}

ref var entry = ref array[idx.Value];
if (entry.SubHashTableOrLeaf is HashEntry[] subHashTable)
{
var newEntry = this.Add(subHashTable, entry.MapOrHash, item, hashCode, shift + 5);
var copy = array.ToArray();
copy[idx.Value] = new HashEntry(newEntry.map, newEntry.array);
return (map, copy);
}

if (entry.SubHashTableOrLeaf is T[] multiLeaf)
{
if (entry.MapOrHash == hashCode)
{
var newEntries = new T[multiLeaf.Length + 1];
Array.Copy(multiLeaf, newEntries, multiLeaf.Length);
newEntries[multiLeaf.Length] = item;
var copy = array.ToArray();
copy[idx.Value] = new HashEntry(hashCode, newEntries);
return (map, copy);
}
}
else
{
if (entry.MapOrHash == hashCode)
{
var newEntries = new[] { (T) entry.SubHashTableOrLeaf!, item };
var copy = array.ToArray();
copy[idx.Value] = new HashEntry(hashCode, newEntries);
return (map, copy);
}
}

{
subHashTable = new[] { entry };
var subMap = 1u << (int) (entry.MapOrHash >> shift);
var newEntry = this.Add(subHashTable, subMap, item, hashCode, shift + 5);
var copy = array.ToArray();
copy[idx.Value] = new HashEntry(newEntry.map, newEntry.array);
return (map, copy);
}
}

private object? Find(uint hashCode)
{
var array = this._mainArray;
var map = this._mainMap;

while (true)
{
var index = GetIndex(map, hashCode);
if (!index.HasValue)
{
return null;
}

var node = array[index.Value];
if (node.SubHashTableOrLeaf is HashEntry[] subHashTable)
{
array = subHashTable;
map = node.MapOrHash;
continue;
}

if (node.MapOrHash == hashCode)
{
return node.SubHashTableOrLeaf;
}

return null;
}
}

private readonly struct HashEntry
{
public HashEntry(uint mapOrHash, object? subHashTableOrLeaf)
{
this.MapOrHash = mapOrHash;
this.SubHashTableOrLeaf = subHashTableOrLeaf;
}

public uint MapOrHash { get; }
public object? SubHashTableOrLeaf { get; }
}
}
}