Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ReaderExtensions.cs 2.6 KiB

pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Buffers;
  3. using MQTTnet.Adapter;
  4. using MQTTnet.Exceptions;
  5. using MQTTnet.Packets;
  6. using MQTTnet.Serializer;
  7. namespace MQTTnet.AspNetCore
  8. {
  9. public static class ReaderExtensions
  10. {
  11. public static bool TryDeserialize(this IMqttPacketSerializer serializer, in ReadOnlySequence<byte> input, out MqttBasePacket packet, out SequencePosition consumed, out SequencePosition observed)
  12. {
  13. packet = null;
  14. consumed = input.Start;
  15. observed = input.End;
  16. var copy = input;
  17. if (copy.Length < 2)
  18. {
  19. return false;
  20. }
  21. var fixedheader = copy.First.Span[0];
  22. if (!TryReadBodyLength(ref copy, out var bodyLength))
  23. {
  24. return false;
  25. }
  26. if (copy.Length < bodyLength)
  27. {
  28. return false;
  29. }
  30. var bodySlice = copy.Slice(0, bodyLength);
  31. packet = serializer.Deserialize(new ReceivedMqttPacket(fixedheader, new MqttPacketBodyReader(bodySlice.GetArray(), 0)));
  32. consumed = bodySlice.End;
  33. observed = bodySlice.End;
  34. return true;
  35. }
  36. private static byte[] GetArray(this in ReadOnlySequence<byte> input)
  37. {
  38. if (input.IsSingleSegment)
  39. {
  40. return input.First.Span.ToArray();
  41. }
  42. // Should be rare
  43. return input.ToArray();
  44. }
  45. private static bool TryReadBodyLength(ref ReadOnlySequence<byte> input, out int result)
  46. {
  47. // Alorithm taken from https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html.
  48. var multiplier = 1;
  49. var value = 0;
  50. byte encodedByte;
  51. var index = 1;
  52. result = 0;
  53. var temp = input.Slice(0, Math.Min(5, input.Length)).GetArray();
  54. do
  55. {
  56. if (index == temp.Length)
  57. {
  58. return false;
  59. }
  60. encodedByte = temp[index];
  61. index++;
  62. value += (byte)(encodedByte & 127) * multiplier;
  63. if (multiplier > 128 * 128 * 128)
  64. {
  65. throw new MqttProtocolViolationException($"Remaining length is invalid (Data={string.Join(",", temp.AsSpan(1, index).ToArray())}).");
  66. }
  67. multiplier *= 128;
  68. } while ((encodedByte & 128) != 0);
  69. input = input.Slice(index);
  70. result = value;
  71. return true;
  72. }
  73. }
  74. }