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