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 com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream; 34 import com.google.protobuf.GeneratedMessageLite.EqualsVisitor.NotEqualsException; 35 import com.google.protobuf.Internal.BooleanList; 36 import com.google.protobuf.Internal.DoubleList; 37 import com.google.protobuf.Internal.FloatList; 38 import com.google.protobuf.Internal.IntList; 39 import com.google.protobuf.Internal.LongList; 40 import com.google.protobuf.Internal.ProtobufList; 41 import com.google.protobuf.WireFormat.FieldType; 42 43 import java.io.IOException; 44 import java.io.InputStream; 45 import java.io.ObjectStreamException; 46 import java.io.Serializable; 47 import java.lang.reflect.InvocationTargetException; 48 import java.lang.reflect.Method; 49 import java.util.ArrayList; 50 import java.util.Collections; 51 import java.util.Iterator; 52 import java.util.List; 53 import java.util.Map; 54 55 /** 56 * Lite version of {@link GeneratedMessage}. 57 * 58 * @author kenton (at) google.com Kenton Varda 59 */ 60 public abstract class GeneratedMessageLite< 61 MessageType extends GeneratedMessageLite<MessageType, BuilderType>, 62 BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>> 63 extends AbstractMessageLite<MessageType, BuilderType> { 64 65 /** For use by generated code only. Lazily initialized to reduce allocations. */ 66 protected UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance(); 67 68 /** For use by generated code only. */ 69 protected int memoizedSerializedSize = -1; 70 71 @Override 72 @SuppressWarnings("unchecked") // Guaranteed by runtime. 73 public final Parser<MessageType> getParserForType() { 74 return (Parser<MessageType>) dynamicMethod(MethodToInvoke.GET_PARSER); 75 } 76 77 @Override 78 @SuppressWarnings("unchecked") // Guaranteed by runtime. 79 public final MessageType getDefaultInstanceForType() { 80 return (MessageType) dynamicMethod(MethodToInvoke.GET_DEFAULT_INSTANCE); 81 } 82 83 @Override 84 @SuppressWarnings("unchecked") // Guaranteed by runtime. 85 public final BuilderType newBuilderForType() { 86 return (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER); 87 } 88 89 /** 90 * A reflective toString function. This is primarily intended as a developer aid, while keeping 91 * binary size down. The first line of the {@code toString()} representation includes a commented 92 * version of {@code super.toString()} to act as an indicator that this should not be relied on 93 * for comparisons. 94 * <p> 95 * NOTE: This method relies on the field getter methods not being stripped or renamed by proguard. 96 * If they are, the fields will not be included in the returned string representation. 97 * <p> 98 * NOTE: This implementation is liable to change in the future, and should not be relied on in 99 * code. 100 */ 101 @Override 102 public String toString() { 103 return MessageLiteToString.toString(this, super.toString()); 104 } 105 106 @SuppressWarnings("unchecked") // Guaranteed by runtime 107 @Override 108 public int hashCode() { 109 if (memoizedHashCode == 0) { 110 HashCodeVisitor visitor = new HashCodeVisitor(); 111 visit(visitor, (MessageType) this); 112 memoizedHashCode = visitor.hashCode; 113 } 114 return memoizedHashCode; 115 } 116 117 @SuppressWarnings("unchecked") // Guaranteed by runtime 118 int hashCode(HashCodeVisitor visitor) { 119 if (memoizedHashCode == 0) { 120 int inProgressHashCode = visitor.hashCode; 121 visitor.hashCode = 0; 122 visit(visitor, (MessageType) this); 123 memoizedHashCode = visitor.hashCode; 124 visitor.hashCode = inProgressHashCode; 125 } 126 return memoizedHashCode; 127 } 128 129 @SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime 130 @Override 131 public boolean equals(Object other) { 132 if (this == other) { 133 return true; 134 } 135 136 if (!getDefaultInstanceForType().getClass().isInstance(other)) { 137 return false; 138 } 139 140 try { 141 visit(EqualsVisitor.INSTANCE, (MessageType) other); 142 } catch (NotEqualsException e) { 143 return false; 144 } 145 return true; 146 } 147 148 /** 149 * Same as {@link #equals(Object)} but throws {@code NotEqualsException}. 150 */ 151 @SuppressWarnings("unchecked") // Guaranteed by isInstance + runtime 152 boolean equals(EqualsVisitor visitor, MessageLite other) { 153 if (this == other) { 154 return true; 155 } 156 157 if (!getDefaultInstanceForType().getClass().isInstance(other)) { 158 return false; 159 } 160 161 visit(visitor, (MessageType) other); 162 return true; 163 } 164 165 // The general strategy for unknown fields is to use an UnknownFieldSetLite that is treated as 166 // mutable during the parsing constructor and immutable after. This allows us to avoid 167 // any unnecessary intermediary allocations while reducing the generated code size. 168 169 /** 170 * Lazily initializes unknown fields. 171 */ 172 private final void ensureUnknownFieldsInitialized() { 173 if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) { 174 unknownFields = UnknownFieldSetLite.newInstance(); 175 } 176 } 177 178 /** 179 * Called by subclasses to parse an unknown field. For use by generated code only. 180 * 181 * @return {@code true} unless the tag is an end-group tag. 182 */ 183 protected boolean parseUnknownField(int tag, CodedInputStream input) throws IOException { 184 // This will avoid the allocation of unknown fields when a group tag is encountered. 185 if (WireFormat.getTagWireType(tag) == WireFormat.WIRETYPE_END_GROUP) { 186 return false; 187 } 188 189 ensureUnknownFieldsInitialized(); 190 return unknownFields.mergeFieldFrom(tag, input); 191 } 192 193 /** 194 * Called by subclasses to parse an unknown field. For use by generated code only. 195 */ 196 protected void mergeVarintField(int tag, int value) { 197 ensureUnknownFieldsInitialized(); 198 unknownFields.mergeVarintField(tag, value); 199 } 200 201 /** 202 * Called by subclasses to parse an unknown field. For use by generated code only. 203 */ 204 protected void mergeLengthDelimitedField(int fieldNumber, ByteString value) { 205 ensureUnknownFieldsInitialized(); 206 unknownFields.mergeLengthDelimitedField(fieldNumber, value); 207 } 208 209 /** 210 * Called by subclasses to complete parsing. For use by generated code only. 211 */ 212 protected void makeImmutable() { 213 dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE); 214 215 unknownFields.makeImmutable(); 216 } 217 218 @Override 219 public final boolean isInitialized() { 220 return dynamicMethod(MethodToInvoke.IS_INITIALIZED, Boolean.TRUE) != null; 221 } 222 223 @Override 224 public final BuilderType toBuilder() { 225 BuilderType builder = (BuilderType) dynamicMethod(MethodToInvoke.NEW_BUILDER); 226 builder.mergeFrom((MessageType) this); 227 return builder; 228 } 229 230 /** 231 * Defines which method path to invoke in {@link GeneratedMessageLite 232 * #dynamicMethod(MethodToInvoke, Object...)}. 233 * <p> 234 * For use by generated code only. 235 */ 236 public static enum MethodToInvoke { 237 // Rely on/modify instance state 238 IS_INITIALIZED, 239 VISIT, 240 MERGE_FROM_STREAM, 241 MAKE_IMMUTABLE, 242 243 // Rely on static state 244 NEW_MUTABLE_INSTANCE, 245 NEW_BUILDER, 246 GET_DEFAULT_INSTANCE, 247 GET_PARSER; 248 } 249 250 /** 251 * A method that implements different types of operations described in {@link MethodToInvoke}. 252 * Theses different kinds of operations are required to implement message-level operations for 253 * builders in the runtime. This method bundles those operations to reduce the generated methods 254 * count. 255 * <ul> 256 * <li>{@code MERGE_FROM_STREAM} is parameterized with an {@link CodedInputStream} and 257 * {@link ExtensionRegistryLite}. It consumes the input stream, parsing the contents into the 258 * returned protocol buffer. If parsing throws an {@link InvalidProtocolBufferException}, the 259 * implementation wraps it in a RuntimeException. 260 * <li>{@code NEW_INSTANCE} returns a new instance of the protocol buffer that has not yet been 261 * made immutable. See {@code MAKE_IMMUTABLE}. 262 * <li>{@code IS_INITIALIZED} is parameterized with a {@code Boolean} detailing whether to 263 * memoize. It returns {@code null} for false and the default instance for true. We optionally 264 * memoize to support the Builder case, where memoization is not desired. 265 * <li>{@code NEW_BUILDER} returns a {@code BuilderType} instance. 266 * <li>{@code VISIT} is parameterized with a {@code Visitor} and a {@code MessageType} and 267 * recursively iterates through the fields side by side between this and the instance. 268 * <li>{@code MAKE_IMMUTABLE} sets all internal fields to an immutable state. 269 * </ul> 270 * This method, plus the implementation of the Builder, enables the Builder class to be proguarded 271 * away entirely on Android. 272 * <p> 273 * For use by generated code only. 274 */ 275 protected abstract Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1); 276 277 /** 278 * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. 279 */ 280 protected Object dynamicMethod(MethodToInvoke method, Object arg0) { 281 return dynamicMethod(method, arg0, null); 282 } 283 284 /** 285 * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. 286 */ 287 protected Object dynamicMethod(MethodToInvoke method) { 288 return dynamicMethod(method, null, null); 289 } 290 291 void visit(Visitor visitor, MessageType other) { 292 dynamicMethod(MethodToInvoke.VISIT, visitor, other); 293 unknownFields = visitor.visitUnknownFields(unknownFields, other.unknownFields); 294 } 295 296 /** 297 * Merge some unknown fields into the {@link UnknownFieldSetLite} for this 298 * message. 299 * 300 * <p>For use by generated code only. 301 */ 302 protected final void mergeUnknownFields(UnknownFieldSetLite unknownFields) { 303 this.unknownFields = UnknownFieldSetLite.mutableCopyOf(this.unknownFields, unknownFields); 304 } 305 306 @SuppressWarnings("unchecked") 307 public abstract static class Builder< 308 MessageType extends GeneratedMessageLite<MessageType, BuilderType>, 309 BuilderType extends Builder<MessageType, BuilderType>> 310 extends AbstractMessageLite.Builder<MessageType, BuilderType> { 311 312 private final MessageType defaultInstance; 313 protected MessageType instance; 314 protected boolean isBuilt; 315 316 protected Builder(MessageType defaultInstance) { 317 this.defaultInstance = defaultInstance; 318 this.instance = 319 (MessageType) defaultInstance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); 320 isBuilt = false; 321 } 322 323 /** 324 * Called before any method that would mutate the builder to ensure that it correctly copies 325 * any state before the write happens to preserve immutability guarantees. 326 */ 327 protected void copyOnWrite() { 328 if (isBuilt) { 329 MessageType newInstance = 330 (MessageType) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); 331 newInstance.visit(MergeFromVisitor.INSTANCE, instance); 332 instance = newInstance; 333 isBuilt = false; 334 } 335 } 336 337 @Override 338 public final boolean isInitialized() { 339 return GeneratedMessageLite.isInitialized(instance, false /* shouldMemoize */); 340 } 341 342 @Override 343 public final BuilderType clear() { 344 // No need to copy on write since we're dropping the instance anyways. 345 instance = (MessageType) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); 346 return (BuilderType) this; 347 } 348 349 @Override 350 public BuilderType clone() { 351 BuilderType builder = 352 (BuilderType) getDefaultInstanceForType().newBuilderForType(); 353 builder.mergeFrom(buildPartial()); 354 return builder; 355 } 356 357 @Override 358 public MessageType buildPartial() { 359 if (isBuilt) { 360 return instance; 361 } 362 363 instance.makeImmutable(); 364 365 isBuilt = true; 366 return instance; 367 } 368 369 @Override 370 public final MessageType build() { 371 MessageType result = buildPartial(); 372 if (!result.isInitialized()) { 373 throw newUninitializedMessageException(result); 374 } 375 return result; 376 } 377 378 @Override 379 protected BuilderType internalMergeFrom(MessageType message) { 380 return mergeFrom(message); 381 } 382 383 /** All subclasses implement this. */ 384 public BuilderType mergeFrom(MessageType message) { 385 copyOnWrite(); 386 instance.visit(MergeFromVisitor.INSTANCE, message); 387 return (BuilderType) this; 388 } 389 390 @Override 391 public MessageType getDefaultInstanceForType() { 392 return defaultInstance; 393 } 394 395 @Override 396 public BuilderType mergeFrom( 397 com.google.protobuf.CodedInputStream input, 398 com.google.protobuf.ExtensionRegistryLite extensionRegistry) 399 throws IOException { 400 copyOnWrite(); 401 try { 402 instance.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry); 403 } catch (RuntimeException e) { 404 if (e.getCause() instanceof IOException) { 405 throw (IOException) e.getCause(); 406 } 407 throw e; 408 } 409 return (BuilderType) this; 410 } 411 } 412 413 414 // ================================================================= 415 // Extensions-related stuff 416 417 /** 418 * Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}. 419 */ 420 public interface ExtendableMessageOrBuilder< 421 MessageType extends ExtendableMessage<MessageType, BuilderType>, 422 BuilderType extends ExtendableBuilder<MessageType, BuilderType>> 423 extends MessageLiteOrBuilder { 424 425 /** Check if a singular extension is present. */ 426 <Type> boolean hasExtension( 427 ExtensionLite<MessageType, Type> extension); 428 429 /** Get the number of elements in a repeated extension. */ 430 <Type> int getExtensionCount( 431 ExtensionLite<MessageType, List<Type>> extension); 432 433 /** Get the value of an extension. */ 434 <Type> Type getExtension(ExtensionLite<MessageType, Type> extension); 435 436 /** Get one element of a repeated extension. */ 437 <Type> Type getExtension( 438 ExtensionLite<MessageType, List<Type>> extension, 439 int index); 440 } 441 442 /** 443 * Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. 444 */ 445 public abstract static class ExtendableMessage< 446 MessageType extends ExtendableMessage<MessageType, BuilderType>, 447 BuilderType extends ExtendableBuilder<MessageType, BuilderType>> 448 extends GeneratedMessageLite<MessageType, BuilderType> 449 implements ExtendableMessageOrBuilder<MessageType, BuilderType> { 450 451 /** 452 * Represents the set of extensions on this message. For use by generated 453 * code only. 454 */ 455 protected FieldSet<ExtensionDescriptor> extensions = FieldSet.newFieldSet(); 456 457 protected final void mergeExtensionFields(final MessageType other) { 458 if (extensions.isImmutable()) { 459 extensions = extensions.clone(); 460 } 461 extensions.mergeFrom(((ExtendableMessage) other).extensions); 462 } 463 464 @Override 465 final void visit(Visitor visitor, MessageType other) { 466 super.visit(visitor, other); 467 extensions = visitor.visitExtensions(extensions, other.extensions); 468 } 469 470 /** 471 * Parse an unknown field or an extension. For use by generated code only. 472 * 473 * <p>For use by generated code only. 474 * 475 * @return {@code true} unless the tag is an end-group tag. 476 */ 477 protected <MessageType extends MessageLite> boolean parseUnknownField( 478 MessageType defaultInstance, 479 CodedInputStream input, 480 ExtensionRegistryLite extensionRegistry, 481 int tag) throws IOException { 482 int wireType = WireFormat.getTagWireType(tag); 483 int fieldNumber = WireFormat.getTagFieldNumber(tag); 484 485 // TODO(dweis): How much bytecode would be saved by not requiring the generated code to 486 // provide the default instance? 487 GeneratedExtension<MessageType, ?> extension = extensionRegistry.findLiteExtensionByNumber( 488 defaultInstance, fieldNumber); 489 490 boolean unknown = false; 491 boolean packed = false; 492 if (extension == null) { 493 unknown = true; // Unknown field. 494 } else if (wireType == FieldSet.getWireFormatForFieldType( 495 extension.descriptor.getLiteType(), 496 false /* isPacked */)) { 497 packed = false; // Normal, unpacked value. 498 } else if (extension.descriptor.isRepeated && 499 extension.descriptor.type.isPackable() && 500 wireType == FieldSet.getWireFormatForFieldType( 501 extension.descriptor.getLiteType(), 502 true /* isPacked */)) { 503 packed = true; // Packed value. 504 } else { 505 unknown = true; // Wrong wire type. 506 } 507 508 if (unknown) { // Unknown field or wrong wire type. Skip. 509 return parseUnknownField(tag, input); 510 } 511 512 if (packed) { 513 int length = input.readRawVarint32(); 514 int limit = input.pushLimit(length); 515 if (extension.descriptor.getLiteType() == WireFormat.FieldType.ENUM) { 516 while (input.getBytesUntilLimit() > 0) { 517 int rawValue = input.readEnum(); 518 Object value = 519 extension.descriptor.getEnumType().findValueByNumber(rawValue); 520 if (value == null) { 521 // If the number isn't recognized as a valid value for this 522 // enum, drop it (don't even add it to unknownFields). 523 return true; 524 } 525 extensions.addRepeatedField(extension.descriptor, 526 extension.singularToFieldSetType(value)); 527 } 528 } else { 529 while (input.getBytesUntilLimit() > 0) { 530 Object value = 531 FieldSet.readPrimitiveField(input, 532 extension.descriptor.getLiteType(), 533 /*checkUtf8=*/ false); 534 extensions.addRepeatedField(extension.descriptor, value); 535 } 536 } 537 input.popLimit(limit); 538 } else { 539 Object value; 540 switch (extension.descriptor.getLiteJavaType()) { 541 case MESSAGE: { 542 MessageLite.Builder subBuilder = null; 543 if (!extension.descriptor.isRepeated()) { 544 MessageLite existingValue = 545 (MessageLite) extensions.getField(extension.descriptor); 546 if (existingValue != null) { 547 subBuilder = existingValue.toBuilder(); 548 } 549 } 550 if (subBuilder == null) { 551 subBuilder = extension.getMessageDefaultInstance() 552 .newBuilderForType(); 553 } 554 if (extension.descriptor.getLiteType() == 555 WireFormat.FieldType.GROUP) { 556 input.readGroup(extension.getNumber(), 557 subBuilder, extensionRegistry); 558 } else { 559 input.readMessage(subBuilder, extensionRegistry); 560 } 561 value = subBuilder.build(); 562 break; 563 } 564 case ENUM: 565 int rawValue = input.readEnum(); 566 value = extension.descriptor.getEnumType() 567 .findValueByNumber(rawValue); 568 // If the number isn't recognized as a valid value for this enum, 569 // write it to unknown fields object. 570 if (value == null) { 571 mergeVarintField(fieldNumber, rawValue); 572 return true; 573 } 574 break; 575 default: 576 value = FieldSet.readPrimitiveField(input, 577 extension.descriptor.getLiteType(), 578 /*checkUtf8=*/ false); 579 break; 580 } 581 582 if (extension.descriptor.isRepeated()) { 583 extensions.addRepeatedField(extension.descriptor, 584 extension.singularToFieldSetType(value)); 585 } else { 586 extensions.setField(extension.descriptor, 587 extension.singularToFieldSetType(value)); 588 } 589 } 590 591 return true; 592 } 593 594 private void verifyExtensionContainingType( 595 final GeneratedExtension<MessageType, ?> extension) { 596 if (extension.getContainingTypeDefaultInstance() != 597 getDefaultInstanceForType()) { 598 // This can only happen if someone uses unchecked operations. 599 throw new IllegalArgumentException( 600 "This extension is for a different message type. Please make " + 601 "sure that you are not suppressing any generics type warnings."); 602 } 603 } 604 605 /** Check if a singular extension is present. */ 606 @Override 607 public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) { 608 GeneratedExtension<MessageType, Type> extensionLite = 609 checkIsLite(extension); 610 611 verifyExtensionContainingType(extensionLite); 612 return extensions.hasField(extensionLite.descriptor); 613 } 614 615 /** Get the number of elements in a repeated extension. */ 616 @Override 617 public final <Type> int getExtensionCount( 618 final ExtensionLite<MessageType, List<Type>> extension) { 619 GeneratedExtension<MessageType, List<Type>> extensionLite = 620 checkIsLite(extension); 621 622 verifyExtensionContainingType(extensionLite); 623 return extensions.getRepeatedFieldCount(extensionLite.descriptor); 624 } 625 626 /** Get the value of an extension. */ 627 @Override 628 @SuppressWarnings("unchecked") 629 public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) { 630 GeneratedExtension<MessageType, Type> extensionLite = 631 checkIsLite(extension); 632 633 verifyExtensionContainingType(extensionLite); 634 final Object value = extensions.getField(extensionLite.descriptor); 635 if (value == null) { 636 return extensionLite.defaultValue; 637 } else { 638 return (Type) extensionLite.fromFieldSetType(value); 639 } 640 } 641 642 /** Get one element of a repeated extension. */ 643 @Override 644 @SuppressWarnings("unchecked") 645 public final <Type> Type getExtension( 646 final ExtensionLite<MessageType, List<Type>> extension, final int index) { 647 GeneratedExtension<MessageType, List<Type>> extensionLite = 648 checkIsLite(extension); 649 650 verifyExtensionContainingType(extensionLite); 651 return (Type) extensionLite.singularFromFieldSetType( 652 extensions.getRepeatedField(extensionLite.descriptor, index)); 653 } 654 655 /** Called by subclasses to check if all extensions are initialized. */ 656 protected boolean extensionsAreInitialized() { 657 return extensions.isInitialized(); 658 } 659 660 @Override 661 protected final void makeImmutable() { 662 super.makeImmutable(); 663 664 extensions.makeImmutable(); 665 } 666 667 /** 668 * Used by subclasses to serialize extensions. Extension ranges may be 669 * interleaved with field numbers, but we must write them in canonical 670 * (sorted by field number) order. ExtensionWriter helps us write 671 * individual ranges of extensions at once. 672 */ 673 protected class ExtensionWriter { 674 // Imagine how much simpler this code would be if Java iterators had 675 // a way to get the next element without advancing the iterator. 676 677 private final Iterator<Map.Entry<ExtensionDescriptor, Object>> iter = 678 extensions.iterator(); 679 private Map.Entry<ExtensionDescriptor, Object> next; 680 private final boolean messageSetWireFormat; 681 682 private ExtensionWriter(boolean messageSetWireFormat) { 683 if (iter.hasNext()) { 684 next = iter.next(); 685 } 686 this.messageSetWireFormat = messageSetWireFormat; 687 } 688 689 public void writeUntil(final int end, final CodedOutputStream output) 690 throws IOException { 691 while (next != null && next.getKey().getNumber() < end) { 692 ExtensionDescriptor extension = next.getKey(); 693 if (messageSetWireFormat && extension.getLiteJavaType() == 694 WireFormat.JavaType.MESSAGE && 695 !extension.isRepeated()) { 696 output.writeMessageSetExtension(extension.getNumber(), 697 (MessageLite) next.getValue()); 698 } else { 699 FieldSet.writeField(extension, next.getValue(), output); 700 } 701 if (iter.hasNext()) { 702 next = iter.next(); 703 } else { 704 next = null; 705 } 706 } 707 } 708 } 709 710 protected ExtensionWriter newExtensionWriter() { 711 return new ExtensionWriter(false); 712 } 713 protected ExtensionWriter newMessageSetExtensionWriter() { 714 return new ExtensionWriter(true); 715 } 716 717 /** Called by subclasses to compute the size of extensions. */ 718 protected int extensionsSerializedSize() { 719 return extensions.getSerializedSize(); 720 } 721 protected int extensionsSerializedSizeAsMessageSet() { 722 return extensions.getMessageSetSerializedSize(); 723 } 724 } 725 726 /** 727 * Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}. 728 */ 729 @SuppressWarnings("unchecked") 730 public abstract static class ExtendableBuilder< 731 MessageType extends ExtendableMessage<MessageType, BuilderType>, 732 BuilderType extends ExtendableBuilder<MessageType, BuilderType>> 733 extends Builder<MessageType, BuilderType> 734 implements ExtendableMessageOrBuilder<MessageType, BuilderType> { 735 protected ExtendableBuilder(MessageType defaultInstance) { 736 super(defaultInstance); 737 738 // TODO(dweis): This is kind of an unnecessary clone since we construct a 739 // new instance in the parent constructor which makes the extensions 740 // immutable. This extra allocation shouldn't matter in practice 741 // though. 742 instance.extensions = instance.extensions.clone(); 743 } 744 745 // For immutable message conversion. 746 void internalSetExtensionSet(FieldSet<ExtensionDescriptor> extensions) { 747 copyOnWrite(); 748 instance.extensions = extensions; 749 } 750 751 @Override 752 protected void copyOnWrite() { 753 if (!isBuilt) { 754 return; 755 } 756 757 super.copyOnWrite(); 758 instance.extensions = instance.extensions.clone(); 759 } 760 761 @Override 762 public final MessageType buildPartial() { 763 if (isBuilt) { 764 return instance; 765 } 766 767 instance.extensions.makeImmutable(); 768 return super.buildPartial(); 769 } 770 771 private void verifyExtensionContainingType( 772 final GeneratedExtension<MessageType, ?> extension) { 773 if (extension.getContainingTypeDefaultInstance() != 774 getDefaultInstanceForType()) { 775 // This can only happen if someone uses unchecked operations. 776 throw new IllegalArgumentException( 777 "This extension is for a different message type. Please make " + 778 "sure that you are not suppressing any generics type warnings."); 779 } 780 } 781 782 /** Check if a singular extension is present. */ 783 @Override 784 public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) { 785 return instance.hasExtension(extension); 786 } 787 788 /** Get the number of elements in a repeated extension. */ 789 @Override 790 public final <Type> int getExtensionCount( 791 final ExtensionLite<MessageType, List<Type>> extension) { 792 return instance.getExtensionCount(extension); 793 } 794 795 /** Get the value of an extension. */ 796 @Override 797 @SuppressWarnings("unchecked") 798 public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) { 799 return instance.getExtension(extension); 800 } 801 802 /** Get one element of a repeated extension. */ 803 @Override 804 @SuppressWarnings("unchecked") 805 public final <Type> Type getExtension( 806 final ExtensionLite<MessageType, List<Type>> extension, final int index) { 807 return instance.getExtension(extension, index); 808 } 809 810 // This is implemented here only to work around an apparent bug in the 811 // Java compiler and/or build system. See bug #1898463. The mere presence 812 // of this dummy clone() implementation makes it go away. 813 @Override 814 public BuilderType clone() { 815 return super.clone(); 816 } 817 818 /** Set the value of an extension. */ 819 public final <Type> BuilderType setExtension( 820 final ExtensionLite<MessageType, Type> extension, 821 final Type value) { 822 GeneratedExtension<MessageType, Type> extensionLite = 823 checkIsLite(extension); 824 825 verifyExtensionContainingType(extensionLite); 826 copyOnWrite(); 827 instance.extensions.setField(extensionLite.descriptor, extensionLite.toFieldSetType(value)); 828 return (BuilderType) this; 829 } 830 831 /** Set the value of one element of a repeated extension. */ 832 public final <Type> BuilderType setExtension( 833 final ExtensionLite<MessageType, List<Type>> extension, 834 final int index, final Type value) { 835 GeneratedExtension<MessageType, List<Type>> extensionLite = 836 checkIsLite(extension); 837 838 verifyExtensionContainingType(extensionLite); 839 copyOnWrite(); 840 instance.extensions.setRepeatedField( 841 extensionLite.descriptor, index, extensionLite.singularToFieldSetType(value)); 842 return (BuilderType) this; 843 } 844 845 /** Append a value to a repeated extension. */ 846 public final <Type> BuilderType addExtension( 847 final ExtensionLite<MessageType, List<Type>> extension, 848 final Type value) { 849 GeneratedExtension<MessageType, List<Type>> extensionLite = 850 checkIsLite(extension); 851 852 verifyExtensionContainingType(extensionLite); 853 copyOnWrite(); 854 instance.extensions.addRepeatedField( 855 extensionLite.descriptor, extensionLite.singularToFieldSetType(value)); 856 return (BuilderType) this; 857 } 858 859 /** Clear an extension. */ 860 public final <Type> BuilderType clearExtension( 861 final ExtensionLite<MessageType, ?> extension) { 862 GeneratedExtension<MessageType, ?> extensionLite = checkIsLite(extension); 863 864 verifyExtensionContainingType(extensionLite); 865 copyOnWrite(); 866 instance.extensions.clearField(extensionLite.descriptor); 867 return (BuilderType) this; 868 } 869 } 870 871 // ----------------------------------------------------------------- 872 873 /** For use by generated code only. */ 874 public static <ContainingType extends MessageLite, Type> 875 GeneratedExtension<ContainingType, Type> 876 newSingularGeneratedExtension( 877 final ContainingType containingTypeDefaultInstance, 878 final Type defaultValue, 879 final MessageLite messageDefaultInstance, 880 final Internal.EnumLiteMap<?> enumTypeMap, 881 final int number, 882 final WireFormat.FieldType type, 883 final Class singularType) { 884 return new GeneratedExtension<ContainingType, Type>( 885 containingTypeDefaultInstance, 886 defaultValue, 887 messageDefaultInstance, 888 new ExtensionDescriptor(enumTypeMap, number, type, 889 false /* isRepeated */, 890 false /* isPacked */), 891 singularType); 892 } 893 894 /** For use by generated code only. */ 895 public static <ContainingType extends MessageLite, Type> 896 GeneratedExtension<ContainingType, Type> 897 newRepeatedGeneratedExtension( 898 final ContainingType containingTypeDefaultInstance, 899 final MessageLite messageDefaultInstance, 900 final Internal.EnumLiteMap<?> enumTypeMap, 901 final int number, 902 final WireFormat.FieldType type, 903 final boolean isPacked, 904 final Class singularType) { 905 @SuppressWarnings("unchecked") // Subclasses ensure Type is a List 906 Type emptyList = (Type) Collections.emptyList(); 907 return new GeneratedExtension<ContainingType, Type>( 908 containingTypeDefaultInstance, 909 emptyList, 910 messageDefaultInstance, 911 new ExtensionDescriptor( 912 enumTypeMap, number, type, true /* isRepeated */, isPacked), 913 singularType); 914 } 915 916 static final class ExtensionDescriptor 917 implements FieldSet.FieldDescriptorLite< 918 ExtensionDescriptor> { 919 ExtensionDescriptor( 920 final Internal.EnumLiteMap<?> enumTypeMap, 921 final int number, 922 final WireFormat.FieldType type, 923 final boolean isRepeated, 924 final boolean isPacked) { 925 this.enumTypeMap = enumTypeMap; 926 this.number = number; 927 this.type = type; 928 this.isRepeated = isRepeated; 929 this.isPacked = isPacked; 930 } 931 932 final Internal.EnumLiteMap<?> enumTypeMap; 933 final int number; 934 final WireFormat.FieldType type; 935 final boolean isRepeated; 936 final boolean isPacked; 937 938 @Override 939 public int getNumber() { 940 return number; 941 } 942 943 @Override 944 public WireFormat.FieldType getLiteType() { 945 return type; 946 } 947 948 @Override 949 public WireFormat.JavaType getLiteJavaType() { 950 return type.getJavaType(); 951 } 952 953 @Override 954 public boolean isRepeated() { 955 return isRepeated; 956 } 957 958 @Override 959 public boolean isPacked() { 960 return isPacked; 961 } 962 963 @Override 964 public Internal.EnumLiteMap<?> getEnumType() { 965 return enumTypeMap; 966 } 967 968 @Override 969 @SuppressWarnings("unchecked") 970 public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) { 971 return ((Builder) to).mergeFrom((GeneratedMessageLite) from); 972 } 973 974 975 @Override 976 public int compareTo(ExtensionDescriptor other) { 977 return number - other.number; 978 } 979 } 980 981 // ================================================================= 982 983 /** Calls Class.getMethod and throws a RuntimeException if it fails. */ 984 @SuppressWarnings("unchecked") 985 static Method getMethodOrDie(Class clazz, String name, Class... params) { 986 try { 987 return clazz.getMethod(name, params); 988 } catch (NoSuchMethodException e) { 989 throw new RuntimeException( 990 "Generated message class \"" + clazz.getName() + 991 "\" missing method \"" + name + "\".", e); 992 } 993 } 994 995 /** Calls invoke and throws a RuntimeException if it fails. */ 996 static Object invokeOrDie(Method method, Object object, Object... params) { 997 try { 998 return method.invoke(object, params); 999 } catch (IllegalAccessException e) { 1000 throw new RuntimeException( 1001 "Couldn't use Java reflection to implement protocol message " + 1002 "reflection.", e); 1003 } catch (InvocationTargetException e) { 1004 final Throwable cause = e.getCause(); 1005 if (cause instanceof RuntimeException) { 1006 throw (RuntimeException) cause; 1007 } else if (cause instanceof Error) { 1008 throw (Error) cause; 1009 } else { 1010 throw new RuntimeException( 1011 "Unexpected exception thrown by generated accessor method.", cause); 1012 } 1013 } 1014 } 1015 1016 /** 1017 * Lite equivalent to {@link GeneratedMessage.GeneratedExtension}. 1018 * 1019 * Users should ignore the contents of this class and only use objects of 1020 * this type as parameters to extension accessors and ExtensionRegistry.add(). 1021 */ 1022 public static class GeneratedExtension< 1023 ContainingType extends MessageLite, Type> 1024 extends ExtensionLite<ContainingType, Type> { 1025 1026 /** 1027 * Create a new instance with the given parameters. 1028 * 1029 * The last parameter {@code singularType} is only needed for enum types. 1030 * We store integer values for enum types in a {@link ExtendableMessage} 1031 * and use Java reflection to convert an integer value back into a concrete 1032 * enum object. 1033 */ 1034 GeneratedExtension( 1035 final ContainingType containingTypeDefaultInstance, 1036 final Type defaultValue, 1037 final MessageLite messageDefaultInstance, 1038 final ExtensionDescriptor descriptor, 1039 final Class singularType) { 1040 // Defensive checks to verify the correct initialization order of 1041 // GeneratedExtensions and their related GeneratedMessages. 1042 if (containingTypeDefaultInstance == null) { 1043 throw new IllegalArgumentException( 1044 "Null containingTypeDefaultInstance"); 1045 } 1046 if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE && 1047 messageDefaultInstance == null) { 1048 throw new IllegalArgumentException( 1049 "Null messageDefaultInstance"); 1050 } 1051 this.containingTypeDefaultInstance = containingTypeDefaultInstance; 1052 this.defaultValue = defaultValue; 1053 this.messageDefaultInstance = messageDefaultInstance; 1054 this.descriptor = descriptor; 1055 } 1056 1057 final ContainingType containingTypeDefaultInstance; 1058 final Type defaultValue; 1059 final MessageLite messageDefaultInstance; 1060 final ExtensionDescriptor descriptor; 1061 1062 /** 1063 * Default instance of the type being extended, used to identify that type. 1064 */ 1065 public ContainingType getContainingTypeDefaultInstance() { 1066 return containingTypeDefaultInstance; 1067 } 1068 1069 /** Get the field number. */ 1070 @Override 1071 public int getNumber() { 1072 return descriptor.getNumber(); 1073 } 1074 1075 1076 /** 1077 * If the extension is an embedded message or group, returns the default 1078 * instance of the message. 1079 */ 1080 @Override 1081 public MessageLite getMessageDefaultInstance() { 1082 return messageDefaultInstance; 1083 } 1084 1085 @SuppressWarnings("unchecked") 1086 Object fromFieldSetType(final Object value) { 1087 if (descriptor.isRepeated()) { 1088 if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) { 1089 final List result = new ArrayList(); 1090 for (final Object element : (List) value) { 1091 result.add(singularFromFieldSetType(element)); 1092 } 1093 return result; 1094 } else { 1095 return value; 1096 } 1097 } else { 1098 return singularFromFieldSetType(value); 1099 } 1100 } 1101 1102 Object singularFromFieldSetType(final Object value) { 1103 if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) { 1104 return descriptor.enumTypeMap.findValueByNumber((Integer) value); 1105 } else { 1106 return value; 1107 } 1108 } 1109 1110 @SuppressWarnings("unchecked") 1111 Object toFieldSetType(final Object value) { 1112 if (descriptor.isRepeated()) { 1113 if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) { 1114 final List result = new ArrayList(); 1115 for (final Object element : (List) value) { 1116 result.add(singularToFieldSetType(element)); 1117 } 1118 return result; 1119 } else { 1120 return value; 1121 } 1122 } else { 1123 return singularToFieldSetType(value); 1124 } 1125 } 1126 1127 Object singularToFieldSetType(final Object value) { 1128 if (descriptor.getLiteJavaType() == WireFormat.JavaType.ENUM) { 1129 return ((Internal.EnumLite) value).getNumber(); 1130 } else { 1131 return value; 1132 } 1133 } 1134 1135 @Override 1136 public FieldType getLiteType() { 1137 return descriptor.getLiteType(); 1138 } 1139 1140 @Override 1141 public boolean isRepeated() { 1142 return descriptor.isRepeated; 1143 } 1144 1145 @Override 1146 public Type getDefaultValue() { 1147 return defaultValue; 1148 } 1149 } 1150 1151 /** 1152 * A serialized (serializable) form of the generated message. Stores the 1153 * message as a class name and a byte array. 1154 */ 1155 protected static final class SerializedForm implements Serializable { 1156 1157 public static SerializedForm of(MessageLite message) { 1158 return new SerializedForm(message); 1159 } 1160 1161 private static final long serialVersionUID = 0L; 1162 1163 private final String messageClassName; 1164 private final byte[] asBytes; 1165 1166 /** 1167 * Creates the serialized form by calling {@link com.google.protobuf.MessageLite#toByteArray}. 1168 * @param regularForm the message to serialize 1169 */ 1170 SerializedForm(MessageLite regularForm) { 1171 messageClassName = regularForm.getClass().getName(); 1172 asBytes = regularForm.toByteArray(); 1173 } 1174 1175 /** 1176 * When read from an ObjectInputStream, this method converts this object 1177 * back to the regular form. Part of Java's serialization magic. 1178 * @return a GeneratedMessage of the type that was serialized 1179 */ 1180 @SuppressWarnings("unchecked") 1181 protected Object readResolve() throws ObjectStreamException { 1182 try { 1183 Class<?> messageClass = Class.forName(messageClassName); 1184 java.lang.reflect.Field defaultInstanceField = 1185 messageClass.getDeclaredField("DEFAULT_INSTANCE"); 1186 defaultInstanceField.setAccessible(true); 1187 MessageLite defaultInstance = (MessageLite) defaultInstanceField.get(null); 1188 return defaultInstance.newBuilderForType() 1189 .mergeFrom(asBytes) 1190 .buildPartial(); 1191 } catch (ClassNotFoundException e) { 1192 throw new RuntimeException("Unable to find proto buffer class: " + messageClassName, e); 1193 } catch (NoSuchFieldException e) { 1194 throw new RuntimeException("Unable to find DEFAULT_INSTANCE in " + messageClassName, e); 1195 } catch (SecurityException e) { 1196 throw new RuntimeException("Unable to call DEFAULT_INSTANCE in " + messageClassName, e); 1197 } catch (IllegalAccessException e) { 1198 throw new RuntimeException("Unable to call parsePartialFrom", e); 1199 } catch (InvalidProtocolBufferException e) { 1200 throw new RuntimeException("Unable to understand proto buffer", e); 1201 } 1202 } 1203 } 1204 1205 /** 1206 * Checks that the {@link Extension} is Lite and returns it as a 1207 * {@link GeneratedExtension}. 1208 */ 1209 private static < 1210 MessageType extends ExtendableMessage<MessageType, BuilderType>, 1211 BuilderType extends ExtendableBuilder<MessageType, BuilderType>, 1212 T> 1213 GeneratedExtension<MessageType, T> checkIsLite( 1214 ExtensionLite<MessageType, T> extension) { 1215 if (!extension.isLite()) { 1216 throw new IllegalArgumentException("Expected a lite extension."); 1217 } 1218 1219 return (GeneratedExtension<MessageType, T>) extension; 1220 } 1221 1222 /** 1223 * A static helper method for checking if a message is initialized, optionally memoizing. 1224 * <p> 1225 * For use by generated code only. 1226 */ 1227 protected static final <T extends GeneratedMessageLite<T, ?>> boolean isInitialized( 1228 T message, boolean shouldMemoize) { 1229 return message.dynamicMethod(MethodToInvoke.IS_INITIALIZED, shouldMemoize) != null; 1230 } 1231 1232 protected static final <T extends GeneratedMessageLite<T, ?>> void makeImmutable(T message) { 1233 message.dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE); 1234 } 1235 1236 protected static IntList emptyIntList() { 1237 return IntArrayList.emptyList(); 1238 } 1239 1240 protected static IntList mutableCopy(IntList list) { 1241 int size = list.size(); 1242 return list.mutableCopyWithCapacity( 1243 size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); 1244 } 1245 1246 protected static LongList emptyLongList() { 1247 return LongArrayList.emptyList(); 1248 } 1249 1250 protected static LongList mutableCopy(LongList list) { 1251 int size = list.size(); 1252 return list.mutableCopyWithCapacity( 1253 size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); 1254 } 1255 1256 protected static FloatList emptyFloatList() { 1257 return FloatArrayList.emptyList(); 1258 } 1259 1260 protected static FloatList mutableCopy(FloatList list) { 1261 int size = list.size(); 1262 return list.mutableCopyWithCapacity( 1263 size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); 1264 } 1265 1266 protected static DoubleList emptyDoubleList() { 1267 return DoubleArrayList.emptyList(); 1268 } 1269 1270 protected static DoubleList mutableCopy(DoubleList list) { 1271 int size = list.size(); 1272 return list.mutableCopyWithCapacity( 1273 size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); 1274 } 1275 1276 protected static BooleanList emptyBooleanList() { 1277 return BooleanArrayList.emptyList(); 1278 } 1279 1280 protected static BooleanList mutableCopy(BooleanList list) { 1281 int size = list.size(); 1282 return list.mutableCopyWithCapacity( 1283 size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); 1284 } 1285 1286 protected static <E> ProtobufList<E> emptyProtobufList() { 1287 return ProtobufArrayList.emptyList(); 1288 } 1289 1290 protected static <E> ProtobufList<E> mutableCopy(ProtobufList<E> list) { 1291 int size = list.size(); 1292 return list.mutableCopyWithCapacity( 1293 size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); 1294 } 1295 1296 /** 1297 * A {@link Parser} implementation that delegates to the default instance. 1298 * <p> 1299 * For use by generated code only. 1300 */ 1301 protected static class DefaultInstanceBasedParser<T extends GeneratedMessageLite<T, ?>> 1302 extends AbstractParser<T> { 1303 1304 private T defaultInstance; 1305 1306 public DefaultInstanceBasedParser(T defaultInstance) { 1307 this.defaultInstance = defaultInstance; 1308 } 1309 1310 @Override 1311 public T parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) 1312 throws InvalidProtocolBufferException { 1313 return GeneratedMessageLite.parsePartialFrom(defaultInstance, input, extensionRegistry); 1314 } 1315 } 1316 1317 /** 1318 * A static helper method for parsing a partial from input using the extension registry and the 1319 * instance. 1320 */ 1321 // TODO(dweis): Should this verify that the last tag was 0? 1322 static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom( 1323 T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry) 1324 throws InvalidProtocolBufferException { 1325 @SuppressWarnings("unchecked") // Guaranteed by protoc 1326 T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); 1327 try { 1328 result.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry); 1329 result.makeImmutable(); 1330 } catch (RuntimeException e) { 1331 if (e.getCause() instanceof InvalidProtocolBufferException) { 1332 throw (InvalidProtocolBufferException) e.getCause(); 1333 } 1334 throw e; 1335 } 1336 return result; 1337 } 1338 1339 protected static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom( 1340 T defaultInstance, 1341 CodedInputStream input) 1342 throws InvalidProtocolBufferException { 1343 return parsePartialFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry()); 1344 } 1345 1346 /** 1347 * Helper method to check if message is initialized. 1348 * 1349 * @throws InvalidProtocolBufferException if it is not initialized. 1350 * @return The message to check. 1351 */ 1352 private static <T extends GeneratedMessageLite<T, ?>> T checkMessageInitialized(T message) 1353 throws InvalidProtocolBufferException { 1354 if (message != null && !message.isInitialized()) { 1355 throw message.newUninitializedMessageException() 1356 .asInvalidProtocolBufferException() 1357 .setUnfinishedMessage(message); 1358 } 1359 return message; 1360 } 1361 1362 // Validates last tag. 1363 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1364 T defaultInstance, ByteString data) 1365 throws InvalidProtocolBufferException { 1366 return checkMessageInitialized( 1367 parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry())); 1368 } 1369 1370 // Validates last tag. 1371 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1372 T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry) 1373 throws InvalidProtocolBufferException { 1374 return checkMessageInitialized(parsePartialFrom(defaultInstance, data, extensionRegistry)); 1375 } 1376 1377 // This is a special case since we want to verify that the last tag is 0. We assume we exhaust the 1378 // ByteString. 1379 private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom( 1380 T defaultInstance, ByteString data, ExtensionRegistryLite extensionRegistry) 1381 throws InvalidProtocolBufferException { 1382 T message; 1383 try { 1384 CodedInputStream input = data.newCodedInput(); 1385 message = parsePartialFrom(defaultInstance, input, extensionRegistry); 1386 try { 1387 input.checkLastTagWas(0); 1388 } catch (InvalidProtocolBufferException e) { 1389 throw e.setUnfinishedMessage(message); 1390 } 1391 return message; 1392 } catch (InvalidProtocolBufferException e) { 1393 throw e; 1394 } 1395 } 1396 1397 // This is a special case since we want to verify that the last tag is 0. We assume we exhaust the 1398 // ByteString. 1399 private static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom( 1400 T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry) 1401 throws InvalidProtocolBufferException { 1402 T message; 1403 try { 1404 CodedInputStream input = CodedInputStream.newInstance(data); 1405 message = parsePartialFrom(defaultInstance, input, extensionRegistry); 1406 try { 1407 input.checkLastTagWas(0); 1408 } catch (InvalidProtocolBufferException e) { 1409 throw e.setUnfinishedMessage(message); 1410 } 1411 return message; 1412 } catch (InvalidProtocolBufferException e) { 1413 throw e; 1414 } 1415 } 1416 1417 // Validates last tag. 1418 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1419 T defaultInstance, byte[] data) 1420 throws InvalidProtocolBufferException { 1421 return checkMessageInitialized( 1422 parsePartialFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry())); 1423 } 1424 1425 // Validates last tag. 1426 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1427 T defaultInstance, byte[] data, ExtensionRegistryLite extensionRegistry) 1428 throws InvalidProtocolBufferException { 1429 return checkMessageInitialized(parsePartialFrom(defaultInstance, data, extensionRegistry)); 1430 } 1431 1432 // Does not validate last tag. 1433 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1434 T defaultInstance, InputStream input) 1435 throws InvalidProtocolBufferException { 1436 return checkMessageInitialized( 1437 parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input), 1438 ExtensionRegistryLite.getEmptyRegistry())); 1439 } 1440 1441 // Does not validate last tag. 1442 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1443 T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry) 1444 throws InvalidProtocolBufferException { 1445 return checkMessageInitialized( 1446 parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input), extensionRegistry)); 1447 } 1448 1449 // Does not validate last tag. 1450 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1451 T defaultInstance, CodedInputStream input) 1452 throws InvalidProtocolBufferException { 1453 return parseFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry()); 1454 } 1455 1456 // Does not validate last tag. 1457 protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom( 1458 T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry) 1459 throws InvalidProtocolBufferException { 1460 return checkMessageInitialized( 1461 parsePartialFrom(defaultInstance, input, extensionRegistry)); 1462 } 1463 1464 // Validates last tag. 1465 protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom( 1466 T defaultInstance, InputStream input) 1467 throws InvalidProtocolBufferException { 1468 return checkMessageInitialized( 1469 parsePartialDelimitedFrom(defaultInstance, input, 1470 ExtensionRegistryLite.getEmptyRegistry())); 1471 } 1472 1473 // Validates last tag. 1474 protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom( 1475 T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry) 1476 throws InvalidProtocolBufferException { 1477 return checkMessageInitialized( 1478 parsePartialDelimitedFrom(defaultInstance, input, extensionRegistry)); 1479 } 1480 1481 private static <T extends GeneratedMessageLite<T, ?>> T parsePartialDelimitedFrom( 1482 T defaultInstance, 1483 InputStream input, 1484 ExtensionRegistryLite extensionRegistry) 1485 throws InvalidProtocolBufferException { 1486 int size; 1487 try { 1488 int firstByte = input.read(); 1489 if (firstByte == -1) { 1490 return null; 1491 } 1492 size = CodedInputStream.readRawVarint32(firstByte, input); 1493 } catch (IOException e) { 1494 throw new InvalidProtocolBufferException(e.getMessage()); 1495 } 1496 InputStream limitedInput = new LimitedInputStream(input, size); 1497 CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput); 1498 T message = parsePartialFrom(defaultInstance, codedInput, extensionRegistry); 1499 try { 1500 codedInput.checkLastTagWas(0); 1501 } catch (InvalidProtocolBufferException e) { 1502 throw e.setUnfinishedMessage(message); 1503 } 1504 return message; 1505 } 1506 1507 /** 1508 * An abstract visitor that the generated code calls into that we use to implement various 1509 * features. Fields that are not members of oneofs are always visited. Members of a oneof are only 1510 * visited when they are the set oneof case value on the "other" proto. The visitOneofNotSet 1511 * method is invoked if other's oneof case is not set. 1512 */ 1513 protected interface Visitor { 1514 boolean visitBoolean(boolean minePresent, boolean mine, boolean otherPresent, boolean other); 1515 int visitInt(boolean minePresent, int mine, boolean otherPresent, int other); 1516 double visitDouble(boolean minePresent, double mine, boolean otherPresent, double other); 1517 float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other); 1518 long visitLong(boolean minePresent, long mine, boolean otherPresent, long other); 1519 String visitString(boolean minePresent, String mine, boolean otherPresent, String other); 1520 ByteString visitByteString( 1521 boolean minePresent, ByteString mine, boolean otherPresent, ByteString other); 1522 1523 Object visitOneofBoolean(boolean minePresent, Object mine, Object other); 1524 Object visitOneofInt(boolean minePresent, Object mine, Object other); 1525 Object visitOneofDouble(boolean minePresent, Object mine, Object other); 1526 Object visitOneofFloat(boolean minePresent, Object mine, Object other); 1527 Object visitOneofLong(boolean minePresent, Object mine, Object other); 1528 Object visitOneofString(boolean minePresent, Object mine, Object other); 1529 Object visitOneofByteString(boolean minePresent, Object mine, Object other); 1530 Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other); 1531 Object visitOneofMessage(boolean minePresent, Object mine, Object other); 1532 void visitOneofNotSet(boolean minePresent); 1533 1534 /** 1535 * Message fields use null sentinals. 1536 */ 1537 <T extends MessageLite> T visitMessage(T mine, T other); 1538 LazyFieldLite visitLazyMessage( 1539 boolean minePresent, LazyFieldLite mine, boolean otherPresent, LazyFieldLite other); 1540 1541 <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other); 1542 BooleanList visitBooleanList(BooleanList mine, BooleanList other); 1543 IntList visitIntList(IntList mine, IntList other); 1544 DoubleList visitDoubleList(DoubleList mine, DoubleList other); 1545 FloatList visitFloatList(FloatList mine, FloatList other); 1546 LongList visitLongList(LongList mine, LongList other); 1547 FieldSet<ExtensionDescriptor> visitExtensions( 1548 FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other); 1549 UnknownFieldSetLite visitUnknownFields(UnknownFieldSetLite mine, UnknownFieldSetLite other); 1550 <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other); 1551 } 1552 1553 /** 1554 * Implements equals. Throws a {@link NotEqualsException} when not equal. 1555 */ 1556 static class EqualsVisitor implements Visitor { 1557 1558 static final class NotEqualsException extends RuntimeException {} 1559 1560 static final EqualsVisitor INSTANCE = new EqualsVisitor(); 1561 1562 static final NotEqualsException NOT_EQUALS = new NotEqualsException(); 1563 1564 private EqualsVisitor() {} 1565 1566 @Override 1567 public boolean visitBoolean( 1568 boolean minePresent, boolean mine, boolean otherPresent, boolean other) { 1569 if (minePresent != otherPresent || mine != other) { 1570 throw NOT_EQUALS; 1571 } 1572 return mine; 1573 } 1574 1575 @Override 1576 public int visitInt(boolean minePresent, int mine, boolean otherPresent, int other) { 1577 if (minePresent != otherPresent || mine != other) { 1578 throw NOT_EQUALS; 1579 } 1580 return mine; 1581 } 1582 1583 @Override 1584 public double visitDouble( 1585 boolean minePresent, double mine, boolean otherPresent, double other) { 1586 if (minePresent != otherPresent || mine != other) { 1587 throw NOT_EQUALS; 1588 } 1589 return mine; 1590 } 1591 1592 @Override 1593 public float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other) { 1594 if (minePresent != otherPresent || mine != other) { 1595 throw NOT_EQUALS; 1596 } 1597 return mine; 1598 } 1599 1600 @Override 1601 public long visitLong(boolean minePresent, long mine, boolean otherPresent, long other) { 1602 if (minePresent != otherPresent || mine != other) { 1603 throw NOT_EQUALS; 1604 } 1605 return mine; 1606 } 1607 1608 @Override 1609 public String visitString( 1610 boolean minePresent, String mine, boolean otherPresent, String other) { 1611 if (minePresent != otherPresent || !mine.equals(other)) { 1612 throw NOT_EQUALS; 1613 } 1614 return mine; 1615 } 1616 1617 @Override 1618 public ByteString visitByteString( 1619 boolean minePresent, ByteString mine, boolean otherPresent, ByteString other) { 1620 if (minePresent != otherPresent || !mine.equals(other)) { 1621 throw NOT_EQUALS; 1622 } 1623 return mine; 1624 } 1625 1626 @Override 1627 public Object visitOneofBoolean(boolean minePresent, Object mine, Object other) { 1628 if (minePresent && mine.equals(other)) { 1629 return mine; 1630 } 1631 throw NOT_EQUALS; 1632 } 1633 1634 @Override 1635 public Object visitOneofInt(boolean minePresent, Object mine, Object other) { 1636 if (minePresent && mine.equals(other)) { 1637 return mine; 1638 } 1639 throw NOT_EQUALS; 1640 } 1641 1642 @Override 1643 public Object visitOneofDouble(boolean minePresent, Object mine, Object other) { 1644 if (minePresent && mine.equals(other)) { 1645 return mine; 1646 } 1647 throw NOT_EQUALS; 1648 } 1649 1650 @Override 1651 public Object visitOneofFloat(boolean minePresent, Object mine, Object other) { 1652 if (minePresent && mine.equals(other)) { 1653 return mine; 1654 } 1655 throw NOT_EQUALS; 1656 } 1657 1658 @Override 1659 public Object visitOneofLong(boolean minePresent, Object mine, Object other) { 1660 if (minePresent && mine.equals(other)) { 1661 return mine; 1662 } 1663 throw NOT_EQUALS; 1664 } 1665 1666 @Override 1667 public Object visitOneofString(boolean minePresent, Object mine, Object other) { 1668 if (minePresent && mine.equals(other)) { 1669 return mine; 1670 } 1671 throw NOT_EQUALS; 1672 } 1673 1674 @Override 1675 public Object visitOneofByteString(boolean minePresent, Object mine, Object other) { 1676 if (minePresent && mine.equals(other)) { 1677 return mine; 1678 } 1679 throw NOT_EQUALS; 1680 } 1681 1682 @Override 1683 public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) { 1684 if (minePresent && mine.equals(other)) { 1685 return mine; 1686 } 1687 throw NOT_EQUALS; 1688 } 1689 1690 @Override 1691 public Object visitOneofMessage(boolean minePresent, Object mine, Object other) { 1692 if (minePresent && ((GeneratedMessageLite<?, ?>) mine).equals(this, (MessageLite) other)) { 1693 return mine; 1694 } 1695 throw NOT_EQUALS; 1696 } 1697 1698 @Override 1699 public void visitOneofNotSet(boolean minePresent) { 1700 if (minePresent) { 1701 throw NOT_EQUALS; 1702 } 1703 } 1704 1705 @Override 1706 public <T extends MessageLite> T visitMessage(T mine, T other) { 1707 if (mine == null && other == null) { 1708 return null; 1709 } 1710 1711 if (mine == null || other == null) { 1712 throw NOT_EQUALS; 1713 } 1714 1715 ((GeneratedMessageLite<?, ?>) mine).equals(this, other); 1716 1717 return mine; 1718 } 1719 1720 @Override 1721 public LazyFieldLite visitLazyMessage( 1722 boolean minePresent, LazyFieldLite mine, boolean otherPresent, LazyFieldLite other) { 1723 if (!minePresent && !otherPresent) { 1724 return mine; 1725 } else if (minePresent && otherPresent && mine.equals(other)) { 1726 return mine; 1727 } 1728 throw NOT_EQUALS; 1729 } 1730 1731 @Override 1732 public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) { 1733 if (!mine.equals(other)) { 1734 throw NOT_EQUALS; 1735 } 1736 return mine; 1737 } 1738 1739 @Override 1740 public BooleanList visitBooleanList(BooleanList mine, BooleanList other) { 1741 if (!mine.equals(other)) { 1742 throw NOT_EQUALS; 1743 } 1744 return mine; 1745 } 1746 1747 @Override 1748 public IntList visitIntList(IntList mine, IntList other) { 1749 if (!mine.equals(other)) { 1750 throw NOT_EQUALS; 1751 } 1752 return mine; 1753 } 1754 1755 @Override 1756 public DoubleList visitDoubleList(DoubleList mine, DoubleList other) { 1757 if (!mine.equals(other)) { 1758 throw NOT_EQUALS; 1759 } 1760 return mine; 1761 } 1762 1763 @Override 1764 public FloatList visitFloatList(FloatList mine, FloatList other) { 1765 if (!mine.equals(other)) { 1766 throw NOT_EQUALS; 1767 } 1768 return mine; 1769 } 1770 1771 @Override 1772 public LongList visitLongList(LongList mine, LongList other) { 1773 if (!mine.equals(other)) { 1774 throw NOT_EQUALS; 1775 } 1776 return mine; 1777 } 1778 1779 @Override 1780 public FieldSet<ExtensionDescriptor> visitExtensions( 1781 FieldSet<ExtensionDescriptor> mine, 1782 FieldSet<ExtensionDescriptor> other) { 1783 if (!mine.equals(other)) { 1784 throw NOT_EQUALS; 1785 } 1786 return mine; 1787 } 1788 1789 @Override 1790 public UnknownFieldSetLite visitUnknownFields( 1791 UnknownFieldSetLite mine, 1792 UnknownFieldSetLite other) { 1793 if (!mine.equals(other)) { 1794 throw NOT_EQUALS; 1795 } 1796 return mine; 1797 } 1798 1799 @Override 1800 public <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other) { 1801 if (!mine.equals(other)) { 1802 throw NOT_EQUALS; 1803 } 1804 return mine; 1805 } 1806 } 1807 1808 /** 1809 * Implements hashCode by accumulating state. 1810 */ 1811 private static class HashCodeVisitor implements Visitor { 1812 1813 // The caller must ensure that the visitor is invoked parameterized with this and this such that 1814 // other is this. This is required due to how oneof cases are handled. See the class comment 1815 // on Visitor for more information. 1816 1817 private int hashCode = 0; 1818 1819 @Override 1820 public boolean visitBoolean( 1821 boolean minePresent, boolean mine, boolean otherPresent, boolean other) { 1822 hashCode = (53 * hashCode) + Internal.hashBoolean(mine); 1823 return mine; 1824 } 1825 1826 @Override 1827 public int visitInt(boolean minePresent, int mine, boolean otherPresent, int other) { 1828 hashCode = (53 * hashCode) + mine; 1829 return mine; 1830 } 1831 1832 @Override 1833 public double visitDouble( 1834 boolean minePresent, double mine, boolean otherPresent, double other) { 1835 hashCode = (53 * hashCode) + Internal.hashLong(Double.doubleToLongBits(mine)); 1836 return mine; 1837 } 1838 1839 @Override 1840 public float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other) { 1841 hashCode = (53 * hashCode) + Float.floatToIntBits(mine); 1842 return mine; 1843 } 1844 1845 @Override 1846 public long visitLong(boolean minePresent, long mine, boolean otherPresent, long other) { 1847 hashCode = (53 * hashCode) + Internal.hashLong(mine); 1848 return mine; 1849 } 1850 1851 @Override 1852 public String visitString( 1853 boolean minePresent, String mine, boolean otherPresent, String other) { 1854 hashCode = (53 * hashCode) + mine.hashCode(); 1855 return mine; 1856 } 1857 1858 @Override 1859 public ByteString visitByteString( 1860 boolean minePresent, ByteString mine, boolean otherPresent, ByteString other) { 1861 hashCode = (53 * hashCode) + mine.hashCode(); 1862 return mine; 1863 } 1864 1865 @Override 1866 public Object visitOneofBoolean(boolean minePresent, Object mine, Object other) { 1867 hashCode = (53 * hashCode) + Internal.hashBoolean(((Boolean) mine)); 1868 return mine; 1869 } 1870 1871 @Override 1872 public Object visitOneofInt(boolean minePresent, Object mine, Object other) { 1873 hashCode = (53 * hashCode) + (Integer) mine; 1874 return mine; 1875 } 1876 1877 @Override 1878 public Object visitOneofDouble(boolean minePresent, Object mine, Object other) { 1879 hashCode = (53 * hashCode) + Internal.hashLong(Double.doubleToLongBits((Double) mine)); 1880 return mine; 1881 } 1882 1883 @Override 1884 public Object visitOneofFloat(boolean minePresent, Object mine, Object other) { 1885 hashCode = (53 * hashCode) + Float.floatToIntBits((Float) mine); 1886 return mine; 1887 } 1888 1889 @Override 1890 public Object visitOneofLong(boolean minePresent, Object mine, Object other) { 1891 hashCode = (53 * hashCode) + Internal.hashLong((Long) mine); 1892 return mine; 1893 } 1894 1895 @Override 1896 public Object visitOneofString(boolean minePresent, Object mine, Object other) { 1897 hashCode = (53 * hashCode) + mine.hashCode(); 1898 return mine; 1899 } 1900 1901 @Override 1902 public Object visitOneofByteString(boolean minePresent, Object mine, Object other) { 1903 hashCode = (53 * hashCode) + mine.hashCode(); 1904 return mine; 1905 } 1906 1907 @Override 1908 public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) { 1909 hashCode = (53 * hashCode) + mine.hashCode(); 1910 return mine; 1911 } 1912 1913 @Override 1914 public Object visitOneofMessage(boolean minePresent, Object mine, Object other) { 1915 return visitMessage((MessageLite) mine, (MessageLite) other); 1916 } 1917 1918 @Override 1919 public void visitOneofNotSet(boolean minePresent) { 1920 if (minePresent) { 1921 throw new IllegalStateException(); // Can't happen if other == this. 1922 } 1923 } 1924 1925 @Override 1926 public <T extends MessageLite> T visitMessage(T mine, T other) { 1927 final int protoHash; 1928 if (mine != null) { 1929 if (mine instanceof GeneratedMessageLite) { 1930 protoHash = ((GeneratedMessageLite) mine).hashCode(this); 1931 } else { 1932 protoHash = mine.hashCode(); 1933 } 1934 } else { 1935 protoHash = 37; 1936 } 1937 hashCode = (53 * hashCode) + protoHash; 1938 return mine; 1939 } 1940 1941 @Override 1942 public LazyFieldLite visitLazyMessage( 1943 boolean minePresent, LazyFieldLite mine, boolean otherPresent, LazyFieldLite other) { 1944 hashCode = (53 * hashCode) + mine.hashCode(); 1945 return mine; 1946 } 1947 1948 @Override 1949 public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) { 1950 hashCode = (53 * hashCode) + mine.hashCode(); 1951 return mine; 1952 } 1953 1954 @Override 1955 public BooleanList visitBooleanList(BooleanList mine, BooleanList other) { 1956 hashCode = (53 * hashCode) + mine.hashCode(); 1957 return mine; 1958 } 1959 1960 @Override 1961 public IntList visitIntList(IntList mine, IntList other) { 1962 hashCode = (53 * hashCode) + mine.hashCode(); 1963 return mine; 1964 } 1965 1966 @Override 1967 public DoubleList visitDoubleList(DoubleList mine, DoubleList other) { 1968 hashCode = (53 * hashCode) + mine.hashCode(); 1969 return mine; 1970 } 1971 1972 @Override 1973 public FloatList visitFloatList(FloatList mine, FloatList other) { 1974 hashCode = (53 * hashCode) + mine.hashCode(); 1975 return mine; 1976 } 1977 1978 @Override 1979 public LongList visitLongList(LongList mine, LongList other) { 1980 hashCode = (53 * hashCode) + mine.hashCode(); 1981 return mine; 1982 } 1983 1984 @Override 1985 public FieldSet<ExtensionDescriptor> visitExtensions( 1986 FieldSet<ExtensionDescriptor> mine, 1987 FieldSet<ExtensionDescriptor> other) { 1988 hashCode = (53 * hashCode) + mine.hashCode(); 1989 return mine; 1990 } 1991 1992 @Override 1993 public UnknownFieldSetLite visitUnknownFields( 1994 UnknownFieldSetLite mine, 1995 UnknownFieldSetLite other) { 1996 hashCode = (53 * hashCode) + mine.hashCode(); 1997 return mine; 1998 } 1999 2000 @Override 2001 public <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other) { 2002 hashCode = (53 * hashCode) + mine.hashCode(); 2003 return mine; 2004 } 2005 } 2006 2007 /** 2008 * Implements field merging semantics over the visitor interface. 2009 */ 2010 protected static class MergeFromVisitor implements Visitor { 2011 2012 public static final MergeFromVisitor INSTANCE = new MergeFromVisitor(); 2013 2014 private MergeFromVisitor() {} 2015 2016 @Override 2017 public boolean visitBoolean( 2018 boolean minePresent, boolean mine, boolean otherPresent, boolean other) { 2019 return otherPresent ? other : mine; 2020 } 2021 2022 @Override 2023 public int visitInt(boolean minePresent, int mine, boolean otherPresent, int other) { 2024 return otherPresent ? other : mine; 2025 } 2026 2027 @Override 2028 public double visitDouble( 2029 boolean minePresent, double mine, boolean otherPresent, double other) { 2030 return otherPresent ? other : mine; 2031 } 2032 2033 @Override 2034 public float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other) { 2035 return otherPresent ? other : mine; 2036 } 2037 2038 @Override 2039 public long visitLong(boolean minePresent, long mine, boolean otherPresent, long other) { 2040 return otherPresent ? other : mine; 2041 } 2042 2043 @Override 2044 public String visitString( 2045 boolean minePresent, String mine, boolean otherPresent, String other) { 2046 return otherPresent ? other : mine; 2047 } 2048 2049 @Override 2050 public ByteString visitByteString( 2051 boolean minePresent, ByteString mine, boolean otherPresent, ByteString other) { 2052 return otherPresent ? other : mine; 2053 } 2054 2055 @Override 2056 public Object visitOneofBoolean(boolean minePresent, Object mine, Object other) { 2057 return other; 2058 } 2059 2060 @Override 2061 public Object visitOneofInt(boolean minePresent, Object mine, Object other) { 2062 return other; 2063 } 2064 2065 @Override 2066 public Object visitOneofDouble(boolean minePresent, Object mine, Object other) { 2067 return other; 2068 } 2069 2070 @Override 2071 public Object visitOneofFloat(boolean minePresent, Object mine, Object other) { 2072 return other; 2073 } 2074 2075 @Override 2076 public Object visitOneofLong(boolean minePresent, Object mine, Object other) { 2077 return other; 2078 } 2079 2080 @Override 2081 public Object visitOneofString(boolean minePresent, Object mine, Object other) { 2082 return other; 2083 } 2084 2085 @Override 2086 public Object visitOneofByteString(boolean minePresent, Object mine, Object other) { 2087 return other; 2088 } 2089 2090 @Override 2091 public Object visitOneofLazyMessage(boolean minePresent, Object mine, Object other) { 2092 if (minePresent) { 2093 LazyFieldLite lazy = (LazyFieldLite) mine; 2094 lazy.merge((LazyFieldLite) other); 2095 return lazy; 2096 } 2097 return other; 2098 } 2099 2100 @Override 2101 public Object visitOneofMessage(boolean minePresent, Object mine, Object other) { 2102 if (minePresent) { 2103 return visitMessage((MessageLite) mine, (MessageLite) other); 2104 } 2105 return other; 2106 } 2107 2108 @Override 2109 public void visitOneofNotSet(boolean minePresent) { 2110 return; 2111 } 2112 2113 @SuppressWarnings("unchecked") // Guaranteed by runtime. 2114 @Override 2115 public <T extends MessageLite> T visitMessage(T mine, T other) { 2116 if (mine != null && other != null) { 2117 return (T) mine.toBuilder().mergeFrom(other).build(); 2118 } 2119 2120 return mine != null ? mine : other; 2121 } 2122 2123 @Override 2124 public LazyFieldLite visitLazyMessage( 2125 boolean minePresent, LazyFieldLite mine, boolean otherPresent, LazyFieldLite other) { 2126 // LazyFieldLite's are never null so we can just copy across. Necessary to avoid leakage 2127 // from builder into immutable message. 2128 // TODO(dweis): Change to null sentinels? 2129 mine.merge(other); 2130 return mine; 2131 } 2132 2133 @Override 2134 public <T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other) { 2135 int size = mine.size(); 2136 int otherSize = other.size(); 2137 if (size > 0 && otherSize > 0) { 2138 if (!mine.isModifiable()) { 2139 mine = mine.mutableCopyWithCapacity(size + otherSize); 2140 } 2141 mine.addAll(other); 2142 } 2143 2144 return size > 0 ? mine : other; 2145 } 2146 2147 @Override 2148 public BooleanList visitBooleanList(BooleanList mine, BooleanList other) { 2149 int size = mine.size(); 2150 int otherSize = other.size(); 2151 if (size > 0 && otherSize > 0) { 2152 if (!mine.isModifiable()) { 2153 mine = mine.mutableCopyWithCapacity(size + otherSize); 2154 } 2155 mine.addAll(other); 2156 } 2157 2158 return size > 0 ? mine : other; 2159 } 2160 2161 @Override 2162 public IntList visitIntList(IntList mine, IntList other) { 2163 int size = mine.size(); 2164 int otherSize = other.size(); 2165 if (size > 0 && otherSize > 0) { 2166 if (!mine.isModifiable()) { 2167 mine = mine.mutableCopyWithCapacity(size + otherSize); 2168 } 2169 mine.addAll(other); 2170 } 2171 2172 return size > 0 ? mine : other; 2173 } 2174 2175 @Override 2176 public DoubleList visitDoubleList(DoubleList mine, DoubleList other) { 2177 int size = mine.size(); 2178 int otherSize = other.size(); 2179 if (size > 0 && otherSize > 0) { 2180 if (!mine.isModifiable()) { 2181 mine = mine.mutableCopyWithCapacity(size + otherSize); 2182 } 2183 mine.addAll(other); 2184 } 2185 2186 return size > 0 ? mine : other; 2187 } 2188 2189 @Override 2190 public FloatList visitFloatList(FloatList mine, FloatList other) { 2191 int size = mine.size(); 2192 int otherSize = other.size(); 2193 if (size > 0 && otherSize > 0) { 2194 if (!mine.isModifiable()) { 2195 mine = mine.mutableCopyWithCapacity(size + otherSize); 2196 } 2197 mine.addAll(other); 2198 } 2199 2200 return size > 0 ? mine : other; 2201 } 2202 2203 @Override 2204 public LongList visitLongList(LongList mine, LongList other) { 2205 int size = mine.size(); 2206 int otherSize = other.size(); 2207 if (size > 0 && otherSize > 0) { 2208 if (!mine.isModifiable()) { 2209 mine = mine.mutableCopyWithCapacity(size + otherSize); 2210 } 2211 mine.addAll(other); 2212 } 2213 2214 return size > 0 ? mine : other; 2215 } 2216 2217 @Override 2218 public FieldSet<ExtensionDescriptor> visitExtensions( 2219 FieldSet<ExtensionDescriptor> mine, 2220 FieldSet<ExtensionDescriptor> other) { 2221 if (mine.isImmutable()) { 2222 mine = mine.clone(); 2223 } 2224 mine.mergeFrom(other); 2225 return mine; 2226 } 2227 2228 @Override 2229 public UnknownFieldSetLite visitUnknownFields( 2230 UnknownFieldSetLite mine, 2231 UnknownFieldSetLite other) { 2232 return other == UnknownFieldSetLite.getDefaultInstance() 2233 ? mine : UnknownFieldSetLite.mutableCopyOf(mine, other); 2234 } 2235 2236 @Override 2237 public <K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other) { 2238 mine.mergeFrom(other); 2239 return mine; 2240 } 2241 } 2242 } 2243