UInt128.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using System.Numerics;
  3. namespace Ryujinx.Graphics.Shader.Translation
  4. {
  5. struct UInt128 : IEquatable<UInt128>
  6. {
  7. public static UInt128 Zero => new UInt128() { _v0 = 0, _v1 = 0 };
  8. private ulong _v0;
  9. private ulong _v1;
  10. public UInt128(ulong low, ulong high)
  11. {
  12. _v0 = low;
  13. _v1 = high;
  14. }
  15. public int TrailingZeroCount()
  16. {
  17. int count = BitOperations.TrailingZeroCount(_v0);
  18. if (count == 64)
  19. {
  20. count += BitOperations.TrailingZeroCount(_v1);
  21. }
  22. return count;
  23. }
  24. public static UInt128 Pow2(int x)
  25. {
  26. if (x >= 64)
  27. {
  28. return new UInt128(0, 1UL << (x - 64));
  29. }
  30. return new UInt128(1UL << x, 0);
  31. }
  32. public static UInt128 operator ~(UInt128 x)
  33. {
  34. return new UInt128(~x._v0, ~x._v1);
  35. }
  36. public static UInt128 operator &(UInt128 x, UInt128 y)
  37. {
  38. return new UInt128(x._v0 & y._v0, x._v1 & y._v1);
  39. }
  40. public static UInt128 operator |(UInt128 x, UInt128 y)
  41. {
  42. return new UInt128(x._v0 | y._v0, x._v1 | y._v1);
  43. }
  44. public static UInt128 operator <<(UInt128 x, int shift)
  45. {
  46. if (shift == 0)
  47. {
  48. return new UInt128(x._v0, x._v1);
  49. }
  50. else if (shift >= 64)
  51. {
  52. return new UInt128(0, x._v0 << (shift - 64));
  53. }
  54. ulong shiftOut = x._v0 >> (64 - shift);
  55. return new UInt128(x._v0 << shift, (x._v1 << shift) | shiftOut);
  56. }
  57. public static UInt128 operator >>(UInt128 x, int shift)
  58. {
  59. if (shift == 0)
  60. {
  61. return new UInt128(x._v0, x._v1);
  62. }
  63. else if (shift >= 64)
  64. {
  65. return new UInt128(x._v1 >> (shift - 64), 0);
  66. }
  67. ulong shiftOut = x._v1 & ((1UL << shift) - 1);
  68. return new UInt128((x._v0 >> shift) | (shiftOut << (64 - shift)), x._v1 >> shift);
  69. }
  70. public static bool operator ==(UInt128 x, UInt128 y)
  71. {
  72. return x.Equals(y);
  73. }
  74. public static bool operator !=(UInt128 x, UInt128 y)
  75. {
  76. return !x.Equals(y);
  77. }
  78. public override bool Equals(object obj)
  79. {
  80. return obj is UInt128 other && Equals(other);
  81. }
  82. public bool Equals(UInt128 other)
  83. {
  84. return _v0 == other._v0 && _v1 == other._v1;
  85. }
  86. public override int GetHashCode()
  87. {
  88. return HashCode.Combine(_v0, _v1);
  89. }
  90. }
  91. }