-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenedGeneratedMessageV3.java
More file actions
4302 lines (3794 loc) · 152 KB
/
FlattenedGeneratedMessageV3.java
File metadata and controls
4302 lines (3794 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
import com.google.protobuf.Internal.BooleanList;
import com.google.protobuf.Internal.DoubleList;
import com.google.protobuf.Internal.FloatList;
import com.google.protobuf.Internal.IntList;
import com.google.protobuf.Internal.LongList;
import com.google.protobuf.Internal.ProtobufList;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static com.google.protobuf.Internal.checkNotNull;
/**
* All generated protocol message classes extend this class. This class implements most of the
* Message and Builder interfaces using Java reflection. Users can ignore this class and pretend
* that generated messages implement the Message interface directly.
*
* @author kenton@google.com Kenton Varda
*/
abstract class FlattenedGeneratedMessageV3 extends AbstractMessage implements Serializable {
private static final long serialVersionUID = 1L;
/**
* For testing. Allows a test to disable the optimization that avoids using field builders for
* nested messages until they are requested. By disabling this optimization, existing tests can be
* reused to test the field builders.
*/
protected static boolean alwaysUseFieldBuilders = false;
/**
* For use by generated code only.
*
* <p>TODO: mark this private and final (breaking change)
*/
protected UnknownFieldSet unknownFields;
protected FlattenedGeneratedMessageV3() {
unknownFields = UnknownFieldSet.getDefaultInstance();
}
protected FlattenedGeneratedMessageV3(Builder<?> builder) {
unknownFields = builder.getUnknownFields();
}
protected int memoizedHashCode = 0;
public ByteString toByteString() {
try {
final ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize());
writeTo(out.getCodedOutput());
return out.build();
} catch (IOException e) {
throw new RuntimeException(getSerializingExceptionMessage("ByteString"), e);
}
}
public byte[] toByteArray() {
try {
final byte[] result = new byte[getSerializedSize()];
final CodedOutputStream output = CodedOutputStream.newInstance(result);
writeTo(output);
output.checkNoSpaceLeft();
return result;
} catch (IOException e) {
throw new RuntimeException(getSerializingExceptionMessage("byte array"), e);
}
}
public void writeTo(final OutputStream output) throws IOException {
final int bufferSize = CodedOutputStream.computePreferredBufferSize(getSerializedSize());
final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize);
writeTo(codedOutput);
codedOutput.flush();
}
public void writeDelimitedTo(final OutputStream output) throws IOException {
final int serialized = getSerializedSize();
final int bufferSize =
CodedOutputStream.computePreferredBufferSize(
CodedOutputStream.computeUInt32SizeNoTag(serialized) + serialized);
final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize);
codedOutput.writeUInt32NoTag(serialized);
writeTo(codedOutput);
codedOutput.flush();
}
int getSerializedSize(
Schema schema) {
int memoizedSerializedSize = getMemoizedSerializedSize();
if (memoizedSerializedSize == -1) {
memoizedSerializedSize = schema.getSerializedSize(this);
setMemoizedSerializedSize(memoizedSerializedSize);
}
return memoizedSerializedSize;
}
private String getSerializingExceptionMessage(String target) {
return "Serializing "
+ getClass().getName()
+ " to a "
+ target
+ " threw an IOException (should never happen).";
}
protected static void checkByteStringIsUtf8(ByteString byteString)
throws IllegalArgumentException {
if (!byteString.isValidUtf8()) {
throw new IllegalArgumentException("Byte string is not UTF-8.");
}
}
/** Interface for an enum which signifies which field in a {@code oneof} was specified. */
protected interface InternalOneOfEnum {
/**
* Retrieves the field number of the field which was set in this {@code oneof}, or {@code 0} if
* none were.
*/
int getNumber();
}
/**
* Interface for the parent of a Builder that allows the builder to communicate invalidations back
* to the parent for use when using nested builders.
*/
protected interface BuilderParent extends Message.BuilderParent{
/**
* A builder becomes dirty whenever a field is modified -- including fields in nested builders
* -- and becomes clean when build() is called. Thus, when a builder becomes dirty, all its
* parents become dirty as well, and when it becomes clean, all its children become clean. The
* dirtiness state is used to invalidate certain cached values.
*
* <p>To this end, a builder calls markDirty() on its parent whenever it transitions from clean
* to dirty. The parent must propagate this call to its own parent, unless it was already dirty,
* in which case the grandparent must necessarily already be dirty as well. The parent can only
* transition back to "clean" after calling build() on all children.
*/
void markDirty();
}
public List<String> findInitializationErrors() {
return MessageReflection.findMissingFields(this);
}
public String getInitializationErrorString() {
return MessageReflection.delimitWithCommas(findInitializationErrors());
}
protected int memoizedSize = -1;
int getMemoizedSerializedSize() {
return memoizedSize;
}
void setMemoizedSerializedSize(int size) {
memoizedSize = size;
}
@Override
public boolean equals(final Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Message)) {
return false;
}
final Message otherMessage = (Message) other;
if (getDescriptorForType() != otherMessage.getDescriptorForType()) {
return false;
}
return compareFields(getAllFields(), otherMessage.getAllFields())
&& getUnknownFields().equals(otherMessage.getUnknownFields());
}
@Override
public int hashCode() {
int hash = memoizedHashCode;
if (hash == 0) {
hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
hash = hashFields(hash, getAllFields());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
}
return hash;
}
private static ByteString toByteString(Object value) {
if (value instanceof byte[]) {
return ByteString.copyFrom((byte[]) value);
} else {
return (ByteString) value;
}
}
/**
* Compares two bytes fields. The parameters must be either a byte array or a ByteString object.
* They can be of different type though.
*/
private static boolean compareBytes(Object a, Object b) {
if (a instanceof byte[] && b instanceof byte[]) {
return Arrays.equals((byte[]) a, (byte[]) b);
}
return toByteString(a).equals(toByteString(b));
}
/** Converts a list of MapEntry messages into a Map used for equals() and hashCode(). */
@SuppressWarnings({"rawtypes", "unchecked"})
private static Map convertMapEntryListToMap(List list) {
if (list.isEmpty()) {
return Collections.emptyMap();
}
Map result = new HashMap<>();
Iterator iterator = list.iterator();
Message entry = (Message) iterator.next();
Descriptor descriptor = entry.getDescriptorForType();
FieldDescriptor key = descriptor.findFieldByName("key");
FieldDescriptor value = descriptor.findFieldByName("value");
Object fieldValue = entry.getField(value);
if (fieldValue instanceof EnumValueDescriptor) {
fieldValue = ((EnumValueDescriptor) fieldValue).getNumber();
}
result.put(entry.getField(key), fieldValue);
while (iterator.hasNext()) {
entry = (Message) iterator.next();
fieldValue = entry.getField(value);
if (fieldValue instanceof EnumValueDescriptor) {
fieldValue = ((EnumValueDescriptor) fieldValue).getNumber();
}
result.put(entry.getField(key), fieldValue);
}
return result;
}
/** Compares two map fields. The parameters must be a list of MapEntry messages. */
@SuppressWarnings({"rawtypes", "unchecked"})
private static boolean compareMapField(Object a, Object b) {
Map ma = convertMapEntryListToMap((List) a);
Map mb = convertMapEntryListToMap((List) b);
return MapFieldLite.equals(ma, mb);
}
/**
* Compares two sets of fields. This method is used to implement {@link
* AbstractMessage#equals(Object)} and {@link AbstractMutableMessage#equals(Object)}. It takes
* special care of bytes fields because immutable messages and mutable messages use different Java
* type to represent a bytes field and this method should be able to compare immutable messages,
* mutable messages and also an immutable message to a mutable message.
*/
static boolean compareFields(Map<FieldDescriptor, Object> a, Map<FieldDescriptor, Object> b) {
if (a.size() != b.size()) {
return false;
}
for (FieldDescriptor descriptor : a.keySet()) {
if (!b.containsKey(descriptor)) {
return false;
}
Object value1 = a.get(descriptor);
Object value2 = b.get(descriptor);
if (descriptor.getType() == FieldDescriptor.Type.BYTES) {
if (descriptor.isRepeated()) {
List<?> list1 = (List) value1;
List<?> list2 = (List) value2;
if (list1.size() != list2.size()) {
return false;
}
for (int i = 0; i < list1.size(); i++) {
if (!compareBytes(list1.get(i), list2.get(i))) {
return false;
}
}
} else {
// Compares a singular bytes field.
if (!compareBytes(value1, value2)) {
return false;
}
}
} else if (descriptor.isMapField()) {
if (!compareMapField(value1, value2)) {
return false;
}
} else {
// Compare non-bytes fields.
if (!value1.equals(value2)) {
return false;
}
}
}
return true;
}
/** Calculates the hash code of a map field. {@code value} must be a list of MapEntry messages. */
@SuppressWarnings("unchecked")
private static int hashMapField(Object value) {
return MapFieldLite.calculateHashCodeForMap(convertMapEntryListToMap((List) value));
}
/** Get a hash code for given fields and values, using the given seed. */
@SuppressWarnings("unchecked")
protected static int hashFields(int hash, Map<FieldDescriptor, Object> map) {
for (Map.Entry<FieldDescriptor, Object> entry : map.entrySet()) {
FieldDescriptor field = entry.getKey();
Object value = entry.getValue();
hash = (37 * hash) + field.getNumber();
if (field.isMapField()) {
hash = (53 * hash) + hashMapField(value);
} else if (field.getType() != FieldDescriptor.Type.ENUM) {
hash = (53 * hash) + value.hashCode();
} else if (field.isRepeated()) {
List<? extends Internal.EnumLite> list = (List<? extends Internal.EnumLite>) value;
hash = (53 * hash) + Internal.hashEnumList(list);
} else {
hash = (53 * hash) + Internal.hashEnum((Internal.EnumLite) value);
}
}
return hash;
}
// /**
// * Package private helper method for AbstractParser to create UninitializedMessageException with
// * missing field information.
// */
// UninitializedMessageException newUninitializedMessageException() {
// return AbstractMessage.Builder.newUninitializedMessageException(this);
// }
/** TODO: Remove this unnecessary intermediate implementation of this method. */
@Override
public Parser<? extends FlattenedGeneratedMessageV3> getParserForType() {
throw new UnsupportedOperationException("This is supposed to be overridden by subclasses.");
}
/**
* TODO: Stop using SingleFieldBuilder and remove this setting
*
* @see #setAlwaysUseFieldBuildersForTesting(boolean)
*/
static void enableAlwaysUseFieldBuildersForTesting() {
setAlwaysUseFieldBuildersForTesting(true);
}
/**
* For testing. Allows a test to disable/re-enable the optimization that avoids using field
* builders for nested messages until they are requested. By disabling this optimization, existing
* tests can be reused to test the field builders. See {@link RepeatedFieldBuilder} and {@link
* SingleFieldBuilder}.
*
* <p>TODO: Stop using SingleFieldBuilder and remove this setting
*/
static void setAlwaysUseFieldBuildersForTesting(boolean useBuilders) {
alwaysUseFieldBuilders = useBuilders;
}
/**
* Get the FieldAccessorTable for this type. We can't have the message class pass this in to the
* constructor because of bootstrapping trouble with DescriptorProtos.
*/
protected abstract FieldAccessorTable internalGetFieldAccessorTable();
public Descriptor getDescriptorForType() {
return internalGetFieldAccessorTable().descriptor;
}
/**
* TODO: This method should be removed. It enables parsing directly into an
* "immutable" message. Have to leave it for now to support old gencode.
*
* @deprecated use newBuilder().mergeFrom() instead
*/
@Deprecated
protected void mergeFromAndMakeImmutableInternal(
CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
Schema<FlattenedGeneratedMessageV3> schema = Protobuf.getInstance().schemaFor(this);
try {
schema.mergeFrom(this, CodedInputStreamReader.forCodedInput(input), extensionRegistry);
} catch (InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (IOException e) {
throw new InvalidProtocolBufferException(e).setUnfinishedMessage(this);
}
schema.makeImmutable(this);
}
/**
* Internal helper to return a modifiable map containing all the fields. The returned Map is
* modifiable so that the caller can add additional extension fields to implement {@link
* #getAllFields()}.
*
* @param getBytesForString whether to generate ByteString for string fields
*/
private Map<FieldDescriptor, Object> getAllFieldsMutable(boolean getBytesForString) {
final TreeMap<FieldDescriptor, Object> result = new TreeMap<>();
final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
final List<FieldDescriptor> fields = descriptor.getFields();
for (int i = 0; i < fields.size(); i++) {
FieldDescriptor field = fields.get(i);
final OneofDescriptor oneofDescriptor = field.getContainingOneof();
/*
* If the field is part of a Oneof, then at maximum one field in the Oneof is set
* and it is not repeated. There is no need to iterate through the others.
*/
if (oneofDescriptor != null) {
// Skip other fields in the Oneof we know are not set
i += oneofDescriptor.getFieldCount() - 1;
if (!hasOneof(oneofDescriptor)) {
// If no field is set in the Oneof, skip all the fields in the Oneof
continue;
}
// Get the pointer to the only field which is set in the Oneof
field = getOneofFieldDescriptor(oneofDescriptor);
} else {
// If we are not in a Oneof, we need to check if the field is set and if it is repeated
if (field.isRepeated()) {
final List<?> value = (List<?>) getField(field);
if (!value.isEmpty()) {
result.put(field, value);
}
continue;
}
if (!hasField(field)) {
continue;
}
}
// Add the field to the map
if (getBytesForString && field.getJavaType() == FieldDescriptor.JavaType.STRING) {
result.put(field, getFieldRaw(field));
} else {
result.put(field, getField(field));
}
}
return result;
}
// TODO: compute this at {@code build()} time in the Builder class.
public boolean isInitialized() {
for (final FieldDescriptor field : getDescriptorForType().getFields()) {
// Check that all required fields are present.
if (field.isRequired()) {
if (!hasField(field)) {
return false;
}
}
// Check that embedded messages are initialized.
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
if (field.isRepeated()) {
@SuppressWarnings("unchecked")
final List<Message> messageList = (List<Message>) getField(field);
for (final Message element : messageList) {
if (!element.isInitialized()) {
return false;
}
}
} else {
if (hasField(field) && !((Message) getField(field)).isInitialized()) {
return false;
}
}
}
}
return true;
}
public Map<FieldDescriptor, Object> getAllFields() {
return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString= */ false));
}
/**
* Returns a collection of all the fields in this message which are set and their corresponding
* values. A singular ("required" or "optional") field is set iff hasField() returns true for that
* field. A "repeated" field is set iff getRepeatedFieldCount() is greater than zero. The values
* are exactly what would be returned by calling {@link #getFieldRaw(FieldDescriptor)}
* for each field. The map is guaranteed to be a sorted map, so iterating over it will return
* fields in order by field number.
*/
Map<FieldDescriptor, Object> getAllFieldsRaw() {
return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString= */ true));
}
public boolean hasOneof(final OneofDescriptor oneof) {
return internalGetFieldAccessorTable().getOneof(oneof).has(this);
}
public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) {
return internalGetFieldAccessorTable().getOneof(oneof).get(this);
}
public boolean hasField(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).has(this);
}
public Object getField(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).get(this);
}
/**
* Obtains the value of the given field, or the default value if it is not set. For primitive
* fields, the boxed primitive value is returned. For enum fields, the EnumValueDescriptor for the
* value is returned. For embedded message fields, the sub-message is returned. For repeated
* fields, a java.util.List is returned. For present string fields, a ByteString is returned
* representing the bytes that the field contains.
*/
Object getFieldRaw(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).getRaw(this);
}
public int getRepeatedFieldCount(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this);
}
public Object getRepeatedField(final FieldDescriptor field, final int index) {
return internalGetFieldAccessorTable().getField(field).getRepeated(this, index);
}
// TODO: This method should be final.
public UnknownFieldSet getUnknownFields() {
return unknownFields;
}
// TODO: This should go away when Schema classes cannot modify immutable
// GeneratedMessageV3 objects anymore.
void setUnknownFields(UnknownFieldSet unknownFields) {
this.unknownFields = unknownFields;
}
/**
* Called by subclasses to parse an unknown field.
*
* <p>TODO remove this method
*
* @return {@code true} unless the tag is an end-group tag.
*/
protected boolean parseUnknownField(
CodedInputStream input,
UnknownFieldSet.Builder unknownFields,
ExtensionRegistryLite extensionRegistry,
int tag)
throws IOException {
if (input.shouldDiscardUnknownFields()) {
return input.skipField(tag);
}
return unknownFields.mergeFieldFrom(tag, input);
}
/**
* Delegates to parseUnknownField. This method is obsolete, but we must retain it for
* compatibility with older generated code.
*
* <p>TODO remove this method
*/
protected boolean parseUnknownFieldProto3(
CodedInputStream input,
UnknownFieldSet.Builder unknownFields,
ExtensionRegistryLite extensionRegistry,
int tag)
throws IOException {
return parseUnknownField(input, unknownFields, extensionRegistry, tag);
}
/** Used by generated code. */
@SuppressWarnings("ProtoParseWithRegistry")
protected static <M extends Message> M parseWithIOException(Parser<M> parser, InputStream input)
throws IOException {
try {
return parser.parseFrom(input);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
protected static <M extends Message> M parseWithIOException(
Parser<M> parser, InputStream input, ExtensionRegistryLite extensions) throws IOException {
try {
return parser.parseFrom(input, extensions);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
@SuppressWarnings("ProtoParseWithRegistry")
protected static <M extends Message> M parseWithIOException(
Parser<M> parser, CodedInputStream input) throws IOException {
try {
return parser.parseFrom(input);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
protected static <M extends Message> M parseWithIOException(
Parser<M> parser, CodedInputStream input, ExtensionRegistryLite extensions)
throws IOException {
try {
return parser.parseFrom(input, extensions);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
@SuppressWarnings("ProtoParseWithRegistry")
protected static <M extends Message> M parseDelimitedWithIOException(
Parser<M> parser, InputStream input) throws IOException {
try {
return parser.parseDelimitedFrom(input);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
protected static <M extends Message> M parseDelimitedWithIOException(
Parser<M> parser, InputStream input, ExtensionRegistryLite extensions) throws IOException {
try {
return parser.parseDelimitedFrom(input, extensions);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
protected static boolean canUseUnsafe() {
return UnsafeUtil.hasUnsafeArrayOperations() && UnsafeUtil.hasUnsafeByteBufferOperations();
}
protected static IntList emptyIntList() {
return IntArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static IntList newIntList() {
return new IntArrayList();
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static IntList mutableCopy(IntList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static LongList mutableCopy(LongList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static FloatList mutableCopy(FloatList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static DoubleList mutableCopy(DoubleList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static BooleanList mutableCopy(BooleanList list) {
return makeMutableCopy(list);
}
protected static LongList emptyLongList() {
return LongArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static LongList newLongList() {
return new LongArrayList();
}
protected static FloatList emptyFloatList() {
return FloatArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static FloatList newFloatList() {
return new FloatArrayList();
}
protected static DoubleList emptyDoubleList() {
return DoubleArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static DoubleList newDoubleList() {
return new DoubleArrayList();
}
protected static BooleanList emptyBooleanList() {
return BooleanArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static BooleanList newBooleanList() {
return new BooleanArrayList();
}
protected static <ListT extends ProtobufList<?>> ListT makeMutableCopy(ListT list) {
return makeMutableCopy(list, 0);
}
@SuppressWarnings("unchecked") // Guaranteed by proto runtime.
protected static <ListT extends ProtobufList<?>> ListT makeMutableCopy(
ListT list, int minCapacity) {
int size = list.size();
if (minCapacity <= size) {
minCapacity = size * 2;
}
if (minCapacity <= 0) {
minCapacity = AbstractProtobufList.DEFAULT_CAPACITY;
}
return (ListT) list.mutableCopyWithCapacity(minCapacity);
}
@SuppressWarnings("unchecked") // The empty list can be safely cast
protected static <T> ProtobufList<T> emptyList(Class<T> elementType) {
return (ProtobufList<T>) ProtobufArrayList.emptyList();
}
public void writeTo(final CodedOutputStream output) throws IOException {
MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
memoizedSize = MessageReflection.getSerializedSize(
this, getAllFieldsRaw());
return memoizedSize;
}
/**
* This class is used to make a generated protected method inaccessible from user's code (e.g.,
* the {@link #newInstance} method below). When this class is used as a parameter's type in a
* generated protected method, the method is visible to user's code in the same package, but since
* the constructor of this class is private to protobuf runtime, user's code can't obtain an
* instance of this class and as such can't actually make a method call on the protected method.
*/
protected static final class UnusedPrivateParameter {
static final UnusedPrivateParameter INSTANCE = new UnusedPrivateParameter();
private UnusedPrivateParameter() {}
}
/** Creates a new instance of this message type. Overridden in the generated code. */
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
throw new UnsupportedOperationException("This method must be overridden by the subclass.");
}
/**
* Used by parsing constructors in generated classes.
*
* <p>TODO: remove unused method (extensions should be immutable after build)
*/
protected void makeExtensionsImmutable() {
// Noop for messages without extensions.
}
/** TODO: remove this together with GeneratedMessageV3.BuilderParent. */
protected abstract Message.Builder newBuilderForType(BuilderParent parent);
/** TODO: generated class should implement this directly */
protected Message.Builder newBuilderForType(final Message.BuilderParent parent) {
return newBuilderForType(
new BuilderParent() {
@Override
public void markDirty() {
parent.markDirty();
}
});
}
/** Builder class for {@link FlattenedGeneratedMessageV3}. */
@SuppressWarnings("unchecked")
public abstract static class Builder<BuilderT extends Builder<BuilderT>>
implements Message.Builder {
private BuilderParent builderParent;
private BuilderParentImpl meAsParent;
// Indicates that we've built a message and so we are now obligated
// to dispatch dirty invalidations. See GeneratedMessageV3.BuilderListener.
private boolean isClean;
/**
* This field holds either an {@link UnknownFieldSet} or {@link UnknownFieldSet.Builder}.
*
* <p>We use an object because it should only be one or the other of those things at a time and
* Object is the only common base. This also saves space.
*
* <p>Conversions are lazy: if {@link #setUnknownFields} is called, this will contain {@link
* UnknownFieldSet}. If unknown fields are merged into this builder, the current {@link
* UnknownFieldSet} will be converted to a {@link UnknownFieldSet.Builder} and left that way
* until either {@link #setUnknownFields} or {@link #buildPartial} or {@link #build} is called.
*/
private Object unknownFieldsOrBuilder = UnknownFieldSet.getDefaultInstance();
protected Builder() {
this(null);
}
protected Builder(BuilderParent builderParent) {
this.builderParent = builderParent;
}
static final class LimitedInputStream extends FilterInputStream {
private int limit;
LimitedInputStream(InputStream in, int limit) {
super(in);
this.limit = limit;
}
@Override
public int available() throws IOException {
return Math.min(super.available(), limit);
}
@Override
public int read() throws IOException {
if (limit <= 0) {
return -1;
}
final int result = super.read();
if (result >= 0) {
--limit;
}
return result;
}
@Override
public int read(final byte[] b, final int off, int len) throws IOException {
if (limit <= 0) {
return -1;
}
len = Math.min(len, limit);
final int result = super.read(b, off, len);
if (result >= 0) {
limit -= result;
}
return result;
}
@Override
public long skip(final long n) throws IOException {
// because we take the minimum of an int and a long, result is guaranteed to be
// less than or equal to Integer.MAX_INT so this cast is safe
int result = (int) super.skip(Math.min(n, limit));
if (result >= 0) {
// if the superclass adheres to the contract for skip, this condition is always true
limit -= result;
}
return result;
}
}
@Override
public boolean mergeDelimitedFrom(
final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException {
final int firstByte = input.read();
if (firstByte == -1) {
return false;
}
final int size = CodedInputStream.readRawVarint32(firstByte, input);
final InputStream limitedInput = new AbstractMessageLite.Builder.LimitedInputStream(input, size);
mergeFrom(limitedInput, extensionRegistry);
return true;
}
@Override
public boolean mergeDelimitedFrom(final InputStream input) throws IOException {
return mergeDelimitedFrom(input, ExtensionRegistryLite.getEmptyRegistry());
}
@Override
@SuppressWarnings("unchecked") // isInstance takes care of this
public BuilderT mergeFrom(final MessageLite other) {
if (!getDefaultInstanceForType().getClass().isInstance(other)) {
throw new IllegalArgumentException(
"mergeFrom(MessageLite) can only merge messages of the same type.");
}
return internalMergeFrom(other);
}
private String getReadingExceptionMessage(String target) {
return "Reading "
+ getClass().getName()
+ " from a "
+ target
+ " threw an IOException (should never happen).";
}
// We check nulls as we iterate to avoid iterating over values twice.
private static <T> void addAllCheckingNulls(Iterable<T> values, List<? super T> list) {
if (list instanceof ArrayList && values instanceof Collection) {
((ArrayList<T>) list).ensureCapacity(list.size() + ((Collection<T>) values).size());
}
int begin = list.size();
for (T value : values) {
if (value == null) {
// encountered a null value so we must undo our modifications prior to throwing
String message = "Element at index " + (list.size() - begin) + " is null.";
for (int i = list.size() - 1; i >= begin; i--) {
list.remove(i);
}
throw new NullPointerException(message);
}
list.add(value);
}
}
/** Construct an UninitializedMessageException reporting missing fields in the given message. */
protected static UninitializedMessageException newUninitializedMessageException(
MessageLite message) {
return new UninitializedMessageException(message);
}
// For binary compatibility.
@Deprecated
protected static <T> void addAll(final Iterable<T> values, final Collection<? super T> list) {
addAll(values, (List<T>) list);
}
/**
* Adds the {@code values} to the {@code list}. This is a helper method used by generated code.
* Users should ignore it.
*
* @throws NullPointerException if {@code values} or any of the elements of {@code values} is
* null.
*/
protected static <T> void addAll(final Iterable<T> values, final List<? super T> list) {
checkNotNull(values);
if (values instanceof LazyStringList) {
// For StringOrByteStringLists, check the underlying elements to avoid
// forcing conversions of ByteStrings to Strings.
// TODO: Could we just prohibit nulls in all protobuf lists and get rid of this? Is
// if even possible to hit this condition as all protobuf methods check for null first,
// right?
List<?> lazyValues = ((LazyStringList) values).getUnderlyingElements();
LazyStringList lazyList = (LazyStringList) list;
int begin = list.size();
for (Object value : lazyValues) {
if (value == null) {
// encountered a null value so we must undo our modifications prior to throwing
String message = "Element at index " + (lazyList.size() - begin) + " is null.";
for (int i = lazyList.size() - 1; i >= begin; i--) {
lazyList.remove(i);
}
throw new NullPointerException(message);
}
if (value instanceof ByteString) {
lazyList.add((ByteString) value);
} else {
lazyList.add((String) value);
}
}
} else {
if (values instanceof PrimitiveNonBoxingCollection) {
list.addAll((Collection<T>) values);
} else {