ExtensionRegistryLite.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // http://github.com/jskeet/dotnet-protobufs/
  5. // Original C++/Java/Python code:
  6. // http://code.google.com/p/protobuf/
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions are
  10. // met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. // * Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following disclaimer
  16. // in the documentation and/or other materials provided with the
  17. // distribution.
  18. // * Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived from
  20. // this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #endregion
  34. using System.Collections.Generic;
  35. using System;
  36. using Google.ProtocolBuffers.Descriptors;
  37. namespace Google.ProtocolBuffers
  38. {
  39. /// <summary>
  40. /// A table of known extensions, searchable by name or field number. When
  41. /// parsing a protocol message that might have extensions, you must provide
  42. /// an <see cref="ExtensionRegistry"/> in which you have registered any extensions
  43. /// that you want to be able to parse. Otherwise, those extensions will just
  44. /// be treated like unknown fields.
  45. /// </summary>
  46. /// <example>
  47. /// For example, if you had the <c>.proto</c> file:
  48. /// <code>
  49. /// option java_class = "MyProto";
  50. ///
  51. /// message Foo {
  52. /// extensions 1000 to max;
  53. /// }
  54. ///
  55. /// extend Foo {
  56. /// optional int32 bar;
  57. /// }
  58. /// </code>
  59. ///
  60. /// Then you might write code like:
  61. ///
  62. /// <code>
  63. /// extensionRegistry registry = extensionRegistry.CreateInstance();
  64. /// registry.Add(MyProto.Bar);
  65. /// MyProto.Foo message = MyProto.Foo.ParseFrom(input, registry);
  66. /// </code>
  67. /// </example>
  68. ///
  69. /// <remarks>
  70. /// <para>You might wonder why this is necessary. Two alternatives might come to
  71. /// mind. First, you might imagine a system where generated extensions are
  72. /// automatically registered when their containing classes are loaded. This
  73. /// is a popular technique, but is bad design; among other things, it creates a
  74. /// situation where behavior can change depending on what classes happen to be
  75. /// loaded. It also introduces a security vulnerability, because an
  76. /// unprivileged class could cause its code to be called unexpectedly from a
  77. /// privileged class by registering itself as an extension of the right type.
  78. /// </para>
  79. /// <para>Another option you might consider is lazy parsing: do not parse an
  80. /// extension until it is first requested, at which point the caller must
  81. /// provide a type to use. This introduces a different set of problems. First,
  82. /// it would require a mutex lock any time an extension was accessed, which
  83. /// would be slow. Second, corrupt data would not be detected until first
  84. /// access, at which point it would be much harder to deal with it. Third, it
  85. /// could violate the expectation that message objects are immutable, since the
  86. /// type provided could be any arbitrary message class. An unprivileged user
  87. /// could take advantage of this to inject a mutable object into a message
  88. /// belonging to privileged code and create mischief.</para>
  89. /// </remarks>
  90. public sealed partial class ExtensionRegistry
  91. {
  92. class ExtensionByNameMap : Dictionary<object, Dictionary<string, IGeneratedExtensionLite>> { }
  93. class ExtensionByIdMap : Dictionary<ExtensionIntPair, IGeneratedExtensionLite> { }
  94. private static readonly ExtensionRegistry empty = new ExtensionRegistry(
  95. new ExtensionByNameMap(),
  96. new ExtensionByIdMap(),
  97. true);
  98. private readonly ExtensionByNameMap extensionsByName;
  99. private readonly ExtensionByIdMap extensionsByNumber;
  100. private readonly bool readOnly;
  101. private ExtensionRegistry(ExtensionByNameMap byName, ExtensionByIdMap byNumber, bool readOnly)
  102. {
  103. this.extensionsByName = byName;
  104. this.extensionsByNumber = byNumber;
  105. this.readOnly = readOnly;
  106. }
  107. /// <summary>
  108. /// Construct a new, empty instance.
  109. /// </summary>
  110. public static ExtensionRegistry CreateInstance()
  111. {
  112. return new ExtensionRegistry(new ExtensionByNameMap(), new ExtensionByIdMap(), false);
  113. }
  114. public ExtensionRegistry AsReadOnly()
  115. {
  116. return new ExtensionRegistry(extensionsByName, extensionsByNumber, true);
  117. }
  118. /// <summary>
  119. /// Get the unmodifiable singleton empty instance.
  120. /// </summary>
  121. public static ExtensionRegistry Empty
  122. {
  123. get { return empty; }
  124. }
  125. /// <summary>
  126. /// Finds an extension by containing type and field number.
  127. /// A null reference is returned if the extension can't be found.
  128. /// </summary>
  129. public IGeneratedExtensionLite this[IMessageLite containingType, int fieldNumber]
  130. {
  131. get
  132. {
  133. IGeneratedExtensionLite ret;
  134. extensionsByNumber.TryGetValue(new ExtensionIntPair(containingType, fieldNumber), out ret);
  135. return ret;
  136. }
  137. }
  138. public IGeneratedExtensionLite FindByName(IMessageLite defaultInstanceOfType, string fieldName)
  139. { return FindExtensionByName(defaultInstanceOfType, fieldName); }
  140. IGeneratedExtensionLite FindExtensionByName(object forwhat, string fieldName)
  141. {
  142. IGeneratedExtensionLite extension = null;
  143. Dictionary<string, IGeneratedExtensionLite> map;
  144. if (extensionsByName.TryGetValue(forwhat, out map) && map.TryGetValue(fieldName, out extension))
  145. return extension;
  146. return null;
  147. }
  148. /// <summary>
  149. /// Add an extension from a generated file to the registry.
  150. /// </summary>
  151. public void Add(IGeneratedExtensionLite extension)
  152. {
  153. if (readOnly)
  154. {
  155. throw new InvalidOperationException("Cannot add entries to a read-only extension registry");
  156. }
  157. extensionsByNumber.Add(new ExtensionIntPair(extension.ContainingType, extension.Number), extension);
  158. Dictionary<string, IGeneratedExtensionLite> map;
  159. if (!extensionsByName.TryGetValue(extension.ContainingType, out map))
  160. extensionsByName.Add(extension.ContainingType, map = new Dictionary<string, IGeneratedExtensionLite>());
  161. map[extension.Descriptor.Name] = extension;
  162. map[extension.Descriptor.FullName] = extension;
  163. }
  164. /// <summary>
  165. /// Nested type just used to represent a pair of MessageDescriptor and int, as
  166. /// the key into the "by number" map.
  167. /// </summary>
  168. private struct ExtensionIntPair : IEquatable<ExtensionIntPair>
  169. {
  170. private readonly object msgType;
  171. private readonly int number;
  172. internal ExtensionIntPair(object msgType, int number)
  173. {
  174. this.msgType = msgType;
  175. this.number = number;
  176. }
  177. public override int GetHashCode()
  178. {
  179. return msgType.GetHashCode() * ((1 << 16) - 1) + number;
  180. }
  181. public override bool Equals(object obj)
  182. {
  183. if (!(obj is ExtensionIntPair))
  184. {
  185. return false;
  186. }
  187. return Equals((ExtensionIntPair)obj);
  188. }
  189. public bool Equals(ExtensionIntPair other)
  190. {
  191. return msgType.Equals(other.msgType) && number == other.number;
  192. }
  193. }
  194. }
  195. }