Updated to C# 12
This commit is contained in:
67
AMWD.Common.MessagePack/Formatters/IPAddressListFormatter.cs
Normal file
67
AMWD.Common.MessagePack/Formatters/IPAddressListFormatter.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using AMWD.Common.MessagePack.Utilities;
|
||||
|
||||
namespace MessagePack.Formatters
|
||||
{
|
||||
/// <summary>
|
||||
/// Serialization of an <see cref="IPAddress"/> list to and from <see cref="MessagePack"/>.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class IPAddressListFormatter : IMessagePackFormatter<List<IPAddress>>
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public List<IPAddress> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.IsNil)
|
||||
return null;
|
||||
|
||||
byte[] bytes = options.Resolver.GetFormatterWithVerify<byte[]>().Deserialize(ref reader, options);
|
||||
|
||||
// skipping the length information
|
||||
int bytePos = sizeof(int);
|
||||
|
||||
var list = new List<IPAddress>();
|
||||
while (bytePos < bytes.Length)
|
||||
{
|
||||
byte len = bytes.Skip(bytePos).First();
|
||||
bytePos++;
|
||||
|
||||
byte[] buffer = bytes.Skip(bytePos).Take(len).ToArray();
|
||||
bytePos += len;
|
||||
|
||||
list.Add(new IPAddress(buffer));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Serialize(ref MessagePackWriter writer, List<IPAddress> value, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNil();
|
||||
return;
|
||||
}
|
||||
|
||||
var bytes = new List<byte>();
|
||||
|
||||
int length = value.Count;
|
||||
byte[] buffer = BitConverter.GetBytes(length);
|
||||
NetworkHelper.SwapBigEndian(buffer);
|
||||
bytes.AddRange(buffer);
|
||||
|
||||
foreach (var ip in value)
|
||||
{
|
||||
buffer = ip.GetAddressBytes();
|
||||
bytes.Add((byte)buffer.Length);
|
||||
bytes.AddRange(buffer);
|
||||
}
|
||||
|
||||
options.Resolver.GetFormatterWithVerify<byte[]>().Serialize(ref writer, [.. bytes], options);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user