Int24.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace IP2Region.Models
  5. {
  6. internal struct Int24
  7. {
  8. private byte Byte1;
  9. private byte Byte2;
  10. private byte Byte3;
  11. internal Int24(int value)
  12. {
  13. if (value > 0x00FFFFFF)
  14. {
  15. throw new ArgumentException("Int24 max value must be smaller than 0x00FFFFFF");
  16. }
  17. ref byte ptr = ref Unsafe.As<int, byte>(ref value);
  18. Byte1 = ptr;
  19. Byte2 = Unsafe.Add(ref ptr, 1);
  20. Byte3 = Unsafe.Add(ref ptr, 2);
  21. }
  22. internal void SetValue(int value)
  23. {
  24. if (value > 0x00FFFFFF)
  25. {
  26. throw new ArgumentException("Int24 max value must be smaller than 0x00FFFFFF");
  27. }
  28. ref byte ptr = ref Unsafe.As<int, byte>(ref value);
  29. Byte1 = ptr;
  30. Byte2 = Unsafe.Add(ref ptr, 1);
  31. Byte3 = Unsafe.Add(ref ptr, 2);
  32. }
  33. internal int GetValue()
  34. {
  35. int value = 0;
  36. ref byte ptr = ref Unsafe.As<int, byte>(ref value);
  37. ptr = Byte1;
  38. Unsafe.Add(ref ptr, 1) = Byte2;
  39. Unsafe.Add(ref ptr, 2) = Byte3;
  40. return value;
  41. }
  42. public static int operator +(Int24 a, Int24 b)
  43. {
  44. return a.GetValue() + b.GetValue();
  45. }
  46. public static Int24 operator -(Int24 a, Int24 b)
  47. {
  48. return new Int24(a.GetValue() - b.GetValue());
  49. }
  50. public static int operator *(Int24 a, Int24 b)
  51. {
  52. return a.GetValue() * b.GetValue();
  53. }
  54. public static int operator /(Int24 a, Int24 b)
  55. {
  56. return new Int24(a.GetValue() / b.GetValue());
  57. }
  58. public static bool operator ==(int a, Int24 b)
  59. {
  60. return a == b.GetValue();
  61. }
  62. public static bool operator !=(int a, Int24 b)
  63. {
  64. return a == b.GetValue();
  65. }
  66. public static implicit operator int (Int24 operand)
  67. {
  68. return operand.GetValue();
  69. }
  70. public static explicit operator Int24(int operand)
  71. {
  72. return new Int24(operand);
  73. }
  74. public override bool Equals(object obj)
  75. {
  76. int value = (int)obj;
  77. return value == GetValue();
  78. }
  79. public override int GetHashCode()
  80. {
  81. return GetValue();
  82. }
  83. }
  84. }