|
| 1 | +namespace Python.Runtime |
| 2 | +{ |
| 3 | + using System; |
| 4 | + |
| 5 | + public struct RawImmutableMemBlock: IEquatable<RawImmutableMemBlock> |
| 6 | + { |
| 7 | + private readonly int _hash; |
| 8 | + |
| 9 | + public RawImmutableMemBlock(IntPtr ptr, int size) |
| 10 | + { |
| 11 | + if (ptr == IntPtr.Zero) |
| 12 | + { |
| 13 | + throw new ArgumentException("Memory pointer should not be zero", nameof(ptr)); |
| 14 | + } |
| 15 | + |
| 16 | + if (size < 0) |
| 17 | + { |
| 18 | + throw new ArgumentOutOfRangeException(nameof(size), "Size should be zero or positive."); |
| 19 | + } |
| 20 | + |
| 21 | + Ptr = ptr; |
| 22 | + Size = size; |
| 23 | + _hash = RawMemUtils.FastXorHash(ptr, size); |
| 24 | + } |
| 25 | + |
| 26 | + public RawImmutableMemBlock(RawImmutableMemBlock memBlock, IntPtr newPtr) |
| 27 | + { |
| 28 | + if (memBlock.Ptr == IntPtr.Zero) |
| 29 | + { |
| 30 | + throw new ArgumentException("Cannot copy non initialized RawImmutableMemBlock structure.", nameof(memBlock)); |
| 31 | + } |
| 32 | + |
| 33 | + if (newPtr == IntPtr.Zero) |
| 34 | + { |
| 35 | + throw new ArgumentException("Cannot copy to zero pointer."); |
| 36 | + } |
| 37 | + |
| 38 | + RawMemUtils.CopyMemBlocks(memBlock.Ptr, newPtr, memBlock.Size); |
| 39 | + Ptr = newPtr; |
| 40 | + Size = memBlock.Size; |
| 41 | + _hash = memBlock._hash; |
| 42 | + } |
| 43 | + |
| 44 | + public IntPtr Ptr { get; } |
| 45 | + |
| 46 | + public int Size { get; } |
| 47 | + |
| 48 | + public bool Equals(RawImmutableMemBlock other) |
| 49 | + { |
| 50 | + bool preEqual = _hash == other._hash && Size == other.Size; |
| 51 | + if (!preEqual) |
| 52 | + { |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + return RawMemUtils.CompareMemBlocks(Ptr, other.Ptr, Size); |
| 57 | + } |
| 58 | + |
| 59 | + /// <inheritdoc/> |
| 60 | + public override bool Equals(object obj) |
| 61 | + { |
| 62 | + return obj is RawImmutableMemBlock && Equals((RawImmutableMemBlock)obj); |
| 63 | + } |
| 64 | + |
| 65 | + /// <inheritdoc/> |
| 66 | + public override int GetHashCode() |
| 67 | + { |
| 68 | + unchecked |
| 69 | + { |
| 70 | + return (_hash * 397) ^ Size; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + public static bool operator ==(RawImmutableMemBlock left, RawImmutableMemBlock right) |
| 75 | + { |
| 76 | + return left.Equals(right); |
| 77 | + } |
| 78 | + |
| 79 | + public static bool operator !=(RawImmutableMemBlock left, RawImmutableMemBlock right) |
| 80 | + { |
| 81 | + return !left.Equals(right); |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments