• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 package com.google.protobuf;
32 
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.Map;
36 
37 /**
38  * Equivalent to {@link ExtensionRegistry} but supports only "lite" types.
39  *
40  * <p>If all of your types are lite types, then you only need to use {@code ExtensionRegistryLite}.
41  * Similarly, if all your types are regular types, then you only need {@link ExtensionRegistry}.
42  * Typically it does not make sense to mix the two, since if you have any regular types in your
43  * program, you then require the full runtime and lose all the benefits of the lite runtime, so you
44  * might as well make all your types be regular types. However, in some cases (e.g. when depending
45  * on multiple third-party libraries where one uses lite types and one uses regular), you may find
46  * yourself wanting to mix the two. In this case things get more complicated.
47  *
48  * <p>There are three factors to consider: Whether the type being extended is lite, whether the
49  * embedded type (in the case of a message-typed extension) is lite, and whether the extension
50  * itself is lite. Since all three are declared in different files, they could all be different.
51  * Here are all the combinations and which type of registry to use:
52  *
53  * <pre>
54  *   Extended type     Inner type    Extension         Use registry
55  *   =======================================================================
56  *   lite              lite          lite              ExtensionRegistryLite
57  *   lite              regular       lite              ExtensionRegistry
58  *   regular           regular       regular           ExtensionRegistry
59  *   all other combinations                            not supported
60  * </pre>
61  *
62  * <p>Note that just as regular types are not allowed to contain lite-type fields, they are also not
63  * allowed to contain lite-type extensions. This is because regular types must be fully accessible
64  * via reflection, which in turn means that all the inner messages must also support reflection. On
65  * the other hand, since regular types implement the entire lite interface, there is no problem with
66  * embedding regular types inside lite types.
67  *
68  * @author kenton@google.com Kenton Varda
69  */
70 public class ExtensionRegistryLite {
71 
72   // Set true to enable lazy parsing feature for MessageSet.
73   //
74   // TODO(xiangl): Now we use a global flag to control whether enable lazy
75   // parsing feature for MessageSet, which may be too crude for some
76   // applications. Need to support this feature on smaller granularity.
77   private static volatile boolean eagerlyParseMessageSets = false;
78 
79   // short circuit the ExtensionRegistryFactory via assumevalues trickery
80   @SuppressWarnings("JavaOptionalSuggestions")
81   private static boolean doFullRuntimeInheritanceCheck = true;
82 
83   // Visible for testing.
84   static final String EXTENSION_CLASS_NAME = "com.google.protobuf.Extension";
85 
86   /* @Nullable */
resolveExtensionClass()87   static Class<?> resolveExtensionClass() {
88     try {
89       return Class.forName(EXTENSION_CLASS_NAME);
90     } catch (ClassNotFoundException e) {
91       // See comment in ExtensionRegistryFactory on the potential expense of this.
92       return null;
93     }
94   }
95 
96   /* @Nullable */
97   private static final Class<?> extensionClass = resolveExtensionClass();
98 
isEagerlyParseMessageSets()99   public static boolean isEagerlyParseMessageSets() {
100     return eagerlyParseMessageSets;
101   }
102 
setEagerlyParseMessageSets(boolean isEagerlyParse)103   public static void setEagerlyParseMessageSets(boolean isEagerlyParse) {
104     eagerlyParseMessageSets = isEagerlyParse;
105   }
106 
107   /**
108    * Construct a new, empty instance.
109    *
110    * <p>This may be an {@code ExtensionRegistry} if the full (non-Lite) proto libraries are
111    * available.
112    */
newInstance()113   public static ExtensionRegistryLite newInstance() {
114     return doFullRuntimeInheritanceCheck
115         ? ExtensionRegistryFactory.create()
116         : new ExtensionRegistryLite();
117   }
118 
119   private static volatile ExtensionRegistryLite emptyRegistry;
120 
121   /**
122    * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or {@code
123    * ExtensionRegistry} (if the full (non-Lite) proto libraries are available).
124    */
getEmptyRegistry()125   public static ExtensionRegistryLite getEmptyRegistry() {
126     ExtensionRegistryLite result = emptyRegistry;
127     if (result == null) {
128       synchronized (ExtensionRegistryLite.class) {
129         result = emptyRegistry;
130         if (result == null) {
131           result =
132               emptyRegistry =
133                   doFullRuntimeInheritanceCheck
134                       ? ExtensionRegistryFactory.createEmpty()
135                       : EMPTY_REGISTRY_LITE;
136         }
137       }
138     }
139     return result;
140   }
141 
142 
143   /** Returns an unmodifiable view of the registry. */
getUnmodifiable()144   public ExtensionRegistryLite getUnmodifiable() {
145     return new ExtensionRegistryLite(this);
146   }
147 
148   /**
149    * Find an extension by containing type and field number.
150    *
151    * @return Information about the extension if found, or {@code null} otherwise.
152    */
153   @SuppressWarnings("unchecked")
154   public <ContainingType extends MessageLite>
findLiteExtensionByNumber( final ContainingType containingTypeDefaultInstance, final int fieldNumber)155       GeneratedMessageLite.GeneratedExtension<ContainingType, ?> findLiteExtensionByNumber(
156           final ContainingType containingTypeDefaultInstance, final int fieldNumber) {
157     return (GeneratedMessageLite.GeneratedExtension<ContainingType, ?>)
158         extensionsByNumber.get(new ObjectIntPair(containingTypeDefaultInstance, fieldNumber));
159   }
160 
161   /** Add an extension from a lite generated file to the registry. */
add(final GeneratedMessageLite.GeneratedExtension<?, ?> extension)162   public final void add(final GeneratedMessageLite.GeneratedExtension<?, ?> extension) {
163     extensionsByNumber.put(
164         new ObjectIntPair(extension.getContainingTypeDefaultInstance(), extension.getNumber()),
165         extension);
166   }
167 
168   /**
169    * Add an extension from a lite generated file to the registry only if it is a non-lite extension
170    * i.e. {@link GeneratedMessageLite.GeneratedExtension}.
171    */
add(ExtensionLite<?, ?> extension)172   public final void add(ExtensionLite<?, ?> extension) {
173     if (GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(extension.getClass())) {
174       add((GeneratedMessageLite.GeneratedExtension<?, ?>) extension);
175     }
176     if (doFullRuntimeInheritanceCheck && ExtensionRegistryFactory.isFullRegistry(this)) {
177       try {
178         this.getClass().getMethod("add", extensionClass).invoke(this, extension);
179       } catch (Exception e) {
180         throw new IllegalArgumentException(
181             String.format("Could not invoke ExtensionRegistry#add for %s", extension), e);
182       }
183     }
184   }
185 
186   // =================================================================
187   // Private stuff.
188 
189   // Constructors are package-private so that ExtensionRegistry can subclass
190   // this.
191 
ExtensionRegistryLite()192   ExtensionRegistryLite() {
193     this.extensionsByNumber =
194         new HashMap<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>();
195   }
196 
197   static final ExtensionRegistryLite EMPTY_REGISTRY_LITE = new ExtensionRegistryLite(true);
198 
ExtensionRegistryLite(ExtensionRegistryLite other)199   ExtensionRegistryLite(ExtensionRegistryLite other) {
200     if (other == EMPTY_REGISTRY_LITE) {
201       this.extensionsByNumber = Collections.emptyMap();
202     } else {
203       this.extensionsByNumber = Collections.unmodifiableMap(other.extensionsByNumber);
204     }
205   }
206 
207   private final Map<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>
208       extensionsByNumber;
209 
ExtensionRegistryLite(boolean empty)210   ExtensionRegistryLite(boolean empty) {
211     this.extensionsByNumber = Collections.emptyMap();
212   }
213 
214   /** A (Object, int) pair, used as a map key. */
215   private static final class ObjectIntPair {
216     private final Object object;
217     private final int number;
218 
ObjectIntPair(final Object object, final int number)219     ObjectIntPair(final Object object, final int number) {
220       this.object = object;
221       this.number = number;
222     }
223 
224     @Override
hashCode()225     public int hashCode() {
226       return System.identityHashCode(object) * ((1 << 16) - 1) + number;
227     }
228 
229     @Override
equals(final Object obj)230     public boolean equals(final Object obj) {
231       if (!(obj instanceof ObjectIntPair)) {
232         return false;
233       }
234       final ObjectIntPair other = (ObjectIntPair) obj;
235       return object == other.object && number == other.number;
236     }
237   }
238 }
239