MqttPacketWriter.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Text;
  4. using MQTTnet.Protocol;
  5. namespace MQTTnet.Formatter
  6. {
  7. /// <summary>
  8. /// This is a custom implementation of a memory stream which provides only MQTTnet relevant features.
  9. /// The goal is to avoid lots of argument checks like in the original stream. The growth rule is the
  10. /// same as for the original MemoryStream in .net. Also this implementation allows accessing the internal
  11. /// buffer for all platforms and .net framework versions (which is not available at the regular MemoryStream).
  12. /// </summary>
  13. public class MqttPacketWriter : IMqttPacketWriter
  14. {
  15. private static readonly ArraySegment<byte> ZeroVariableLengthIntegerArray = new ArraySegment<byte>(new byte[1], 0, 1);
  16. private static readonly ArraySegment<byte> ZeroTwoByteIntegerArray = new ArraySegment<byte>(new byte[2], 0, 2);
  17. public static int InitialBufferSize = 128;
  18. public static int MaxBufferSize = 4096;
  19. private byte[] _buffer = new byte[InitialBufferSize];
  20. private int _offset;
  21. public int Length { get; private set; }
  22. public static byte BuildFixedHeader(MqttControlPacketType packetType, byte flags = 0)
  23. {
  24. var fixedHeader = (int)packetType << 4;
  25. fixedHeader |= flags;
  26. return (byte)fixedHeader;
  27. }
  28. public static int GetLengthOfVariableInteger(uint value)
  29. {
  30. var result = 0;
  31. var x = value;
  32. do
  33. {
  34. x = x / 128;
  35. result++;
  36. } while (x > 0);
  37. return result;
  38. }
  39. public static ArraySegment<byte> EncodeVariableLengthInteger(uint value)
  40. {
  41. if (value == 0)
  42. {
  43. return ZeroVariableLengthIntegerArray;
  44. }
  45. if (value <= 127)
  46. {
  47. return new ArraySegment<byte>(new[] { (byte)value }, 0, 1);
  48. }
  49. var buffer = new byte[4];
  50. var bufferOffset = 0;
  51. var x = value;
  52. do
  53. {
  54. var encodedByte = x % 128;
  55. x = x / 128;
  56. if (x > 0)
  57. {
  58. encodedByte = encodedByte | 128;
  59. }
  60. buffer[bufferOffset] = (byte)encodedByte;
  61. bufferOffset++;
  62. } while (x > 0);
  63. return new ArraySegment<byte>(buffer, 0, bufferOffset);
  64. }
  65. public void WriteVariableLengthInteger(uint value)
  66. {
  67. Write(EncodeVariableLengthInteger(value));
  68. }
  69. public void WriteWithLengthPrefix(string value)
  70. {
  71. if (string.IsNullOrEmpty(value))
  72. {
  73. Write(ZeroTwoByteIntegerArray);
  74. }
  75. else
  76. {
  77. WriteWithLengthPrefix(Encoding.UTF8.GetBytes(value));
  78. }
  79. }
  80. public void WriteWithLengthPrefix(byte[] value)
  81. {
  82. if (value == null || value.Length == 0)
  83. {
  84. Write(ZeroTwoByteIntegerArray);
  85. }
  86. else
  87. {
  88. EnsureAdditionalCapacity(value.Length + 2);
  89. Write((ushort)value.Length);
  90. Write(value, 0, value.Length);
  91. }
  92. }
  93. public void Write(byte @byte)
  94. {
  95. EnsureAdditionalCapacity(1);
  96. _buffer[_offset] = @byte;
  97. IncreasePosition(1);
  98. }
  99. public void Write(ushort value)
  100. {
  101. EnsureAdditionalCapacity(2);
  102. _buffer[_offset] = (byte)(value >> 8);
  103. IncreasePosition(1);
  104. _buffer[_offset] = (byte)value;
  105. IncreasePosition(1);
  106. }
  107. public void Write(byte[] buffer, int offset, int count)
  108. {
  109. if (buffer == null) throw new ArgumentNullException(nameof(buffer));
  110. if (count == 0)
  111. {
  112. return;
  113. }
  114. EnsureAdditionalCapacity(count);
  115. Array.Copy(buffer, offset, _buffer, _offset, count);
  116. IncreasePosition(count);
  117. }
  118. public void Write(IMqttPacketWriter propertyWriter)
  119. {
  120. if (propertyWriter == null) throw new ArgumentNullException(nameof(propertyWriter));
  121. if (propertyWriter is MqttPacketWriter writer)
  122. {
  123. if (writer.Length == 0)
  124. {
  125. return;
  126. }
  127. Write(writer._buffer, 0, writer.Length);
  128. return;
  129. }
  130. throw new InvalidOperationException($"{nameof(propertyWriter)} must be of type {typeof(MqttPacketWriter).Name}");
  131. }
  132. public void Reset(int length)
  133. {
  134. Length = length;
  135. }
  136. public void Seek(int position)
  137. {
  138. EnsureCapacity(position);
  139. _offset = position;
  140. }
  141. public byte[] GetBuffer()
  142. {
  143. return _buffer;
  144. }
  145. public void FreeBuffer()
  146. {
  147. // This method frees the used memory by shrinking the buffer. This is required because the buffer
  148. // is used across several messages. In general this is not a big issue because subsequent Ping packages
  149. // have the same size but a very big publish package with 100 MB of payload will increase the buffer
  150. // a lot and the size will never reduced. So this method tries to find a size which can be held in
  151. // memory for a long time without causing troubles.
  152. if (_buffer.Length < MaxBufferSize)
  153. {
  154. return;
  155. }
  156. Array.Resize(ref _buffer, MaxBufferSize);
  157. }
  158. private void Write(ArraySegment<byte> buffer)
  159. {
  160. Write(buffer.Array, buffer.Offset, buffer.Count);
  161. }
  162. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  163. private void EnsureAdditionalCapacity(int additionalCapacity)
  164. {
  165. var freeSpace = _buffer.Length - _offset;
  166. if (freeSpace >= additionalCapacity)
  167. {
  168. return;
  169. }
  170. EnsureCapacity(_buffer.Length + additionalCapacity - freeSpace);
  171. }
  172. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  173. private void EnsureCapacity(int capacity)
  174. {
  175. var newBufferLength = _buffer.Length;
  176. if (newBufferLength >= capacity)
  177. {
  178. return;
  179. }
  180. while (newBufferLength < capacity)
  181. {
  182. newBufferLength *= 2;
  183. }
  184. Array.Resize(ref _buffer, newBufferLength);
  185. }
  186. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  187. private void IncreasePosition(int length)
  188. {
  189. _offset += length;
  190. if (_offset > Length)
  191. {
  192. Length = _offset;
  193. }
  194. }
  195. }
  196. }