• 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   private static class ExtensionClassHolder {
87     /* @Nullable */
88     static final Class<?> INSTANCE = resolveExtensionClass();
89 
90     /* @Nullable */
resolveExtensionClass()91     static Class<?> resolveExtensionClass() {
92       try {
93         return Class.forName(EXTENSION_CLASS_NAME);
94       } catch (ClassNotFoundException e) {
95         // See comment in ExtensionRegistryFactory on the potential expense of this.
96         return null;
97       }
98     }
99   }
100 
isEagerlyParseMessageSets()101   public static boolean isEagerlyParseMessageSets() {
102     return eagerlyParseMessageSets;
103   }
104 
setEagerlyParseMessageSets(boolean isEagerlyParse)105   public static void setEagerlyParseMessageSets(boolean isEagerlyParse) {
106     eagerlyParseMessageSets = isEagerlyParse;
107   }
108 
109   /**
110    * Construct a new, empty instance.
111    *
112    * <p>This may be an {@code ExtensionRegistry} if the full (non-Lite) proto libraries are
113    * available.
114    */
newInstance()115   public static ExtensionRegistryLite newInstance() {
116     return doFullRuntimeInheritanceCheck
117         ? ExtensionRegistryFactory.create()
118         : new ExtensionRegistryLite();
119   }
120 
121   private static volatile ExtensionRegistryLite emptyRegistry;
122 
123   /**
124    * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or {@code
125    * ExtensionRegistry} (if the full (non-Lite) proto libraries are available).
126    */
getEmptyRegistry()127   public static ExtensionRegistryLite getEmptyRegistry() {
128     ExtensionRegistryLite result = emptyRegistry;
129     if (result == null) {
130       synchronized (ExtensionRegistryLite.class) {
131         result = emptyRegistry;
132         if (result == null) {
133           result =
134               emptyRegistry =
135                   doFullRuntimeInheritanceCheck
136                       ? ExtensionRegistryFactory.createEmpty()
137                       : EMPTY_REGISTRY_LITE;
138         }
139       }
140     }
141     return result;
142   }
143 
144 
145   /** Returns an unmodifiable view of the registry. */
getUnmodifiable()146   public ExtensionRegistryLite getUnmodifiable() {
147     return new ExtensionRegistryLite(this);
148   }
149 
150   /**
151    * Find an extension by containing type and field number.
152    *
153    * @return Information about the extension if found, or {@code null} otherwise.
154    */
155   @SuppressWarnings("unchecked")
156   public <ContainingType extends MessageLite>
findLiteExtensionByNumber( final ContainingType containingTypeDefaultInstance, final int fieldNumber)157       GeneratedMessageLite.GeneratedExtension<ContainingType, ?> findLiteExtensionByNumber(
158           final ContainingType containingTypeDefaultInstance, final int fieldNumber) {
159     return (GeneratedMessageLite.GeneratedExtension<ContainingType, ?>)
160         extensionsByNumber.get(new ObjectIntPair(containingTypeDefaultInstance, fieldNumber));
161   }
162 
163   /** Add an extension from a lite generated file to the registry. */
add(final GeneratedMessageLite.GeneratedExtension<?, ?> extension)164   public final void add(final GeneratedMessageLite.GeneratedExtension<?, ?> extension) {
165     extensionsByNumber.put(
166         new ObjectIntPair(extension.getContainingTypeDefaultInstance(), extension.getNumber()),
167         extension);
168   }
169 
170   /**
171    * Add an extension from a lite generated file to the registry only if it is a non-lite extension
172    * i.e. {@link GeneratedMessageLite.GeneratedExtension}.
173    */
add(ExtensionLite<?, ?> extension)174   public final void add(ExtensionLite<?, ?> extension) {
175     if (GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(extension.getClass())) {
176       add((GeneratedMessageLite.GeneratedExtension<?, ?>) extension);
177     }
178     if (doFullRuntimeInheritanceCheck && ExtensionRegistryFactory.isFullRegistry(this)) {
179       try {
180         this.getClass().getMethod("add", ExtensionClassHolder.INSTANCE).invoke(this, extension);
181       } catch (Exception e) {
182         throw new IllegalArgumentException(
183             String.format("Could not invoke ExtensionRegistry#add for %s", extension), e);
184       }
185     }
186   }
187 
188   // =================================================================
189   // Private stuff.
190 
191   // Constructors are package-private so that ExtensionRegistry can subclass
192   // this.
193 
ExtensionRegistryLite()194   ExtensionRegistryLite() {
195     this.extensionsByNumber =
196         new HashMap<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>();
197   }
198 
199   static final ExtensionRegistryLite EMPTY_REGISTRY_LITE = new ExtensionRegistryLite(true);
200 
ExtensionRegistryLite(ExtensionRegistryLite other)201   ExtensionRegistryLite(ExtensionRegistryLite other) {
202     if (other == EMPTY_REGISTRY_LITE) {
203       this.extensionsByNumber = Collections.emptyMap();
204     } else {
205       this.extensionsByNumber = Collections.unmodifiableMap(other.extensionsByNumber);
206     }
207   }
208 
209   private final Map<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>
210       extensionsByNumber;
211 
ExtensionRegistryLite(boolean empty)212   ExtensionRegistryLite(boolean empty) {
213     this.extensionsByNumber = Collections.emptyMap();
214   }
215 
216   /** A (Object, int) pair, used as a map key. */
217   private static final class ObjectIntPair {
218     private final Object object;
219     private final int number;
220 
ObjectIntPair(final Object object, final int number)221     ObjectIntPair(final Object object, final int number) {
222       this.object = object;
223       this.number = number;
224     }
225 
226     @Override
hashCode()227     public int hashCode() {
228       return System.identityHashCode(object) * ((1 << 16) - 1) + number;
229     }
230 
231     @Override
equals(final Object obj)232     public boolean equals(final Object obj) {
233       if (!(obj instanceof ObjectIntPair)) {
234         return false;
235       }
236       final ObjectIntPair other = (ObjectIntPair) obj;
237       return object == other.object && number == other.number;
238     }
239   }
240 }
241