You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

55 lines
1.3 KiB

  1. using System;
  2. using System.Text;
  3. namespace MQTTnet.Serializer
  4. {
  5. public class MqttPacketBodyReader
  6. {
  7. private readonly byte[] _buffer;
  8. private int _offset;
  9. public MqttPacketBodyReader(byte[] buffer)
  10. {
  11. _buffer = buffer;
  12. }
  13. public int Length => _buffer.Length - _offset;
  14. public bool EndOfStream => _offset == _buffer.Length;
  15. public byte ReadByte()
  16. {
  17. return _buffer[_offset++];
  18. }
  19. public ArraySegment<byte> ReadRemainingData()
  20. {
  21. return new ArraySegment<byte>(_buffer, _offset, _buffer.Length - _offset);
  22. }
  23. public ushort ReadUInt16()
  24. {
  25. var msb = _buffer[_offset++];
  26. var lsb = _buffer[_offset++];
  27. return (ushort)(msb << 8 | lsb);
  28. }
  29. public ArraySegment<byte> ReadWithLengthPrefix()
  30. {
  31. var length = ReadUInt16();
  32. var result = new ArraySegment<byte>(_buffer, _offset, length);
  33. _offset += length;
  34. return result;
  35. }
  36. public string ReadStringWithLengthPrefix()
  37. {
  38. var buffer = ReadWithLengthPrefix();
  39. return Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
  40. }
  41. }
  42. }