| | 1 | | using System.Buffers; |
| | 2 | | using NLightning.Domain.Channels.ValueObjects; |
| | 3 | | using NLightning.Domain.Interfaces; |
| | 4 | | using NLightning.Domain.Serialization.Interfaces; |
| | 5 | |
|
| | 6 | | namespace NLightning.Infrastructure.Serialization.ValueObjects; |
| | 7 | | public class ShortChannelIdTypeSerializer : IValueObjectTypeSerializer<ShortChannelId> |
| | 8 | | { |
| | 9 | | /// <summary> |
| | 10 | | /// Serializes a ShortChannelId value into a stream. |
| | 11 | | /// </summary> |
| | 12 | | /// <param name="valueObject">The ShortChannelId value to serialize.</param> |
| | 13 | | /// <param name="stream">The stream where the serialized value will be written.</param> |
| | 14 | | /// <returns>A task that represents the asynchronous serialization operation.</returns> |
| | 15 | | /// <exception cref="ArgumentNullException">Thrown when the stream is null.</exception> |
| | 16 | | /// <exception cref="IOException">Thrown when an I/O error occurs during the write operation.</exception> |
| | 17 | | public async Task SerializeAsync(IValueObject valueObject, Stream stream) |
| | 18 | | { |
| 4 | 19 | | if (valueObject is not ShortChannelId shortChannelId) |
| 0 | 20 | | throw new ArgumentException("Value object must be of type ShortChannelId.", nameof(valueObject)); |
| | 21 | |
|
| 4 | 22 | | await stream.WriteAsync(shortChannelId); |
| 4 | 23 | | } |
| | 24 | |
|
| | 25 | | /// <summary> |
| | 26 | | /// Deserializes a ShortChannelId value from a stream. |
| | 27 | | /// </summary> |
| | 28 | | /// <param name="stream">The stream from which the ShortChannelId value will be deserialized.</param> |
| | 29 | | /// <returns>A task that represents the asynchronous deserialization operation, containing the deserialized ShortCha |
| | 30 | | /// <exception cref="ArgumentException">Thrown when the stream is empty or contains insufficient data for deserializ |
| | 31 | | /// <exception cref="IOException">Thrown when an I/O error occurs during the read operation.</exception> |
| | 32 | | public async Task<ShortChannelId> DeserializeAsync(Stream stream) |
| | 33 | | { |
| 4 | 34 | | var buffer = ArrayPool<byte>.Shared.Rent(ShortChannelId.Length); |
| | 35 | |
|
| | 36 | | try |
| | 37 | | { |
| 4 | 38 | | await stream.ReadExactlyAsync(buffer.AsMemory()[..ShortChannelId.Length]); |
| | 39 | |
|
| 4 | 40 | | return new ShortChannelId(buffer[..ShortChannelId.Length]); |
| | 41 | | } |
| | 42 | | finally |
| | 43 | | { |
| 4 | 44 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 45 | | } |
| 4 | 46 | | } |
| | 47 | | async Task<IValueObject> IValueObjectTypeSerializer.DeserializeAsync(Stream stream) |
| | 48 | | { |
| 0 | 49 | | return await DeserializeAsync(stream); |
| 0 | 50 | | } |
| | 51 | | } |