1
0

Added Converters/Formatters for Serialization of Json/MessagePack

This commit is contained in:
2022-08-04 22:34:14 +02:00
parent aeaeeb16c1
commit 1522c0cbc9
7 changed files with 340 additions and 1 deletions

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
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);
Swap(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.ToArray(), options);
}
private void Swap(byte[] bytes)
{
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
}
}
}