Adding IPNetwork to Converter/Formatters
This commit is contained in:
59
AMWD.Common/Formatters/IPNetworkFormatter.cs
Normal file
59
AMWD.Common/Formatters/IPNetworkFormatter.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
|
||||
namespace MessagePack.Formatters
|
||||
{
|
||||
/// <summary>
|
||||
/// Serialization of an <see cref="IPNetwork"/> to and from <see cref="MessagePack"/>.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
|
||||
public class IPNetworkFormatter : IMessagePackFormatter<IPNetwork>
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public IPNetwork Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.IsNil)
|
||||
return null;
|
||||
|
||||
byte[] bytes = options.Resolver.GetFormatterWithVerify<byte[]>().Deserialize(ref reader, options);
|
||||
return DeserializeInternal(bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Serialize(ref MessagePackWriter writer, IPNetwork value, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNil();
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] bytes = SerializeInternal(value);
|
||||
options.Resolver.GetFormatterWithVerify<byte[]>().Serialize(ref writer, bytes, options);
|
||||
}
|
||||
|
||||
internal static byte[] SerializeInternal(IPNetwork network)
|
||||
{
|
||||
// IP network prefix has a maximum of 128 bit - therefore the length can be covered with a byte.
|
||||
byte prefixLength = (byte)network.PrefixLength;
|
||||
byte[] prefixBytes = network.Prefix.GetAddressBytes();
|
||||
|
||||
byte[] bytes = new byte[prefixBytes.Length + 1];
|
||||
bytes[0] = prefixLength;
|
||||
Array.Copy(prefixBytes, 0, bytes, 1, prefixBytes.Length);
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
internal static IPNetwork DeserializeInternal(byte[] bytes)
|
||||
{
|
||||
byte prefixLength = bytes[0];
|
||||
byte[] prefixBytes = bytes.Skip(1).ToArray();
|
||||
|
||||
var prefix = new IPAddress(prefixBytes);
|
||||
return new IPNetwork(prefix, prefixLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user