| | 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 PongPayloadSerializer : IPayloadSerializer<PongPayload> |
| | 13 | | { |
| | 14 | | public async Task SerializeAsync(IMessagePayload payload, Stream stream) |
| | 15 | | { |
| 4 | 16 | | if (payload is not PongPayload pongPayload) |
| 0 | 17 | | throw new SerializationException($"Payload is not of type {nameof(PongPayload)}"); |
| | 18 | |
|
| 4 | 19 | | await stream.WriteAsync(EndianBitConverter.GetBytesBigEndian(pongPayload.BytesLength)); |
| 4 | 20 | | await stream.WriteAsync(pongPayload.Ignored); |
| 4 | 21 | | } |
| | 22 | |
|
| | 23 | | public async Task<PongPayload?> DeserializeAsync(Stream stream) |
| | 24 | | { |
| 4 | 25 | | var buffer = ArrayPool<byte>.Shared.Rent(sizeof(ushort)); |
| | 26 | |
|
| | 27 | | try |
| | 28 | | { |
| 4 | 29 | | await stream.ReadExactlyAsync(buffer.AsMemory()[..sizeof(ushort)]); |
| 4 | 30 | | var bytesLength = EndianBitConverter.ToUInt16BigEndian(buffer[..sizeof(ushort)]); |
| | 31 | |
|
| 4 | 32 | | if (stream.Length - stream.Position < bytesLength) |
| 0 | 33 | | throw new SerializationException( |
| 0 | 34 | | $"Invalid Ignored data for {nameof(PongPayload)}. Expected {bytesLength} bytes."); |
| | 35 | |
|
| 4 | 36 | | return new PongPayload(bytesLength); |
| | 37 | | } |
| 0 | 38 | | catch (Exception e) |
| | 39 | | { |
| 0 | 40 | | throw new PayloadSerializationException($"Error deserializing {nameof(PongPayload)}", e); |
| | 41 | | } |
| | 42 | | finally |
| | 43 | | { |
| 4 | 44 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 45 | | } |
| 4 | 46 | | } |
| | 47 | |
|
| | 48 | | async Task<IMessagePayload?> IPayloadSerializer.DeserializeAsync(Stream stream) |
| | 49 | | { |
| 0 | 50 | | return await DeserializeAsync(stream); |
| 0 | 51 | | } |
| | 52 | | } |