RepeatedEnumAccessor.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using Google.ProtocolBuffers.Collections;
  20. using Google.ProtocolBuffers.Descriptors;
  21. namespace Google.ProtocolBuffers.FieldAccess {
  22. /// <summary>
  23. /// Accessor for a repeated enum field.
  24. /// </summary>
  25. internal sealed class RepeatedEnumAccessor<TMessage, TBuilder> : RepeatedPrimitiveAccessor<TMessage, TBuilder>
  26. where TMessage : IMessage<TMessage, TBuilder>
  27. where TBuilder : IBuilder<TMessage, TBuilder> {
  28. private readonly EnumDescriptor enumDescriptor;
  29. internal RepeatedEnumAccessor(FieldDescriptor field, string name) : base(name) {
  30. enumDescriptor = field.EnumType;
  31. }
  32. public override object GetValue(TMessage message) {
  33. List<EnumValueDescriptor> ret = new List<EnumValueDescriptor>();
  34. foreach (int rawValue in (IEnumerable) base.GetValue(message)) {
  35. ret.Add(enumDescriptor.FindValueByNumber(rawValue));
  36. }
  37. return Lists.AsReadOnly(ret);
  38. }
  39. public override object GetRepeatedValue(IMessage message, int index) {
  40. // Note: This relies on the fact that the CLR allows unboxing from an enum to
  41. // its underlying value
  42. int rawValue = (int) base.GetRepeatedValue(message, index);
  43. return enumDescriptor.FindValueByNumber(rawValue);
  44. }
  45. public override void AddRepeated(IBuilder builder, object value) {
  46. base.AddRepeated(builder, ((EnumValueDescriptor) value).Number);
  47. }
  48. public override void SetRepeated(IBuilder builder, int index, object value) {
  49. base.SetRepeated(builder, index, ((EnumValueDescriptor) value).Number);
  50. }
  51. }
  52. }