• 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  * <p>
40  * If all of your types are lite types, then you only need to use
41  * {@code ExtensionRegistryLite}.  Similarly, if all your types are regular
42  * types, then you only need {@link ExtensionRegistry}.  Typically it does not
43  * make sense to mix the two, since if you have any regular types in your
44  * program, you then require the full runtime and lose all the benefits of
45  * the lite runtime, so you might as well make all your types be regular types.
46  * However, in some cases (e.g. when depending on multiple third-party libraries
47  * where one uses lite types and one uses regular), you may find yourself
48  * wanting to mix the two.  In this case things get more complicated.
49  * <p>
50  * There are three factors to consider:  Whether the type being extended is
51  * lite, whether the embedded type (in the case of a message-typed extension)
52  * is lite, and whether the extension itself is lite.  Since all three are
53  * declared in different files, they could all be different.  Here are all
54  * the combinations and which type of registry to use:
55  * <pre>
56  *   Extended type     Inner type    Extension         Use registry
57  *   =======================================================================
58  *   lite              lite          lite              ExtensionRegistryLite
59  *   lite              regular       lite              ExtensionRegistry
60  *   regular           regular       regular           ExtensionRegistry
61  *   all other combinations                            not supported
62  * </pre>
63  * <p>
64  * Note that just as regular types are not allowed to contain lite-type fields,
65  * they are also not allowed to contain lite-type extensions.  This is because
66  * regular types must be fully accessible via reflection, which in turn means
67  * that all the inner messages must also support reflection.  On the other hand,
68  * since regular types implement the entire lite interface, there is no problem
69  * with embedding regular types inside lite types.
70  *
71  * @author kenton@google.com Kenton Varda
72  */
73 public class ExtensionRegistryLite {
74 
75   // Set true to enable lazy parsing feature for MessageSet.
76   //
77   // TODO(xiangl): Now we use a global flag to control whether enable lazy
78   // parsing feature for MessageSet, which may be too crude for some
79   // applications. Need to support this feature on smaller granularity.
80   private static volatile boolean eagerlyParseMessageSets = false;
81 
82   // Visible for testing.
83   static final String EXTENSION_CLASS_NAME = "com.google.protobuf.Extension";
84 
85   /* @Nullable */
resolveExtensionClass()86   static Class<?> resolveExtensionClass() {
87     try {
88       return Class.forName(EXTENSION_CLASS_NAME);
89     } catch (ClassNotFoundException e) {
90       // See comment in ExtensionRegistryFactory on the potential expense of this.
91       return null;
92     }
93   }
94 
95   /* @Nullable */
96   private static final Class<?> extensionClass = resolveExtensionClass();
97 
isEagerlyParseMessageSets()98   public static boolean isEagerlyParseMessageSets() {
99     return eagerlyParseMessageSets;
100   }
101 
setEagerlyParseMessageSets(boolean isEagerlyParse)102   public static void setEagerlyParseMessageSets(boolean isEagerlyParse) {
103     eagerlyParseMessageSets = isEagerlyParse;
104   }
105 
106   /**
107    * Construct a new, empty instance.
108    *
109    * <p>
110    * This may be an {@code ExtensionRegistry} if the full (non-Lite) proto libraries are available.
111    */
newInstance()112   public static ExtensionRegistryLite newInstance() {
113     return ExtensionRegistryFactory.create();
114   }
115 
116   /**
117    * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or
118    * {@code ExtensionRegistry} (if the full (non-Lite) proto libraries are available).
119    */
getEmptyRegistry()120   public static ExtensionRegistryLite getEmptyRegistry() {
121     return ExtensionRegistryFactory.createEmpty();
122   }
123 
124   /** Returns an unmodifiable view of the registry. */
getUnmodifiable()125   public ExtensionRegistryLite getUnmodifiable() {
126     return new ExtensionRegistryLite(this);
127   }
128 
129   /**
130    * Find an extension by containing type and field number.
131    *
132    * @return Information about the extension if found, or {@code null}
133    *         otherwise.
134    */
135   @SuppressWarnings("unchecked")
136   public <ContainingType extends MessageLite>
137       GeneratedMessageLite.GeneratedExtension<ContainingType, ?>
findLiteExtensionByNumber( final ContainingType containingTypeDefaultInstance, final int fieldNumber)138         findLiteExtensionByNumber(
139           final ContainingType containingTypeDefaultInstance,
140           final int fieldNumber) {
141     return (GeneratedMessageLite.GeneratedExtension<ContainingType, ?>)
142       extensionsByNumber.get(
143         new ObjectIntPair(containingTypeDefaultInstance, fieldNumber));
144   }
145 
146   /** Add an extension from a lite generated file to the registry. */
add( final GeneratedMessageLite.GeneratedExtension<?, ?> extension)147   public final void add(
148       final GeneratedMessageLite.GeneratedExtension<?, ?> extension) {
149     extensionsByNumber.put(
150       new ObjectIntPair(extension.getContainingTypeDefaultInstance(),
151                         extension.getNumber()),
152       extension);
153   }
154 
155   /**
156    * Add an extension from a lite generated file to the registry only if it is
157    * a non-lite extension i.e. {@link GeneratedMessageLite.GeneratedExtension}. */
add(ExtensionLite<?, ?> extension)158   public final void add(ExtensionLite<?, ?> extension) {
159     if (GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(extension.getClass())) {
160       add((GeneratedMessageLite.GeneratedExtension<?, ?>) extension);
161     }
162     if (ExtensionRegistryFactory.isFullRegistry(this)) {
163       try {
164         this.getClass().getMethod("add", extensionClass).invoke(this, extension);
165       } catch (Exception e) {
166         throw new IllegalArgumentException(
167             String.format("Could not invoke ExtensionRegistry#add for %s", extension), e);
168       }
169     }
170   }
171 
172   // =================================================================
173   // Private stuff.
174 
175   // Constructors are package-private so that ExtensionRegistry can subclass
176   // this.
177 
ExtensionRegistryLite()178   ExtensionRegistryLite() {
179     this.extensionsByNumber =
180         new HashMap<ObjectIntPair,
181                     GeneratedMessageLite.GeneratedExtension<?, ?>>();
182   }
183   static final ExtensionRegistryLite EMPTY_REGISTRY_LITE =
184       new ExtensionRegistryLite(true);
185 
ExtensionRegistryLite(ExtensionRegistryLite other)186   ExtensionRegistryLite(ExtensionRegistryLite other) {
187     if (other == EMPTY_REGISTRY_LITE) {
188       this.extensionsByNumber = Collections.emptyMap();
189     } else {
190       this.extensionsByNumber =
191         Collections.unmodifiableMap(other.extensionsByNumber);
192     }
193   }
194 
195   private final Map<ObjectIntPair,
196                     GeneratedMessageLite.GeneratedExtension<?, ?>>
197       extensionsByNumber;
198 
ExtensionRegistryLite(boolean empty)199   ExtensionRegistryLite(boolean empty) {
200     this.extensionsByNumber = Collections.emptyMap();
201   }
202 
203   /** A (Object, int) pair, used as a map key. */
204   private static final class ObjectIntPair {
205     private final Object object;
206     private final int number;
207 
ObjectIntPair(final Object object, final int number)208     ObjectIntPair(final Object object, final int number) {
209       this.object = object;
210       this.number = number;
211     }
212 
213     @Override
hashCode()214     public int hashCode() {
215       return System.identityHashCode(object) * ((1 << 16) - 1) + number;
216     }
217     @Override
equals(final Object obj)218     public boolean equals(final Object obj) {
219       if (!(obj instanceof ObjectIntPair)) {
220         return false;
221       }
222       final ObjectIntPair other = (ObjectIntPair)obj;
223       return object == other.object && number == other.number;
224     }
225   }
226 }
227