Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.03 KB | None | 0 0
  1. public struct BitInputStream : INetworkStream
  2. {
  3. public uint Length { get; }
  4.  
  5. private int SizeBytes => _currentByteIndex * sizeof(byte);
  6.  
  7. private readonly unsafe byte* _buffer;
  8. private int _currentByteIndex;
  9.  
  10. public unsafe BitInputStream(byte[] buffer)
  11. {
  12. Length = (uint)buffer.Length;
  13. fixed (byte* ptr = buffer)
  14. {
  15. _buffer = ptr;
  16. }
  17.  
  18. _currentByteIndex = 0;
  19. }
  20.  
  21. public unsafe void Process<T>(ref T value) where T : unmanaged
  22. {
  23. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  24. var newLength = _currentByteIndex + sizeof(T);
  25. if (newLength > Length)
  26. throw new IndexOutOfRangeException($"New length of buffer: {newLength} is out of range in buffer of '{Length}' Length.");
  27. #endif
  28. value = *(T*) (_buffer + _currentByteIndex);
  29. _currentByteIndex += sizeof(T);
  30. }
  31.  
  32. public unsafe void Process(ref bool value)
  33. {
  34. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  35. var newLength = _currentByteIndex + sizeof(byte);
  36. if (newLength > Length)
  37. throw new IndexOutOfRangeException($"New length of buffer: {newLength} is out of range in buffer of '{Length}' Length.");
  38. #endif
  39. value = *(_buffer + _currentByteIndex) != 0;
  40. _currentByteIndex += sizeof(byte);
  41. }
  42.  
  43. public void Process(ref float value, CastType castType = CastType.Float, int precision = 1)
  44. {
  45. switch (castType)
  46. {
  47. case CastType.Byte:
  48. value = (float) Process<byte>() / precision;
  49. break;
  50. case CastType.Short:
  51. value = (float) Process<short>() / precision;
  52. break;
  53. case CastType.Int:
  54. value = (float) Process<int>() / precision;
  55. break;
  56. case CastType.Long:
  57. value = (float) Process<long>() / precision;
  58. break;
  59. case CastType.Float:
  60. value = Process<float>() / precision;
  61. break;
  62. }
  63. }
  64.  
  65. public unsafe byte[] ToArrayAndFlush()
  66. {
  67. var data = new byte[SizeBytes];
  68. fixed (byte* ptr = data)
  69. {
  70. Buffer.MemoryCopy(_buffer, ptr, SizeBytes, SizeBytes);
  71. }
  72. _currentByteIndex = 0;
  73. return data;
  74. }
  75.  
  76. private unsafe T Process<T>() where T : unmanaged
  77. {
  78. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  79. var newLength = _currentByteIndex + sizeof(T);
  80. if (newLength > Length)
  81. throw new IndexOutOfRangeException($"New length of buffer: {newLength} is out of range in buffer of '{Length}' Length.");
  82. #endif
  83. var value = *(T*) (_buffer + _currentByteIndex);
  84. _currentByteIndex += sizeof(T);
  85. return value;
  86. }
  87.  
  88. public void Dispose()
  89. {
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement