Helper method on Any to allow an any to be unpacked more easily

We already have the TypeRegistry abstraction for JSON parsing, so it lends itself well to this.

Note that this is much more useful than it would have been before C# gained pattern matching support: it's easy to imagine a switch statement/expression using pattern matching with the result of this, with cases for a set of known message types, for example.
pull/9963/head
Jon Skeet 3 years ago committed by Jon Skeet
parent b3cbea18ea
commit c32d7ec2ab
  1. 27
      csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
  2. 20
      csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs

@ -30,8 +30,11 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.Protobuf.Reflection;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
using System.Linq;
using UnitTest.Issues.TestProtos;
namespace Google.Protobuf.WellKnownTypes
{
@ -148,10 +151,34 @@ namespace Google.Protobuf.WellKnownTypes
Assert.False(any.Is(TestOneof.Descriptor));
}
[Test]
public void IsRightType()
{
var any = Any.Pack(SampleMessages.CreateFullTestAllTypes());
Assert.True(any.Is(TestAllTypes.Descriptor));
}
[Test]
public void Unpack_TypeRegistry()
{
var messages = new IMessage[]
{
SampleMessages.CreateFullTestAllTypes(),
new TestWellKnownTypes { BoolField = true },
new MoreString { Data = { "x" } },
new MoreBytes { Data = ByteString.CopyFromUtf8("xyz") },
new ReservedNames { Descriptor_ = 10 }
};
var anyMessages = messages.Select(Any.Pack);
// The type registry handles the first four of the packed messages, but not the final one.
var registry = TypeRegistry.FromFiles(
UnittestWellKnownTypesReflection.Descriptor,
UnittestProto3Reflection.Descriptor);
var unpacked = anyMessages.Select(any => any.Unpack(registry)).ToList();
var expected = (IMessage[]) messages.Clone();
expected[4] = null;
Assert.AreEqual(expected, unpacked);
}
}
}

@ -120,6 +120,26 @@ namespace Google.Protobuf.WellKnownTypes
return true;
}
/// <summary>
/// Attempts to unpack the content of this Any message into one of the message types
/// in the given type registry, based on the type URL.
/// </summary>
/// <param name="registry">The type registry to consult for messages.</param>
/// <returns>The unpacked message, or <c>null</c> if no matching message was found.</returns>
public IMessage Unpack(TypeRegistry registry)
{
string typeName = GetTypeName(TypeUrl);
MessageDescriptor descriptor = registry.Find(typeName);
if (descriptor == null)
{
return null;
}
var message = descriptor.Parser.CreateTemplate();
message.MergeFrom(Value);
return message;
}
/// <summary>
/// Packs the specified message into an Any message using a type URL prefix of "type.googleapis.com".
/// </summary>

Loading…
Cancel
Save