Utils.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Runtime.CompilerServices;
  2. namespace kcp2k
  3. {
  4. public static partial class Utils
  5. {
  6. // Clamp so we don't have to depend on UnityEngine
  7. public static int Clamp(int value, int min, int max)
  8. {
  9. if (value < min) return min;
  10. if (value > max) return max;
  11. return value;
  12. }
  13. // encode 8 bits unsigned int
  14. public static int Encode8u(byte[] p, int offset, byte c)
  15. {
  16. p[0 + offset] = c;
  17. return 1;
  18. }
  19. // decode 8 bits unsigned int
  20. public static int Decode8u(byte[] p, int offset, ref byte c)
  21. {
  22. c = p[0 + offset];
  23. return 1;
  24. }
  25. // encode 16 bits unsigned int (lsb)
  26. public static int Encode16U(byte[] p, int offset, ushort w)
  27. {
  28. p[0 + offset] = (byte)(w >> 0);
  29. p[1 + offset] = (byte)(w >> 8);
  30. return 2;
  31. }
  32. // decode 16 bits unsigned int (lsb)
  33. public static int Decode16U(byte[] p, int offset, ref ushort c)
  34. {
  35. ushort result = 0;
  36. result |= p[0 + offset];
  37. result |= (ushort)(p[1 + offset] << 8);
  38. c = result;
  39. return 2;
  40. }
  41. // encode 32 bits unsigned int (lsb)
  42. public static int Encode32U(byte[] p, int offset, uint l)
  43. {
  44. p[0 + offset] = (byte)(l >> 0);
  45. p[1 + offset] = (byte)(l >> 8);
  46. p[2 + offset] = (byte)(l >> 16);
  47. p[3 + offset] = (byte)(l >> 24);
  48. return 4;
  49. }
  50. // decode 32 bits unsigned int (lsb)
  51. public static int Decode32U(byte[] p, int offset, ref uint c)
  52. {
  53. uint result = 0;
  54. result |= p[0 + offset];
  55. result |= (uint)(p[1 + offset] << 8);
  56. result |= (uint)(p[2 + offset] << 16);
  57. result |= (uint)(p[3 + offset] << 24);
  58. c = result;
  59. return 4;
  60. }
  61. // timediff was a macro in original Kcp. let's inline it if possible.
  62. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  63. public static int TimeDiff(uint later, uint earlier)
  64. {
  65. return (int)(later - earlier);
  66. }
  67. }
  68. }