#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#endregion
using System;
using System.Reflection;
using Google.Protobuf.Compatibility;
namespace Google.Protobuf.Reflection
{
///
/// Reflection access for a oneof, allowing clear and "get case" actions.
///
public sealed class OneofAccessor
{
private readonly Func caseDelegate;
private readonly Action clearDelegate;
private OneofAccessor(OneofDescriptor descriptor, Func caseDelegate, Action clearDelegate)
{
Descriptor = descriptor;
this.caseDelegate = caseDelegate;
this.clearDelegate = clearDelegate;
}
internal static OneofAccessor ForRegularOneof(
OneofDescriptor descriptor,
PropertyInfo caseProperty,
MethodInfo clearMethod) =>
new OneofAccessor(
descriptor,
ReflectionUtil.CreateFuncIMessageInt32(caseProperty.GetGetMethod()),
ReflectionUtil.CreateActionIMessage(clearMethod));
internal static OneofAccessor ForSyntheticOneof(OneofDescriptor descriptor)
{
// Note: descriptor.Fields will be null when this method is called, because we haven't
// cross-linked yet. But by the time the delegates are called by user code, all will be
// well. (That's why we capture the descriptor itself rather than a field.)
return new OneofAccessor(descriptor,
message => descriptor.Fields[0].Accessor.HasValue(message) ? descriptor.Fields[0].FieldNumber : 0,
message => descriptor.Fields[0].Accessor.Clear(message));
}
///
/// Gets the descriptor for this oneof.
///
///
/// The descriptor of the oneof.
///
public OneofDescriptor Descriptor { get; }
///
/// Clears the oneof in the specified message.
///
public void Clear(IMessage message) => clearDelegate(message);
///
/// Indicates which field in the oneof is set for specified message
///
public FieldDescriptor GetCaseFieldDescriptor(IMessage message)
{
int fieldNumber = caseDelegate(message);
return fieldNumber > 0
? Descriptor.ContainingType.FindFieldByNumber(fieldNumber)
: null;
}
}
}