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