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