Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
38 changes: 19 additions & 19 deletions src/Neo.Cryptography.MPTTrie/Cryptography/MPTTrie/Cache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,37 +32,37 @@ private class Trackable
public TrackState State;
}

private readonly IStoreSnapshot store;
private readonly byte prefix;
private readonly Dictionary<UInt256, Trackable> cache = new Dictionary<UInt256, Trackable>();
private readonly IStoreSnapshot _store;
private readonly byte _prefix;
private readonly Dictionary<UInt256, Trackable> _cache = [];

public Cache(IStoreSnapshot store, byte prefix)
{
this.store = store;
this.prefix = prefix;
_store = store;
_prefix = prefix;
}

private byte[] Key(UInt256 hash)
{
byte[] buffer = new byte[UInt256.Length + 1];
using (MemoryStream ms = new MemoryStream(buffer, true))
using (BinaryWriter writer = new BinaryWriter(ms))
using (var ms = new MemoryStream(buffer, true))
using (var writer = new BinaryWriter(ms))
{
writer.Write(prefix);
writer.Write(_prefix);
hash.Serialize(writer);
}
return buffer;
}

public Node Resolve(UInt256 hash)
{
if (cache.TryGetValue(hash, out Trackable t))
if (_cache.TryGetValue(hash, out var t))
{
return t.Node?.Clone();
}

var n = store.TryGet(Key(hash), out var data) ? data.AsSerializable<Node>() : null;
cache.Add(hash, new Trackable
var n = _store.TryGet(Key(hash), out var data) ? data.AsSerializable<Node>() : null;
_cache.Add(hash, new Trackable
{
Node = n,
State = TrackState.None,
Expand All @@ -76,14 +76,14 @@ public void PutNode(Node np)
if (n is null)
{
np.Reference = 1;
cache[np.Hash] = new Trackable
_cache[np.Hash] = new Trackable
{
Node = np.Clone(),
State = TrackState.Added,
};
return;
}
var entry = cache[np.Hash];
var entry = _cache[np.Hash];
entry.Node.Reference++;
entry.State = TrackState.Changed;
}
Expand All @@ -94,12 +94,12 @@ public void DeleteNode(UInt256 hash)
if (n is null) return;
if (1 < n.Reference)
{
var entry = cache[hash];
var entry = _cache[hash];
entry.Node.Reference--;
entry.State = TrackState.Changed;
return;
}
cache[hash] = new Trackable
_cache[hash] = new Trackable
{
Node = null,
State = TrackState.Deleted,
Expand All @@ -108,20 +108,20 @@ public void DeleteNode(UInt256 hash)

public void Commit()
{
foreach (var item in cache)
foreach (var item in _cache)
{
switch (item.Value.State)
{
case TrackState.Added:
case TrackState.Changed:
store.Put(Key(item.Key), item.Value.Node.ToArray());
_store.Put(Key(item.Key), item.Value.Node.ToArray());
break;
case TrackState.Deleted:
store.Delete(Key(item.Key));
_store.Delete(Key(item.Key));
break;
}
}
cache.Clear();
_cache.Clear();
}
}
}
10 changes: 5 additions & 5 deletions src/Neo.Cryptography.MPTTrie/Cryptography/MPTTrie/Node.Branch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static Node NewBranch()
Reference = 1,
Children = new Node[BranchChildCount],
};
for (int i = 0; i < BranchChildCount; i++)
for (var i = 0; i < BranchChildCount; i++)
{
n.Children[i] = new Node();
}
Expand All @@ -38,8 +38,8 @@ protected int BranchSize
{
get
{
int size = 0;
for (int i = 0; i < BranchChildCount; i++)
var size = 0;
for (var i = 0; i < BranchChildCount; i++)
{
size += Children[i].SizeAsChild;
}
Expand All @@ -49,7 +49,7 @@ protected int BranchSize

private void SerializeBranch(BinaryWriter writer)
{
for (int i = 0; i < BranchChildCount; i++)
for (var i = 0; i < BranchChildCount; i++)
{
Children[i].SerializeAsChild(writer);
}
Expand All @@ -58,7 +58,7 @@ private void SerializeBranch(BinaryWriter writer)
private void DeserializeBranch(ref MemoryReader reader)
{
Children = new Node[BranchChildCount];
for (int i = 0; i < BranchChildCount; i++)
for (var i = 0; i < BranchChildCount; i++)
{
var n = new Node();
n.Deserialize(ref reader);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ partial class Node
{
public static Node NewHash(UInt256 hash)
{
if (hash is null) throw new ArgumentNullException(nameof(NewHash));
ArgumentNullException.ThrowIfNull(hash);
var n = new Node
{
type = NodeType.HashNode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ partial class Node

public static Node NewLeaf(byte[] value)
{
if (value is null) throw new ArgumentNullException(nameof(value));
ArgumentNullException.ThrowIfNull(value);
var n = new Node
{
type = NodeType.LeafNode,
Expand Down
70 changes: 26 additions & 44 deletions src/Neo.Cryptography.MPTTrie/Cryptography/MPTTrie/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,16 @@ public int Size
{
get
{
int size = sizeof(NodeType);
switch (type)
var size = sizeof(NodeType);
return type switch
{
case NodeType.BranchNode:
return size + BranchSize + Reference.GetVarSize();
case NodeType.ExtensionNode:
return size + ExtensionSize + Reference.GetVarSize();
case NodeType.LeafNode:
return size + LeafSize + Reference.GetVarSize();
case NodeType.HashNode:
return size + HashSize;
case NodeType.Empty:
return size;
default:
throw new InvalidOperationException($"{nameof(Node)} Cannt get size, unsupport type");
}
NodeType.BranchNode => size + BranchSize + Reference.GetVarSize(),
NodeType.ExtensionNode => size + ExtensionSize + Reference.GetVarSize(),
NodeType.LeafNode => size + LeafSize + Reference.GetVarSize(),
NodeType.HashNode => size + HashSize,
NodeType.Empty => size,
_ => throw new InvalidOperationException($"{nameof(Node)} Cannt get size, unsupport type"),
};
}
}

Expand All @@ -61,18 +55,12 @@ public int SizeAsChild
{
get
{
switch (type)
return type switch
{
case NodeType.BranchNode:
case NodeType.ExtensionNode:
case NodeType.LeafNode:
return NewHash(Hash).Size;
case NodeType.HashNode:
case NodeType.Empty:
return Size;
default:
throw new InvalidOperationException(nameof(Node));
}
NodeType.BranchNode or NodeType.ExtensionNode or NodeType.LeafNode => NewHash(Hash).Size,
NodeType.HashNode or NodeType.Empty => Size,
_ => throw new InvalidOperationException(nameof(Node)),
};
}
}

Expand Down Expand Up @@ -128,8 +116,8 @@ public void Serialize(BinaryWriter writer)

public byte[] ToArrayWithoutReference()
{
using MemoryStream ms = new MemoryStream();
using BinaryWriter writer = new BinaryWriter(ms, Utility.StrictUTF8, true);
using var ms = new MemoryStream();
using var writer = new BinaryWriter(ms, Utility.StrictUTF8, true);

SerializeWithoutReference(writer);
writer.Flush();
Expand Down Expand Up @@ -165,22 +153,16 @@ public void Deserialize(ref MemoryReader reader)

private Node CloneAsChild()
{
switch (type)
return type switch
{
case NodeType.BranchNode:
case NodeType.ExtensionNode:
case NodeType.LeafNode:
return new Node
{
type = NodeType.HashNode,
hash = Hash,
};
case NodeType.HashNode:
case NodeType.Empty:
return Clone();
default:
throw new InvalidOperationException(nameof(Clone));
}
NodeType.BranchNode or NodeType.ExtensionNode or NodeType.LeafNode => new Node
{
type = NodeType.HashNode,
hash = Hash,
},
NodeType.HashNode or NodeType.Empty => Clone(),
_ => throw new InvalidOperationException(nameof(Clone)),
};
}

public Node Clone()
Expand All @@ -194,7 +176,7 @@ public Node Clone()
Reference = Reference,
Children = new Node[BranchChildCount],
};
for (int i = 0; i < BranchChildCount; i++)
for (var i = 0; i < BranchChildCount; i++)
{
n.Children[i] = Children[i].CloneAsChild();
}
Expand Down
10 changes: 5 additions & 5 deletions src/Neo.Cryptography.MPTTrie/Cryptography/MPTTrie/Trie.Delete.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ private bool TryDelete(ref Node node, ReadOnlySpan<byte> path)
}
if (!result) return false;
if (!_full) _cache.DeleteNode(oldHash);
List<byte> childrenIndexes = new List<byte>(Node.BranchChildCount);
for (int i = 0; i < Node.BranchChildCount; i++)
var childrenIndexes = new List<byte>(Node.BranchChildCount);
for (var i = 0; i < Node.BranchChildCount; i++)
{
if (node.Children[i].IsEmpty) continue;
childrenIndexes.Add((byte)i);
Expand Down Expand Up @@ -112,7 +112,7 @@ private bool TryDelete(ref Node node, ReadOnlySpan<byte> path)
node = lastChild;
return true;
}
node = Node.NewExtension(childrenIndexes.ToArray(), lastChild);
node = Node.NewExtension([.. childrenIndexes], lastChild);
_cache.PutNode(node);
return true;
}
Expand All @@ -122,8 +122,8 @@ private bool TryDelete(ref Node node, ReadOnlySpan<byte> path)
}
case NodeType.HashNode:
{
var newNode = _cache.Resolve(node.Hash);
if (newNode is null) throw new InvalidOperationException("Internal error, can't resolve hash when mpt delete");
var newNode = _cache.Resolve(node.Hash)
?? throw new InvalidOperationException("Internal error, can't resolve hash when mpt delete");
node = newNode;
return TryDelete(ref node, path);
}
Expand Down
28 changes: 14 additions & 14 deletions src/Neo.Cryptography.MPTTrie/Cryptography/MPTTrie/Trie.Find.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
if (path.IsEmpty)
{
start = node;
return ReadOnlySpan<byte>.Empty;
return [];
}
break;
}
case NodeType.Empty:
break;
case NodeType.HashNode:
{
var newNode = _cache.Resolve(node.Hash);
if (newNode is null) throw new InvalidOperationException("Internal error, can't resolve hash when mpt seek");
var newNode = _cache.Resolve(node.Hash)
?? throw new InvalidOperationException("Internal error, can't resolve hash when mpt seek");
node = newNode;
return Seek(ref node, path, out start);
}
Expand All @@ -44,7 +44,7 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
if (path.IsEmpty)
{
start = node;
return ReadOnlySpan<byte>.Empty;
return [];
}
return new([.. path[..1], .. Seek(ref node.Children[path[0]], path[1..], out start)]);
}
Expand All @@ -68,14 +68,14 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
}
}
start = null;
return ReadOnlySpan<byte>.Empty;
return [];
}

