|
| 1 | +using System.Text; |
| 2 | + |
| 3 | +namespace Ydb.Sdk.Services.Topic; |
| 4 | + |
| 5 | +public interface ISerializer<in TValue> |
| 6 | +{ |
| 7 | + public byte[] Serialize(TValue data); |
| 8 | +} |
| 9 | + |
| 10 | +public static class Serializers |
| 11 | +{ |
| 12 | + /// <summary>String (UTF8) serializer.</summary> |
| 13 | + public static readonly ISerializer<string> Utf8 = new Utf8Serializer(); |
| 14 | + |
| 15 | + /// <summary> |
| 16 | + /// System.Int64 (big endian, network byte order) serializer. |
| 17 | + /// </summary> |
| 18 | + public static readonly ISerializer<long> Int64 = new Int64Serializer(); |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// System.Int32 (big endian, network byte order) serializer. |
| 22 | + /// </summary> |
| 23 | + public static readonly ISerializer<int> Int32 = new Int32Serializer(); |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// System.Byte[] (nullable) serializer.</summary> |
| 27 | + /// <remarks>Byte order is original order.</remarks> |
| 28 | + public static readonly ISerializer<byte[]> ByteArray = new ByteArraySerializer(); |
| 29 | + |
| 30 | + internal static readonly Dictionary<System.Type, object> DefaultSerializers = new() |
| 31 | + { |
| 32 | + { typeof(int), Int32 }, |
| 33 | + { typeof(long), Int64 }, |
| 34 | + { typeof(string), Utf8 }, |
| 35 | + { typeof(byte[]), ByteArray } |
| 36 | + }; |
| 37 | + |
| 38 | + private class Utf8Serializer : ISerializer<string> |
| 39 | + { |
| 40 | + public byte[] Serialize(string data) |
| 41 | + { |
| 42 | + return Encoding.UTF8.GetBytes(data); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private class Int64Serializer : ISerializer<long> |
| 47 | + { |
| 48 | + public byte[] Serialize(long data) |
| 49 | + { |
| 50 | + return new[] |
| 51 | + { |
| 52 | + (byte)(data >> 56), |
| 53 | + (byte)(data >> 48), |
| 54 | + (byte)(data >> 40), |
| 55 | + (byte)(data >> 32), |
| 56 | + (byte)(data >> 24), |
| 57 | + (byte)(data >> 16), |
| 58 | + (byte)(data >> 8), |
| 59 | + (byte)data |
| 60 | + }; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private class Int32Serializer : ISerializer<int> |
| 65 | + { |
| 66 | + public byte[] Serialize(int data) |
| 67 | + { |
| 68 | + return new[] |
| 69 | + { |
| 70 | + (byte)(data >> 24), |
| 71 | + (byte)(data >> 16), |
| 72 | + (byte)(data >> 8), |
| 73 | + (byte)data |
| 74 | + }; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + private class ByteArraySerializer : ISerializer<byte[]> |
| 79 | + { |
| 80 | + public byte[] Serialize(byte[] data) |
| 81 | + { |
| 82 | + return data; |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments