| | 1 | | using System.Buffers; |
| | 2 | | using System.Runtime.Serialization; |
| | 3 | | using NLightning.Domain.Serialization.Payloads; |
| | 4 | |
|
| | 5 | | namespace NLightning.Infrastructure.Serialization.Payloads; |
| | 6 | |
|
| | 7 | | using Converters; |
| | 8 | | using Domain.Protocol.Payloads; |
| | 9 | | using Domain.Protocol.Payloads.Interfaces; |
| | 10 | | using Exceptions; |
| | 11 | |
|
| | 12 | | public class PingPayloadSerializer : IPayloadSerializer<PingPayload> |
| | 13 | | { |
| | 14 | | public async Task SerializeAsync(IMessagePayload payload, Stream stream) |
| | 15 | | { |
| 4 | 16 | | if (payload is not PingPayload pingPayload) |
| 0 | 17 | | throw new SerializationException($"Payload is not of type {nameof(PingPayload)}"); |
| | 18 | |
|
| 4 | 19 | | await stream.WriteAsync(EndianBitConverter.GetBytesBigEndian(pingPayload.NumPongBytes)); |
| 4 | 20 | | await stream.WriteAsync(EndianBitConverter.GetBytesBigEndian(pingPayload.BytesLength)); |
| 4 | 21 | | await stream.WriteAsync(pingPayload.Ignored); |
| 4 | 22 | | } |
| | 23 | |
|
| | 24 | | public async Task<PingPayload?> DeserializeAsync(Stream stream) |
| | 25 | | { |
| 4 | 26 | | var buffer = ArrayPool<byte>.Shared.Rent(sizeof(ushort)); |
| | 27 | |
|
| | 28 | | try |
| | 29 | | { |
| 4 | 30 | | await stream.ReadExactlyAsync(buffer.AsMemory()[..sizeof(ushort)]); |
| 4 | 31 | | var numPongBytes = EndianBitConverter.ToUInt16BigEndian(buffer[..sizeof(ushort)]); |
| | 32 | |
|
| 4 | 33 | | await stream.ReadExactlyAsync(buffer.AsMemory()[..sizeof(ushort)]); |
| 4 | 34 | | var bytesLength = EndianBitConverter.ToUInt16BigEndian(buffer[..sizeof(ushort)]); |
| | 35 | |
|
| 4 | 36 | | if (stream.Length - stream.Position < bytesLength) |
| 0 | 37 | | throw new SerializationException( |
| 0 | 38 | | $"Invalid Ignored data for PingPayload. Expected {bytesLength} bytes."); |
| | 39 | |
|
| 4 | 40 | | return new PingPayload |
| 4 | 41 | | { |
| 4 | 42 | | NumPongBytes = numPongBytes, |
| 4 | 43 | | BytesLength = bytesLength |
| 4 | 44 | | }; |
| | 45 | | } |
| 0 | 46 | | catch (Exception e) |
| | 47 | | { |
| 0 | 48 | | throw new PayloadSerializationException("Error deserializing PingPayload", e); |
| | 49 | | } |
| | 50 | | finally |
| | 51 | | { |
| 4 | 52 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 53 | | } |
| 4 | 54 | | } |
| | 55 | |
|
| | 56 | | async Task<IMessagePayload?> IPayloadSerializer.DeserializeAsync(Stream stream) |
| | 57 | | { |
| 0 | 58 | | return await DeserializeAsync(stream); |
| 0 | 59 | | } |
| | 60 | | } |