public IEnumerable<(ReadOnlyMemory<byte> Key, ReadOnlyMemory<byte> Value)> Find(ReadOnlySpan<byte> prefix, byte[] from = null)
{
var path = ToNibbles(prefix);
int offset = 0;
if (from is null) from = Array.Empty<byte>();
var offset = 0;
from ??= [];
if (0 < from.Length)
{
if (!from.AsSpan().StartsWith(prefix))
Expand All @@ -84,12 +84,12 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
}
if (path.Length > Node.MaxKeyLength || from.Length > Node.MaxKeyLength)
throw new ArgumentException("exceeds limit");
path = Seek(ref _root, path, out Node start).ToArray();
path = Seek(ref _root, path, out var start).ToArray();
if (from.Length > 0)
{
for (int i = 0; i < from.Length && i < path.Length; i++)
for (var i = 0; i < from.Length && i < path.Length; i++)
{
if (path[i] < from[i]) return Enumerable.Empty<(ReadOnlyMemory<byte>, ReadOnlyMemory<byte>)>();
if (path[i] < from[i]) return [];
if (path[i] > from[i])
{
offset = from.Length;
Expand Down Expand Up @@ -120,8 +120,8 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
break;
case NodeType.HashNode:
{
var newNode = _cache.Resolve(node.Hash);
if (newNode is null) throw new InvalidOperationException("Internal error, can't resolve hash when mpt find");
var newNode = _cache.Resolve(node.Hash)
?? throw new InvalidOperationException("Internal error, can't resolve hash when mpt find");
node = newNode;
foreach (var item in Travers(node, path, from, offset))
yield return item;
Expand All @@ -131,7 +131,7 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
{
if (offset < from.Length)
{
for (int i = 0; i < Node.BranchChildCount - 1; i++)
for (var i = 0; i < Node.BranchChildCount - 1; i++)
{
if (from[offset] < i)
{
Expand All @@ -149,7 +149,7 @@ private ReadOnlySpan<byte> Seek(ref Node node, ReadOnlySpan<byte> path, out Node
{
foreach (var item in Travers(node.Children[Node.BranchChildCount - 1], path, from, offset))
yield return item;
for (int i = 0; i < Node.BranchChildCount - 1; i++)
for (var i = 0; i < Node.BranchChildCount - 1; i++)
{
foreach (var item in Travers(node.Children[i], [.. path, .. new byte[] { (byte)i }], from, offset))
yield return item;
Expand Down
Loading