diff --git a/src/Neo/BigDecimal.cs b/src/Neo/BigDecimal.cs index 6dfc3c8a92..074babe4c9 100644 --- a/src/Neo/BigDecimal.cs +++ b/src/Neo/BigDecimal.cs @@ -9,6 +9,8 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +#nullable enable + using System; using System.Numerics; @@ -17,25 +19,25 @@ namespace Neo /// /// Represents a fixed-point number of arbitrary precision. /// - public struct BigDecimal : IComparable, IEquatable + public readonly struct BigDecimal : IComparable, IEquatable { - private readonly BigInteger value; - private readonly byte decimals; + private readonly BigInteger _value; + private readonly byte _decimals; /// /// The value of the number. /// - public readonly BigInteger Value => value; + public readonly BigInteger Value => _value; /// /// The number of decimal places for this number. /// - public readonly byte Decimals => decimals; + public readonly byte Decimals => _decimals; /// /// The sign of the number. /// - public readonly int Sign => value.Sign; + public readonly int Sign => _value.Sign; /// /// Initializes a new instance of the struct. @@ -44,8 +46,8 @@ public struct BigDecimal : IComparable, IEquatable /// The number of decimal places for this number. public BigDecimal(BigInteger value, byte decimals) { - this.value = value; - this.decimals = decimals; + _value = value; + _decimals = decimals; } /// @@ -59,9 +61,9 @@ public unsafe BigDecimal(decimal value) fixed (int* p = span) { ReadOnlySpan buffer = new(p, 16); - this.value = new BigInteger(buffer[..12], isUnsigned: true); - if (buffer[15] != 0) this.value = -this.value; - decimals = buffer[14]; + _value = new BigInteger(buffer[..12], isUnsigned: true); + if (buffer[15] != 0) _value = -_value; + _decimals = buffer[14]; } } @@ -77,15 +79,15 @@ public unsafe BigDecimal(decimal value, byte decimals) fixed (int* p = span) { ReadOnlySpan buffer = new(p, 16); - this.value = new BigInteger(buffer[..12], isUnsigned: true); + _value = new BigInteger(buffer[..12], isUnsigned: true); if (buffer[14] > decimals) throw new ArgumentException(null, nameof(value)); else if (buffer[14] < decimals) - this.value *= BigInteger.Pow(10, decimals - buffer[14]); + _value *= BigInteger.Pow(10, decimals - buffer[14]); if (buffer[15] != 0) - this.value = -this.value; + _value = -_value; } - this.decimals = decimals; + _decimals = decimals; } /// @@ -95,16 +97,16 @@ public unsafe BigDecimal(decimal value, byte decimals) /// The that has the new number of decimal places. public readonly BigDecimal ChangeDecimals(byte decimals) { - if (this.decimals == decimals) return this; + if (_decimals == decimals) return this; BigInteger value; - if (this.decimals < decimals) + if (_decimals < decimals) { - value = this.value * BigInteger.Pow(10, decimals - this.decimals); + value = _value * BigInteger.Pow(10, decimals - _decimals); } else { - BigInteger divisor = BigInteger.Pow(10, this.decimals - decimals); - value = BigInteger.DivRem(this.value, divisor, out BigInteger remainder); + var divisor = BigInteger.Pow(10, _decimals - decimals); + value = BigInteger.DivRem(_value, divisor, out var remainder); if (remainder > BigInteger.Zero) throw new ArgumentOutOfRangeException(nameof(decimals)); } @@ -120,7 +122,7 @@ public readonly BigDecimal ChangeDecimals(byte decimals) /// is not in the correct format. public static BigDecimal Parse(string s, byte decimals) { - if (!TryParse(s, decimals, out BigDecimal result)) + if (!TryParse(s, decimals, out var result)) throw new FormatException(); return result; } @@ -131,10 +133,10 @@ public static BigDecimal Parse(string s, byte decimals) /// The representing the number. public override readonly string ToString() { - BigInteger divisor = BigInteger.Pow(10, decimals); - BigInteger result = BigInteger.DivRem(value, divisor, out BigInteger remainder); + var divisor = BigInteger.Pow(10, _decimals); + var result = BigInteger.DivRem(_value, divisor, out var remainder); if (remainder == 0) return result.ToString(); - return $"{result}.{remainder.ToString("d" + decimals)}".TrimEnd('0'); + return $"{result}.{remainder.ToString("d" + _decimals)}".TrimEnd('0'); } /// @@ -146,17 +148,17 @@ public override readonly string ToString() /// if a number is successfully parsed; otherwise, . public static bool TryParse(string s, byte decimals, out BigDecimal result) { - int e = 0; - int index = s.IndexOfAny(new[] { 'e', 'E' }); + var e = 0; + var index = s.IndexOfAny(['e', 'E']); if (index >= 0) { - if (!sbyte.TryParse(s[(index + 1)..], out sbyte e_temp)) + if (!sbyte.TryParse(s[(index + 1)..], out var e_temp)) { result = default; return false; } e = e_temp; - s = s.Substring(0, index); + s = s[..index]; } index = s.IndexOf('.'); if (index >= 0) @@ -165,7 +167,7 @@ public static bool TryParse(string s, byte decimals, out BigDecimal result) e -= s.Length - index - 1; s = s.Remove(index, 1); } - int ds = e + decimals; + var ds = e + decimals; if (ds < 0) { result = default; @@ -173,7 +175,7 @@ public static bool TryParse(string s, byte decimals, out BigDecimal result) } if (ds > 0) s += new string('0', ds); - if (!BigInteger.TryParse(s, out BigInteger value)) + if (!BigInteger.TryParse(s, out var value)) { result = default; return false; @@ -184,15 +186,15 @@ public static bool TryParse(string s, byte decimals, out BigDecimal result) public readonly int CompareTo(BigDecimal other) { - BigInteger left = value, right = other.value; - if (decimals < other.decimals) - left *= BigInteger.Pow(10, other.decimals - decimals); - else if (decimals > other.decimals) - right *= BigInteger.Pow(10, decimals - other.decimals); + BigInteger left = _value, right = other._value; + if (_decimals < other._decimals) + left *= BigInteger.Pow(10, other._decimals - _decimals); + else if (_decimals > other._decimals) + right *= BigInteger.Pow(10, _decimals - other._decimals); return left.CompareTo(right); } - public override readonly bool Equals(object obj) + public override readonly bool Equals(object? obj) { if (obj is not BigDecimal @decimal) return false; return Equals(@decimal); @@ -205,8 +207,8 @@ public readonly bool Equals(BigDecimal other) public override readonly int GetHashCode() { - BigInteger divisor = BigInteger.Pow(10, decimals); - BigInteger result = BigInteger.DivRem(value, divisor, out BigInteger remainder); + var divisor = BigInteger.Pow(10, _decimals); + var result = BigInteger.DivRem(_value, divisor, out var remainder); return HashCode.Combine(result, remainder); } diff --git a/src/Neo/Persistence/ClonedCache.cs b/src/Neo/Persistence/ClonedCache.cs index 2bc09b1172..768d850165 100644 --- a/src/Neo/Persistence/ClonedCache.cs +++ b/src/Neo/Persistence/ClonedCache.cs @@ -9,6 +9,8 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +#nullable enable + using Neo.SmartContract; using System.Collections.Generic; @@ -16,48 +18,51 @@ namespace Neo.Persistence { class ClonedCache : DataCache { - private readonly DataCache innerCache; + private readonly DataCache _innerCache; public ClonedCache(DataCache innerCache) { - this.innerCache = innerCache; + _innerCache = innerCache; } protected override void AddInternal(StorageKey key, StorageItem value) { - innerCache.Add(key, value.Clone()); + _innerCache.Add(key, value.Clone()); } protected override void DeleteInternal(StorageKey key) { - innerCache.Delete(key); + _innerCache.Delete(key); } protected override bool ContainsInternal(StorageKey key) { - return innerCache.Contains(key); + return _innerCache.Contains(key); } /// protected override StorageItem GetInternal(StorageKey key) { - return innerCache[key].Clone(); + return _innerCache[key].Clone(); } protected override IEnumerable<(StorageKey, StorageItem)> SeekInternal(byte[] keyOrPreifx, SeekDirection direction) { - foreach (var (key, value) in innerCache.Seek(keyOrPreifx, direction)) + foreach (var (key, value) in _innerCache.Seek(keyOrPreifx, direction)) yield return (key, value.Clone()); } - protected override StorageItem TryGetInternal(StorageKey key) + protected override StorageItem? TryGetInternal(StorageKey key) { - return innerCache.TryGet(key)?.Clone(); + return _innerCache.TryGet(key)?.Clone(); } protected override void UpdateInternal(StorageKey key, StorageItem value) { - innerCache.GetAndChange(key).FromReplica(value); + var entry = _innerCache.GetAndChange(key) + ?? throw new KeyNotFoundException(); + + entry.FromReplica(value); } } } diff --git a/src/Neo/Persistence/DataCache.cs b/src/Neo/Persistence/DataCache.cs index 950c43b837..016bed2ee2 100644 --- a/src/Neo/Persistence/DataCache.cs +++ b/src/Neo/Persistence/DataCache.cs @@ -9,10 +9,13 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +#nullable enable + using Neo.Extensions; using Neo.SmartContract; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; @@ -26,26 +29,26 @@ public abstract class DataCache : IReadOnlyStoreView /// /// Represents an entry in the cache. /// - public class Trackable + public class Trackable(StorageKey key, StorageItem item, TrackState state) { /// /// The key of the entry. /// - public StorageKey Key; + public StorageKey Key { get; } = key; /// /// The data of the entry. /// - public StorageItem Item; + public StorageItem Item { get; set; } = item; /// /// The state of the entry. /// - public TrackState State; + public TrackState State { get; set; } = state; } - private readonly Dictionary dictionary = new(); - private readonly HashSet changeSet = new(); + private readonly Dictionary _dictionary = new(); + private readonly HashSet _changeSet = new(); /// /// Reads a specified entry from the cache. If the entry is not in the cache, it will be automatically loaded from the underlying storage. @@ -57,22 +60,17 @@ public StorageItem this[StorageKey key] { get { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) { if (trackable.State == TrackState.Deleted || trackable.State == TrackState.NotFound) throw new KeyNotFoundException(); } else { - trackable = new Trackable - { - Key = key, - Item = GetInternal(key), - State = TrackState.None - }; - dictionary.Add(key, trackable); + trackable = new Trackable(key, GetInternal(key), TrackState.None); + _dictionary.Add(key, trackable); } return trackable.Item; } @@ -88,9 +86,9 @@ public StorageItem this[StorageKey key] /// Note: This method does not read the internal storage to check whether the record already exists. public void Add(StorageKey key, StorageItem value) { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) { trackable.Item = value; trackable.State = trackable.State switch @@ -102,14 +100,9 @@ public void Add(StorageKey key, StorageItem value) } else { - dictionary[key] = new Trackable - { - Key = key, - Item = value, - State = TrackState.Added - }; + _dictionary[key] = new Trackable(key, value, TrackState.Added); } - changeSet.Add(key); + _changeSet.Add(key); } } @@ -125,11 +118,11 @@ public void Add(StorageKey key, StorageItem value) /// public virtual void Commit() { - lock (dictionary) + lock (_dictionary) { - foreach (var key in changeSet) + foreach (var key in _changeSet) { - var trackable = dictionary[key]; + var trackable = _dictionary[key]; switch (trackable.State) { case TrackState.Added: @@ -142,11 +135,11 @@ public virtual void Commit() break; case TrackState.Deleted: DeleteInternal(key); - dictionary.Remove(key); + _dictionary.Remove(key); break; } } - changeSet.Clear(); + _changeSet.Clear(); } } @@ -175,32 +168,27 @@ public DataCache CloneCache() /// The key of the entry. public void Delete(StorageKey key) { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) { if (trackable.State == TrackState.Added) { trackable.State = TrackState.NotFound; - changeSet.Remove(key); + _changeSet.Remove(key); } else if (trackable.State != TrackState.NotFound) { trackable.State = TrackState.Deleted; - changeSet.Add(key); + _changeSet.Add(key); } } else { - StorageItem item = TryGetInternal(key); + var item = TryGetInternal(key); if (item == null) return; - dictionary.Add(key, new Trackable - { - Key = key, - Item = item, - State = TrackState.Deleted - }); - changeSet.Add(key); + _dictionary.Add(key, new Trackable(key, item, TrackState.Deleted)); + _changeSet.Add(key); } } } @@ -217,17 +205,23 @@ public void Delete(StorageKey key) /// The prefix of the key. /// The search direction. /// The entries found with the desired prefix. - public IEnumerable<(StorageKey Key, StorageItem Value)> Find(byte[] key_prefix = null, SeekDirection direction = SeekDirection.Forward) + public IEnumerable<(StorageKey Key, StorageItem Value)> Find(byte[]? key_prefix = null, SeekDirection direction = SeekDirection.Forward) { var seek_prefix = key_prefix; if (direction == SeekDirection.Backward) { - if (key_prefix == null || key_prefix.Length == 0) - { // Backwards seek for zero prefix is not supported for now. - throw new ArgumentException(); + if (key_prefix == null) + { + // Backwards seek for null prefix is not supported for now. + throw new ArgumentNullException(nameof(key_prefix)); + } + if (key_prefix.Length == 0) + { + // Backwards seek for zero prefix is not supported for now. + throw new ArgumentOutOfRangeException(nameof(key_prefix)); } seek_prefix = null; - for (int i = key_prefix.Length - 1; i >= 0; i--) + for (var i = key_prefix.Length - 1; i >= 0; i--) { if (key_prefix[i] < 0xff) { @@ -239,18 +233,18 @@ public void Delete(StorageKey key) } if (seek_prefix == null) { - throw new ArgumentException(); + throw new ArgumentException($"{nameof(key_prefix)} with all bytes being 0xff is not supported now"); } } return FindInternal(key_prefix, seek_prefix, direction); } - private IEnumerable<(StorageKey Key, StorageItem Value)> FindInternal(byte[] key_prefix, byte[] seek_prefix, SeekDirection direction) + private IEnumerable<(StorageKey Key, StorageItem Value)> FindInternal(byte[]? key_prefix, byte[]? seek_prefix, SeekDirection direction) { foreach (var (key, value) in Seek(seek_prefix, direction)) - if (key.ToArray().AsSpan().StartsWith(key_prefix)) + if (key_prefix == null || key.ToArray().AsSpan().StartsWith(key_prefix)) yield return (key, value); - else if (direction == SeekDirection.Forward || !key.ToArray().SequenceEqual(seek_prefix)) + else if (direction == SeekDirection.Forward || (seek_prefix == null || !key.ToArray().SequenceEqual(seek_prefix))) yield break; } @@ -279,10 +273,10 @@ public void Delete(StorageKey key) /// The change set. public IEnumerable GetChangeSet() { - lock (dictionary) + lock (_dictionary) { - foreach (StorageKey key in changeSet) - yield return dictionary[key]; + foreach (StorageKey key in _changeSet) + yield return _dictionary[key]; } } @@ -293,9 +287,9 @@ public IEnumerable GetChangeSet() /// if the cache contains an entry with the specified key; otherwise, . public bool Contains(StorageKey key) { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) return trackable.State != TrackState.Deleted && trackable.State != TrackState.NotFound; return ContainsInternal(key); } @@ -322,11 +316,11 @@ public bool Contains(StorageKey key) /// The key of the entry. /// A delegate used to create the entry if it doesn't exist. If the entry already exists, the factory will not be used. /// The cached data. Or if it doesn't exist and the is not provided. - public StorageItem GetAndChange(StorageKey key, Func factory = null) + public StorageItem? GetAndChange(StorageKey key, Func? factory = null) { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) { if (trackable.State == TrackState.Deleted || trackable.State == TrackState.NotFound) { @@ -339,34 +333,29 @@ public StorageItem GetAndChange(StorageKey key, Func factory = null else { trackable.State = TrackState.Added; - changeSet.Add(key); + _changeSet.Add(key); } } else if (trackable.State == TrackState.None) { trackable.State = TrackState.Changed; - changeSet.Add(key); + _changeSet.Add(key); } } else { - trackable = new Trackable - { - Key = key, - Item = TryGetInternal(key) - }; - if (trackable.Item == null) + var item = TryGetInternal(key); + if (item == null) { if (factory == null) return null; - trackable.Item = factory(); - trackable.State = TrackState.Added; + trackable = new Trackable(key, factory(), TrackState.Added); } else { - trackable.State = TrackState.Changed; + trackable = new Trackable(key, item, TrackState.Changed); } - dictionary.Add(key, trackable); - changeSet.Add(key); + _dictionary.Add(key, trackable); + _changeSet.Add(key); } return trackable.Item; } @@ -380,9 +369,9 @@ public StorageItem GetAndChange(StorageKey key, Func factory = null /// The cached data. public StorageItem GetOrAdd(StorageKey key, Func factory) { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) { if (trackable.State == TrackState.Deleted || trackable.State == TrackState.NotFound) { @@ -394,28 +383,23 @@ public StorageItem GetOrAdd(StorageKey key, Func factory) else { trackable.State = TrackState.Added; - changeSet.Add(key); + _changeSet.Add(key); } } } else { - trackable = new Trackable + var item = TryGetInternal(key); + if (item == null) { - Key = key, - Item = TryGetInternal(key) - }; - if (trackable.Item == null) - { - trackable.Item = factory(); - trackable.State = TrackState.Added; - changeSet.Add(key); + trackable = new Trackable(key, factory(), TrackState.Added); + _changeSet.Add(key); } else { - trackable.State = TrackState.None; + trackable = new Trackable(key, item, TrackState.None); } - dictionary.Add(key, trackable); + _dictionary.Add(key, trackable); } return trackable.Item; } @@ -427,14 +411,14 @@ public StorageItem GetOrAdd(StorageKey key, Func factory) /// The key to be sought. /// The direction of seek. /// An enumerator containing all the entries after seeking. - public IEnumerable<(StorageKey Key, StorageItem Value)> Seek(byte[] keyOrPrefix = null, SeekDirection direction = SeekDirection.Forward) + public IEnumerable<(StorageKey Key, StorageItem Value)> Seek(byte[]? keyOrPrefix = null, SeekDirection direction = SeekDirection.Forward) { IEnumerable<(byte[], StorageKey, StorageItem)> cached; HashSet cachedKeySet; ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse; - lock (dictionary) + lock (_dictionary) { - cached = dictionary + cached = _dictionary .Where(p => p.Value.State != TrackState.Deleted && p.Value.State != TrackState.NotFound && (keyOrPrefix == null || comparer.Compare(p.Key.ToArray(), keyOrPrefix) >= 0)) .Select(p => ( @@ -444,7 +428,7 @@ public StorageItem GetOrAdd(StorageKey key, Func factory) )) .OrderBy(p => p.KeyBytes, comparer) .ToArray(); - cachedKeySet = new HashSet(dictionary.Keys); + cachedKeySet = new HashSet(_dictionary.Keys); } var uncached = SeekInternal(keyOrPrefix ?? Array.Empty(), direction) .Where(p => !cachedKeySet.Contains(p.Key)) @@ -491,31 +475,26 @@ public StorageItem GetOrAdd(StorageKey key, Func factory) /// /// The key of the entry. /// The cached data. Or if it is neither in the cache nor in the underlying storage. - public StorageItem TryGet(StorageKey key) + public StorageItem? TryGet(StorageKey key) { - lock (dictionary) + lock (_dictionary) { - if (dictionary.TryGetValue(key, out Trackable trackable)) + if (_dictionary.TryGetValue(key, out var trackable)) { if (trackable.State == TrackState.Deleted || trackable.State == TrackState.NotFound) return null; return trackable.Item; } - StorageItem value = TryGetInternal(key); + var value = TryGetInternal(key); if (value == null) return null; - dictionary.Add(key, new Trackable - { - Key = key, - Item = value, - State = TrackState.None - }); + _dictionary.Add(key, new Trackable(key, value, TrackState.None)); return value; } } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryGet(StorageKey key, out StorageItem item) + public bool TryGet(StorageKey key, [NotNullWhen(true)] out StorageItem? item) { item = TryGet(key); return item != null; @@ -526,7 +505,7 @@ public bool TryGet(StorageKey key, out StorageItem item) /// /// The key of the entry. /// The data of the entry. Or if it doesn't exist. - protected abstract StorageItem TryGetInternal(StorageKey key); + protected abstract StorageItem? TryGetInternal(StorageKey key); /// /// Updates an entry in the underlying storage. diff --git a/src/Neo/Persistence/MemorySnapshot.cs b/src/Neo/Persistence/MemorySnapshot.cs index 567573bb87..930c983a4d 100644 --- a/src/Neo/Persistence/MemorySnapshot.cs +++ b/src/Neo/Persistence/MemorySnapshot.cs @@ -9,40 +9,42 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +#nullable enable + using Neo.Extensions; -using Neo.IO; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Neo.Persistence { internal class MemorySnapshot : ISnapshot { - private readonly ConcurrentDictionary innerData; - private readonly ImmutableDictionary immutableData; - private readonly ConcurrentDictionary writeBatch; + private readonly ConcurrentDictionary _innerData; + private readonly ImmutableDictionary _immutableData; + private readonly ConcurrentDictionary _writeBatch; public MemorySnapshot(ConcurrentDictionary innerData) { - this.innerData = innerData; - immutableData = innerData.ToImmutableDictionary(ByteArrayEqualityComparer.Default); - writeBatch = new ConcurrentDictionary(ByteArrayEqualityComparer.Default); + _innerData = innerData; + _immutableData = innerData.ToImmutableDictionary(ByteArrayEqualityComparer.Default); + _writeBatch = new ConcurrentDictionary(ByteArrayEqualityComparer.Default); } public void Commit() { - foreach (var pair in writeBatch) + foreach (var pair in _writeBatch) if (pair.Value is null) - innerData.TryRemove(pair.Key, out _); + _innerData.TryRemove(pair.Key, out _); else - innerData[pair.Key] = pair.Value; + _innerData[pair.Key] = pair.Value; } public void Delete(byte[] key) { - writeBatch[key] = null; + _writeBatch[key] = null; } public void Dispose() @@ -51,34 +53,34 @@ public void Dispose() public void Put(byte[] key, byte[] value) { - writeBatch[key[..]] = value[..]; + _writeBatch[key[..]] = value[..]; } /// - public IEnumerable<(byte[] Key, byte[] Value)> Seek(byte[] keyOrPrefix, SeekDirection direction = SeekDirection.Forward) + public IEnumerable<(byte[] Key, byte[] Value)> Seek(byte[]? keyOrPrefix, SeekDirection direction = SeekDirection.Forward) { - ByteArrayComparer comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse; - IEnumerable> records = immutableData; + var comparer = direction == SeekDirection.Forward ? ByteArrayComparer.Default : ByteArrayComparer.Reverse; + IEnumerable> records = _immutableData; if (keyOrPrefix?.Length > 0) records = records.Where(p => comparer.Compare(p.Key, keyOrPrefix) >= 0); records = records.OrderBy(p => p.Key, comparer); return records.Select(p => (p.Key[..], p.Value[..])); } - public byte[] TryGet(byte[] key) + public byte[]? TryGet(byte[] key) { - immutableData.TryGetValue(key, out byte[] value); + _immutableData.TryGetValue(key, out var value); return value?[..]; } - public bool TryGet(byte[] key, out byte[] value) + public bool TryGet(byte[] key, [NotNullWhen(true)] out byte[]? value) { - return immutableData.TryGetValue(key, out value); + return _immutableData.TryGetValue(key, out value); } public bool Contains(byte[] key) { - return immutableData.ContainsKey(key); + return _immutableData.ContainsKey(key); } } } diff --git a/src/Neo/Persistence/MemoryStore.cs b/src/Neo/Persistence/MemoryStore.cs index c66d132dd2..d1eb91f8af 100644 --- a/src/Neo/Persistence/MemoryStore.cs +++ b/src/Neo/Persistence/MemoryStore.cs @@ -9,10 +9,12 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +#nullable enable + using Neo.Extensions; -using Neo.IO; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; @@ -62,14 +64,14 @@ public void Put(byte[] key, byte[] value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public byte[] TryGet(byte[] key) + public byte[]? TryGet(byte[] key) { - if (!_innerData.TryGetValue(key, out byte[] value)) return null; + if (!_innerData.TryGetValue(key, out var value)) return null; return value[..]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryGet(byte[] key, out byte[] value) + public bool TryGet(byte[] key, [NotNullWhen(true)] out byte[] value) { return _innerData.TryGetValue(key, out value); } diff --git a/src/Neo/Persistence/SnapshotCache.cs b/src/Neo/Persistence/SnapshotCache.cs index 025f0eb04d..912a9f5512 100644 --- a/src/Neo/Persistence/SnapshotCache.cs +++ b/src/Neo/Persistence/SnapshotCache.cs @@ -9,6 +9,8 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +#nullable enable + using Neo.Extensions; using Neo.SmartContract; using System; @@ -22,8 +24,8 @@ namespace Neo.Persistence /// public class SnapshotCache : DataCache, IDisposable { - private readonly IReadOnlyStore store; - private readonly ISnapshot snapshot; + private readonly IReadOnlyStore _store; + private readonly ISnapshot? _snapshot; /// /// Initializes a new instance of the class. @@ -31,58 +33,58 @@ public class SnapshotCache : DataCache, IDisposable /// An to create a readonly cache; or an to create a snapshot cache. public SnapshotCache(IReadOnlyStore store) { - this.store = store; - snapshot = store as ISnapshot; + _store = store; + _snapshot = store as ISnapshot; } protected override void AddInternal(StorageKey key, StorageItem value) { - snapshot?.Put(key.ToArray(), value.ToArray()); + _snapshot?.Put(key.ToArray(), value.ToArray()); } protected override void DeleteInternal(StorageKey key) { - snapshot?.Delete(key.ToArray()); + _snapshot?.Delete(key.ToArray()); } public override void Commit() { base.Commit(); - snapshot?.Commit(); + _snapshot?.Commit(); } protected override bool ContainsInternal(StorageKey key) { - return store.Contains(key.ToArray()); + return _store.Contains(key.ToArray()); } public void Dispose() { - snapshot?.Dispose(); + _snapshot?.Dispose(); } /// protected override StorageItem GetInternal(StorageKey key) { - if (store.TryGet(key.ToArray(), out var value)) + if (_store.TryGet(key.ToArray(), out var value)) return new(value); throw new KeyNotFoundException(); } protected override IEnumerable<(StorageKey, StorageItem)> SeekInternal(byte[] keyOrPrefix, SeekDirection direction) { - return store.Seek(keyOrPrefix, direction).Select(p => (new StorageKey(p.Key), new StorageItem(p.Value))); + return _store.Seek(keyOrPrefix, direction).Select(p => (new StorageKey(p.Key), new StorageItem(p.Value))); } /// - protected override StorageItem TryGetInternal(StorageKey key) + protected override StorageItem? TryGetInternal(StorageKey key) { - return store.TryGet(key.ToArray(), out var value) ? new(value) : null; + return _store.TryGet(key.ToArray(), out var value) ? new(value) : null; } protected override void UpdateInternal(StorageKey key, StorageItem value) { - snapshot?.Put(key.ToArray(), value.ToArray()); + _snapshot?.Put(key.ToArray(), value.ToArray()); } } }