Created
June 15, 2022 09:04
-
-
Save mgravell/481614450935d903ea3a821f85a0c735 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using ProtoBuf; | |
using ProtoBuf.Serializers; | |
using System; | |
using System.IO; | |
static class P | |
{ | |
static void Main() | |
{ | |
var obj = new SomeRegularPoco | |
{ | |
Whatever = new BlobLike(new byte[] { 1, 2, 3 }) | |
}; | |
using var ms = new MemoryStream(); | |
Serializer.Serialize(ms, obj); | |
Console.WriteLine(BitConverter.ToString(ms.ToArray())); | |
// ^^^ 0A-03-01-02-03 | |
// i.e. "field 1, string; length 3; payload 1,2,3" - no extra layer | |
ms.Position = 0; | |
var clone = Serializer.Deserialize<SomeRegularPoco>(ms); | |
Console.WriteLine(clone.Whatever.Payload.Length); // 3 | |
} | |
} | |
[ProtoContract] | |
public class SomeRegularPoco | |
{ | |
[ProtoMember(1)] | |
public BlobLike Whatever { get; set; } | |
} | |
[ProtoContract(Serializer = typeof(BlobLikeSerializer), Name = "bytes")] | |
public readonly struct BlobLike | |
{ | |
public ReadOnlyMemory<byte> Payload { get; } | |
public BlobLike(ReadOnlyMemory<byte> payload) | |
=> Payload = payload; | |
public class BlobLikeSerializer : ISerializer<BlobLike> | |
{ | |
SerializerFeatures ISerializer<BlobLike>.Features => | |
SerializerFeatures.CategoryScalar | SerializerFeatures.WireTypeString; | |
BlobLike ISerializer<BlobLike>.Read(ref ProtoReader.State state, BlobLike value) | |
=> new BlobLike(state.AppendBytes(value.Payload)); | |
void ISerializer<BlobLike>.Write(ref ProtoWriter.State state, BlobLike value) | |
=> state.WriteBytes(value.Payload); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment