Add client-side support for proto3 config

This commit is contained in:
John Colvin committed 2022-04-19 11:42:42 -04:00
1 parent b00b12bed2
commit aa254142e8
2 files changed
+35 -6

No files matched your search

@@ -11,6 +11,12 @@ namespace Spark.Core.Protobuf {
using System.IO;
public static class ProtobufSerializationHelper {
public static T deserialize_proto3<T>(byte[] bytes) where T : IMessage, new() {
var rv = new T();
rv.MergeFrom(bytes);
return rv;
}
public static bool try_deserialize<T>(Stream stream, [NotNullWhen(true)] out T? result, bool log_exception = true) {
try {
result = deserialize<T>(stream);
@@ -41,6 +47,20 @@ namespace Spark.Core.Protobuf {
return try_deserialize(ms, out result);
}
public static bool try_deserialize_proto3<T>(
byte[] bytes, [NotNullWhen(true)] out T? result, bool log_exception = true) where T : IMessage, new() {
try {
result = deserialize_proto3<T>(bytes);
return true;
} catch (Exception ex) {
if (log_exception) {
Log.Gen.warn($"Failed to deserialize protobuf of type {typeof(T)}: {ex}");
}
}
result = default;
return false;
}
public static void serialize<T>(Stream stream, T t) =>
Serializer.SerializeWithLengthPrefix(stream, t, PrefixStyle.Fixed32);
+15 -6
View File
@@ -2,7 +2,7 @@
namespace mbts.config {
using bts;
using Spark.Core.Protobuf;
using Google.Protobuf;
using System;
using System.Diagnostics.Contracts;
@@ -34,11 +34,20 @@ namespace mbts.config {
using var ms = new MemoryStream(buffer);
try {
return ProtoBuf.Serializer.Deserialize<T>(ms);
return typeof(IMessage).IsAssignableFrom(typeof(T)) ? proto3_impl() : proto2_impl();
} catch (Exception ex) {
Log.assert(false, _fmt_deserialization_error(typeof(T), key, ex));
}
return new();
T proto2_impl() =>
ProtoBuf.Serializer.Deserialize<T>(ms);
T proto3_impl() {
var rv = new T();
((IMessage)rv).MergeFrom(ms);
return rv;
}
}
public static void initialize() {
@@ -75,7 +84,7 @@ namespace mbts.config {
return true;
}
[DllImport("libspark", CharSet = CharSet.Unicode)]
[DllImport("libspark")]
internal static extern void configcheck(int count, string[] args);
[Pure]
@@ -105,13 +114,13 @@ namespace mbts.config {
}
}
[DllImport("libspark", EntryPoint = "get_buffer", CharSet = CharSet.Unicode)]
[DllImport("libspark", EntryPoint = "get_buffer")]
static extern IntPtr _raw_get_buffer(string key_name, ref int length);
[DllImport("libspark", EntryPoint = "initialize_nothrow", CharSet = CharSet.Unicode)]
[DllImport("libspark", EntryPoint = "initialize_nothrow")]
static extern bool _initialize_nothrow(StringBuilder buffer, int length);
[DllImport("libspark", EntryPoint = "initialize_for_test", CharSet = CharSet.Unicode)]
[DllImport("libspark", EntryPoint = "initialize_for_test")]
static extern void _raw_initialize_for_test(string buffer);
[DllImport("libspark", EntryPoint = "reset")]