IBinaryFormattable<TSelf>
Represents an object that can be converted to and restored from the binary representation.
using System;
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace DotNext.Buffers.Binary
{
public interface IBinaryFormattable<[Nullable(1)] TSelf> where TSelf : IBinaryFormattable<TSelf>
{
int Size { get; }
void Format(Span<byte> destination);
[return: Nullable(1)]
TSelf Parse(ReadOnlySpan<byte> source);
unsafe bool TryParse(ReadOnlySpan<byte> source, [Nullable(2)] [NotNullWhen(true)] out TSelf result)
{
int size = ((TSelf*)source.Length)->Size;
if ((int) >= size) {
TSelf val = result.Parse(source);
*(TSelf*)(long)(IntPtr)(void*) = val;
return true;
}
result = default(TSelf);
return false;
}
MemoryOwner<byte> Format([Nullable(1)] TSelf value, [Nullable(2)] MemoryAllocator<byte> allocator = null)
{
MemoryOwner<byte> result = Memory.AllocateExactly<byte>(length: ((IBinaryFormattable<TSelf>)allocator).Size, allocator: (MemoryAllocator<byte>));
ref TSelf reference = ref value;
TSelf val = default(TSelf);
if (val == null) {
val = reference;
ref reference = ref val;
}
reference.Format(result.Span);
return result;
}
unsafe bool TryFormat([Nullable(1)] TSelf value, Span<byte> destination)
{
int size = ((TSelf*)destination.Length)->Size;
if ((int) >= size) {
value.Format(destination);
return true;
}
return false;
}
[return: Nullable(1)]
unsafe TSelf Parse([In] [IsReadOnly] ref ReadOnlySequence<byte> source)
{
ReadOnlySpan<byte> firstSpan = source.FirstSpan;
int size = ((TSelf*)firstSpan.Length)->Size;
if ((int) < size)
return ((IBinaryFormattable<TSelf>)).<Parse>g__ParseSlow|7_0(ref source);
ReadOnlySpan<byte> source2 = firstSpan;
return ((IBinaryFormattable<TSelf>)).Parse(source2);
}
}
}