diff options
27 files changed, 358 insertions, 1594 deletions
@@ -111,5 +111,7 @@ conformance/conformance.pb.h conformance/Conformance.pbobjc.h conformance/Conformance.pbobjc.m conformance/conformance.rb +conformance/google/ conformance/javac_middleman +conformance/lite/ conformance/protoc_middleman diff --git a/benchmarks/Makefile.am b/benchmarks/Makefile.am index 1e162eb1..f730afe5 100644 --- a/benchmarks/Makefile.am +++ b/benchmarks/Makefile.am @@ -40,6 +40,9 @@ CLEANFILES = \ protoc_middleman2 \ dataset.* +MAINTAINERCLEANFILES = \ + Makefile.in + if USE_EXTERNAL_PROTOC protoc_middleman: $(benchmarks_protoc_inputs) diff --git a/conformance/Makefile.am b/conformance/Makefile.am index abb1c00d..31a9e408 100644 --- a/conformance/Makefile.am +++ b/conformance/Makefile.am @@ -17,12 +17,114 @@ protoc_outputs = \ conformance.pb.h other_language_protoc_outputs = \ + conformance_pb2.py \ + Conformance.pbobjc.h \ + Conformance.pbobjc.m \ conformance.rb \ + com/google/protobuf/Any.java \ + com/google/protobuf/AnyOrBuilder.java \ + com/google/protobuf/AnyProto.java \ + com/google/protobuf/BoolValue.java \ + com/google/protobuf/BoolValueOrBuilder.java \ + com/google/protobuf/BytesValue.java \ + com/google/protobuf/BytesValueOrBuilder.java \ com/google/protobuf/conformance/Conformance.java \ + com/google/protobuf/DoubleValue.java \ + com/google/protobuf/DoubleValueOrBuilder.java \ + com/google/protobuf/Duration.java \ + com/google/protobuf/DurationOrBuilder.java \ + com/google/protobuf/DurationProto.java \ + com/google/protobuf/FieldMask.java \ + com/google/protobuf/FieldMaskOrBuilder.java \ + com/google/protobuf/FieldMaskProto.java \ + com/google/protobuf/FloatValue.java \ + com/google/protobuf/FloatValueOrBuilder.java \ + com/google/protobuf/Int32Value.java \ + com/google/protobuf/Int32ValueOrBuilder.java \ + com/google/protobuf/Int64Value.java \ + com/google/protobuf/Int64ValueOrBuilder.java \ + com/google/protobuf/ListValue.java \ + com/google/protobuf/ListValueOrBuilder.java \ + com/google/protobuf/NullValue.java \ + com/google/protobuf/StringValue.java \ + com/google/protobuf/StringValueOrBuilder.java \ + com/google/protobuf/Struct.java \ + com/google/protobuf/StructOrBuilder.java \ + com/google/protobuf/StructProto.java \ + com/google/protobuf/Timestamp.java \ + com/google/protobuf/TimestampOrBuilder.java \ + com/google/protobuf/TimestampProto.java \ + com/google/protobuf/UInt32Value.java \ + com/google/protobuf/UInt32ValueOrBuilder.java \ + com/google/protobuf/UInt64Value.java \ + com/google/protobuf/UInt64ValueOrBuilder.java \ + com/google/protobuf/Value.java \ + com/google/protobuf/ValueOrBuilder.java \ + com/google/protobuf/WrappersProto.java \ + google/protobuf/any.pb.cc \ + google/protobuf/any.pb.h \ + google/protobuf/any.rb \ + google/protobuf/any_pb2.py \ + google/protobuf/duration.pb.cc \ + google/protobuf/duration.pb.h \ + google/protobuf/duration.rb \ + google/protobuf/duration_pb2.py \ + google/protobuf/field_mask.pb.cc \ + google/protobuf/field_mask.pb.h \ + google/protobuf/field_mask.rb \ + google/protobuf/field_mask_pb2.py \ + google/protobuf/struct.pb.cc \ + google/protobuf/struct.pb.h \ + google/protobuf/struct.rb \ + google/protobuf/struct_pb2.py \ + google/protobuf/timestamp.pb.cc \ + google/protobuf/timestamp.pb.h \ + google/protobuf/timestamp.rb \ + google/protobuf/timestamp_pb2.py \ + google/protobuf/wrappers.pb.cc \ + google/protobuf/wrappers.pb.h \ + google/protobuf/wrappers.rb \ + google/protobuf/wrappers_pb2.py \ + lite/com/google/protobuf/Any.java \ + lite/com/google/protobuf/AnyOrBuilder.java \ + lite/com/google/protobuf/AnyProto.java \ + lite/com/google/protobuf/BoolValue.java \ + lite/com/google/protobuf/BoolValueOrBuilder.java \ + lite/com/google/protobuf/BytesValue.java \ + lite/com/google/protobuf/BytesValueOrBuilder.java \ lite/com/google/protobuf/conformance/Conformance.java \ - conformance_pb2.py \ - Conformance.pbobjc.h \ - Conformance.pbobjc.m + lite/com/google/protobuf/DoubleValue.java \ + lite/com/google/protobuf/DoubleValueOrBuilder.java \ + lite/com/google/protobuf/Duration.java \ + lite/com/google/protobuf/DurationOrBuilder.java \ + lite/com/google/protobuf/DurationProto.java \ + lite/com/google/protobuf/FieldMask.java \ + lite/com/google/protobuf/FieldMaskOrBuilder.java \ + lite/com/google/protobuf/FieldMaskProto.java \ + lite/com/google/protobuf/FloatValue.java \ + lite/com/google/protobuf/FloatValueOrBuilder.java \ + lite/com/google/protobuf/Int32Value.java \ + lite/com/google/protobuf/Int32ValueOrBuilder.java \ + lite/com/google/protobuf/Int64Value.java \ + lite/com/google/protobuf/Int64ValueOrBuilder.java \ + lite/com/google/protobuf/ListValue.java \ + lite/com/google/protobuf/ListValueOrBuilder.java \ + lite/com/google/protobuf/NullValue.java \ + lite/com/google/protobuf/StringValue.java \ + lite/com/google/protobuf/StringValueOrBuilder.java \ + lite/com/google/protobuf/Struct.java \ + lite/com/google/protobuf/StructOrBuilder.java \ + lite/com/google/protobuf/StructProto.java \ + lite/com/google/protobuf/Timestamp.java \ + lite/com/google/protobuf/TimestampOrBuilder.java \ + lite/com/google/protobuf/TimestampProto.java \ + lite/com/google/protobuf/UInt32Value.java \ + lite/com/google/protobuf/UInt32ValueOrBuilder.java \ + lite/com/google/protobuf/UInt64Value.java \ + lite/com/google/protobuf/UInt64ValueOrBuilder.java \ + lite/com/google/protobuf/Value.java \ + lite/com/google/protobuf/ValueOrBuilder.java \ + lite/com/google/protobuf/WrappersProto.java bin_PROGRAMS = conformance-test-runner conformance-cpp diff --git a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs index 0b6cd7e6..827a7595 100644 --- a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs @@ -481,6 +481,15 @@ namespace Google.Protobuf } [Test] + public void AnyMessageType_CustomPrefix() + { + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10 }; + var any = Any.Pack(message, "foo.bar/baz"); + AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any)); + } + + [Test] public void AnyNested() { var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); diff --git a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs index 684f52b4..c3ad851b 100644 --- a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs @@ -811,6 +811,17 @@ namespace Google.Protobuf } [Test] + public void Any_CustomPrefix() + { + var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor); + var message = new TestAllTypes { SingleInt32 = 10 }; + var original = Any.Pack(message, "custom.prefix/middle-part"); + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest.TestAllTypes\", \"singleInt32\": 10 }"; + Assert.AreEqual(original, parser.Parse<Any>(json)); + } + + [Test] public void Any_UnknownType() { string json = "{ \"@type\": \"type.googleapis.com/bogus\" }"; diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs index f3593e5f..f21be7d9 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs @@ -47,6 +47,24 @@ namespace Google.Protobuf.WellKnownTypes } [Test] + public void Pack_WithCustomPrefix() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message, "foo.bar/baz"); + Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl); + Assert.AreEqual(message.CalculateSize(), any.Value.Length); + } + + [Test] + public void Pack_WithCustomPrefixTrailingSlash() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message, "foo.bar/baz/"); + Assert.AreEqual("foo.bar/baz/protobuf_unittest.TestAllTypes", any.TypeUrl); + Assert.AreEqual(message.CalculateSize(), any.Value.Length); + } + + [Test] public void Unpack_WrongType() { var message = SampleMessages.CreateFullTestAllTypes(); @@ -64,6 +82,15 @@ namespace Google.Protobuf.WellKnownTypes } [Test] + public void Unpack_CustomPrefix_Success() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var any = Any.Pack(message, "foo.bar/baz"); + var unpacked = any.Unpack<TestAllTypes>(); + Assert.AreEqual(message, unpacked); + } + + [Test] public void ToString_WithValues() { var message = SampleMessages.CreateFullTestAllTypes(); diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs index 5b7185dc..18d18be3 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs @@ -417,5 +417,12 @@ namespace Google.Protobuf.WellKnownTypes TestWellKnownTypes.Descriptor.Fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.Clear(message); Assert.IsNull(message.StringField); } + + [Test] + public void GivenBoolValueWhenPerformingRoundTripEncodingViaJsonThenShouldNotExpectObjectAtTopLevel() + { + var value = new BoolValue { Value = true }; + Assert.AreEqual(value, JsonParser.Default.Parse<BoolValue>(JsonFormatter.Default.Format(value))); + } } } diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs index 73a4f64b..83772473 100644 --- a/csharp/src/Google.Protobuf/JsonFormatter.cs +++ b/csharp/src/Google.Protobuf/JsonFormatter.cs @@ -567,7 +567,7 @@ namespace Google.Protobuf string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value); ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value); - string typeName = GetTypeName(typeUrl); + string typeName = Any.GetTypeName(typeUrl); MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName); if (descriptor == null) { @@ -608,17 +608,7 @@ namespace Google.Protobuf writer.Write(data.ToBase64()); writer.Write('"'); writer.Write(" }"); - } - - internal static string GetTypeName(String typeUrl) - { - string[] parts = typeUrl.Split('/'); - if (parts.Length != 2 || parts[0] != TypeUrlPrefix) - { - throw new InvalidProtocolBufferException($"Invalid type url: {typeUrl}"); - } - return parts[1]; - } + } private void WriteStruct(TextWriter writer, IMessage message) { diff --git a/csharp/src/Google.Protobuf/JsonParser.cs b/csharp/src/Google.Protobuf/JsonParser.cs index 80d3013d..6b6f2d9a 100644 --- a/csharp/src/Google.Protobuf/JsonParser.cs +++ b/csharp/src/Google.Protobuf/JsonParser.cs @@ -86,7 +86,8 @@ namespace Google.Protobuf { FloatValue.Descriptor.FullName, MergeWrapperField }, { DoubleValue.Descriptor.FullName, MergeWrapperField }, { BytesValue.Descriptor.FullName, MergeWrapperField }, - { StringValue.Descriptor.FullName, MergeWrapperField } + { StringValue.Descriptor.FullName, MergeWrapperField }, + { BoolValue.Descriptor.FullName, MergeWrapperField } }; // Convenience method to avoid having to repeat the same code multiple times in the above @@ -513,7 +514,7 @@ namespace Google.Protobuf throw new InvalidProtocolBufferException("Expected string value for Any.@type"); } string typeUrl = token.StringValue; - string typeName = JsonFormatter.GetTypeName(typeUrl); + string typeName = Any.GetTypeName(typeUrl); MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName); if (descriptor == null) diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs index 9d43856e..f4fac738 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs @@ -36,11 +36,27 @@ namespace Google.Protobuf.WellKnownTypes { public partial class Any { + private const string DefaultPrefix = "type.googleapis.com"; + // This could be moved to MessageDescriptor if we wanted to, but keeping it here means // all the Any-specific code is in the same place. - private static string GetTypeUrl(MessageDescriptor descriptor) + private static string GetTypeUrl(MessageDescriptor descriptor, string prefix) => + prefix.EndsWith("/") ? prefix + descriptor.FullName : prefix + "/" + descriptor.FullName; + + /// <summary> + /// Retrieves the type name for a type URL. This is always just the last part of the URL, + /// after the trailing slash. No validation of anything before the trailing slash is performed. + /// If the type URL does not include a slash, an empty string is returned rather than an exception + /// being thrown; this won't match any types, and the calling code is probably in a better position + /// to give a meaningful error. + /// There is no handling of fragments or queries at the moment. + /// </summary> + /// <param name="typeUrl">The URL to extract the type name from</param> + /// <returns>The type name</returns> + internal static string GetTypeName(string typeUrl) { - return "type.googleapis.com/" + descriptor.FullName; + int lastSlash = typeUrl.LastIndexOf('/'); + return lastSlash == -1 ? "" : typeUrl.Substring(lastSlash + 1); } /// <summary> @@ -55,25 +71,37 @@ namespace Google.Protobuf.WellKnownTypes // Note: this doesn't perform as well is it might. We could take a MessageParser<T> in an alternative overload, // which would be expected to perform slightly better... although the difference is likely to be negligible. T target = new T(); - string targetTypeUrl = GetTypeUrl(target.Descriptor); - if (TypeUrl != targetTypeUrl) + if (GetTypeName(TypeUrl) != target.Descriptor.FullName) { - throw new InvalidProtocolBufferException(string.Format("Type url for {0} is {1}; Any message's type url is {2}", - target.Descriptor.Name, targetTypeUrl, TypeUrl)); + throw new InvalidProtocolBufferException( + $"Full type name for {target.Descriptor.Name} is {target.Descriptor.FullName}; Any message's type url is {TypeUrl}"); } target.MergeFrom(Value); return target; } /// <summary> - /// Packs the specified message into an Any message. + /// Packs the specified message into an Any message using a type URL prefix of "type.googleapis.com". + /// </summary> + /// <param name="message">The message to pack.</param> + /// <returns>An Any message with the content and type URL of <paramref name="message"/>.</returns> + public static Any Pack(IMessage message) => Pack(message, DefaultPrefix); + + /// <summary> + /// Packs the specified message into an Any message using the specified type URL prefix. /// </summary> /// <param name="message">The message to pack.</param> + /// <param name="typeUrlPrefix">The prefix for the type URL.</param> /// <returns>An Any message with the content and type URL of <paramref name="message"/>.</returns> - public static Any Pack(IMessage message) + public static Any Pack(IMessage message, string typeUrlPrefix) { - ProtoPreconditions.CheckNotNull(message, "message"); - return new Any { TypeUrl = GetTypeUrl(message.Descriptor), Value = message.ToByteString() }; + ProtoPreconditions.CheckNotNull(message, nameof(message)); + ProtoPreconditions.CheckNotNull(typeUrlPrefix, nameof(typeUrlPrefix)); + return new Any + { + TypeUrl = GetTypeUrl(message.Descriptor, typeUrlPrefix), + Value = message.ToByteString() + }; } } } diff --git a/java/src/main/java/com/google/protobuf/AbstractMessage.java b/java/src/main/java/com/google/protobuf/AbstractMessage.java deleted file mode 100644 index 03c0d579..00000000 --- a/java/src/main/java/com/google/protobuf/AbstractMessage.java +++ /dev/null @@ -1,553 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package com.google.protobuf; - -import com.google.protobuf.Descriptors.EnumValueDescriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.OneofDescriptor; -import com.google.protobuf.Internal.EnumLite; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * A partial implementation of the {@link Message} interface which implements - * as many methods of that interface as possible in terms of other methods. - * - * @author kenton@google.com Kenton Varda - */ -public abstract class AbstractMessage - // TODO(dweis): Update GeneratedMessage to parameterize with MessageType and BuilderType. - extends AbstractMessageLite - implements Message { - - @Override - public boolean isInitialized() { - return MessageReflection.isInitialized(this); - } - - - @Override - public List<String> findInitializationErrors() { - return MessageReflection.findMissingFields(this); - } - - @Override - public String getInitializationErrorString() { - return MessageReflection.delimitWithCommas(findInitializationErrors()); - } - - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ - @Override - public boolean hasOneof(OneofDescriptor oneof) { - throw new UnsupportedOperationException("hasOneof() is not implemented."); - } - - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ - @Override - public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { - throw new UnsupportedOperationException( - "getOneofFieldDescriptor() is not implemented."); - } - - @Override - public final String toString() { - return TextFormat.printToString(this); - } - - @Override - public void writeTo(final CodedOutputStream output) throws IOException { - MessageReflection.writeMessageTo(this, getAllFields(), output, false); - } - - protected int memoizedSize = -1; - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) { - return size; - } - - memoizedSize = MessageReflection.getSerializedSize(this, getAllFields()); - return memoizedSize; - } - - @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(); - Descriptors.Descriptor descriptor = entry.getDescriptorForType(); - Descriptors.FieldDescriptor key = descriptor.findFieldByName("key"); - Descriptors.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 set 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 reprensent 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 EnumLite> list = (List<? extends EnumLite>) value; - hash = (53 * hash) + Internal.hashEnumList(list); - } else { - hash = (53 * hash) + Internal.hashEnum((EnumLite) value); - } - } - return hash; - } - - /** - * Package private helper method for AbstractParser to create - * UninitializedMessageException with missing field information. - */ - @Override - UninitializedMessageException newUninitializedMessageException() { - return Builder.newUninitializedMessageException(this); - } - - // ================================================================= - - /** - * A partial implementation of the {@link Message.Builder} interface which - * implements as many methods of that interface as possible in terms of - * other methods. - */ - @SuppressWarnings("unchecked") - public static abstract class Builder<BuilderType extends Builder<BuilderType>> - extends AbstractMessageLite.Builder - implements Message.Builder { - // The compiler produces an error if this is not declared explicitly. - @Override - public abstract BuilderType clone(); - - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ - @Override - public boolean hasOneof(OneofDescriptor oneof) { - throw new UnsupportedOperationException("hasOneof() is not implemented."); - } - - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ - @Override - public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { - throw new UnsupportedOperationException( - "getOneofFieldDescriptor() is not implemented."); - } - - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ - @Override - public BuilderType clearOneof(OneofDescriptor oneof) { - throw new UnsupportedOperationException("clearOneof() is not implemented."); - } - - @Override - public BuilderType clear() { - for (final Map.Entry<FieldDescriptor, Object> entry : - getAllFields().entrySet()) { - clearField(entry.getKey()); - } - return (BuilderType) this; - } - - @Override - public List<String> findInitializationErrors() { - return MessageReflection.findMissingFields(this); - } - - @Override - public String getInitializationErrorString() { - return MessageReflection.delimitWithCommas(findInitializationErrors()); - } - - @Override - protected BuilderType internalMergeFrom(AbstractMessageLite other) { - return mergeFrom((Message) other); - } - - @Override - public BuilderType mergeFrom(final Message other) { - if (other.getDescriptorForType() != getDescriptorForType()) { - throw new IllegalArgumentException( - "mergeFrom(Message) can only merge messages of the same type."); - } - - // Note: We don't attempt to verify that other's fields have valid - // types. Doing so would be a losing battle. We'd have to verify - // all sub-messages as well, and we'd have to make copies of all of - // them to insure that they don't change after verification (since - // the Message interface itself cannot enforce immutability of - // implementations). - // TODO(kenton): Provide a function somewhere called makeDeepCopy() - // which allows people to make secure deep copies of messages. - - for (final Map.Entry<FieldDescriptor, Object> entry : - other.getAllFields().entrySet()) { - final FieldDescriptor field = entry.getKey(); - if (field.isRepeated()) { - for (final Object element : (List)entry.getValue()) { - addRepeatedField(field, element); - } - } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { - final Message existingValue = (Message)getField(field); - if (existingValue == existingValue.getDefaultInstanceForType()) { - setField(field, entry.getValue()); - } else { - setField(field, - existingValue.newBuilderForType() - .mergeFrom(existingValue) - .mergeFrom((Message)entry.getValue()) - .build()); - } - } else { - setField(field, entry.getValue()); - } - } - - mergeUnknownFields(other.getUnknownFields()); - - return (BuilderType) this; - } - - @Override - public BuilderType mergeFrom(final CodedInputStream input) - throws IOException { - return mergeFrom(input, ExtensionRegistry.getEmptyRegistry()); - } - - @Override - public BuilderType mergeFrom( - final CodedInputStream input, - final ExtensionRegistryLite extensionRegistry) - throws IOException { - final UnknownFieldSet.Builder unknownFields = - UnknownFieldSet.newBuilder(getUnknownFields()); - while (true) { - final int tag = input.readTag(); - if (tag == 0) { - break; - } - - MessageReflection.BuilderAdapter builderAdapter = - new MessageReflection.BuilderAdapter(this); - if (!MessageReflection.mergeFieldFrom(input, unknownFields, - extensionRegistry, - getDescriptorForType(), - builderAdapter, - tag)) { - // end group tag - break; - } - } - setUnknownFields(unknownFields.build()); - return (BuilderType) this; - } - - @Override - public BuilderType mergeUnknownFields(final UnknownFieldSet unknownFields) { - setUnknownFields( - UnknownFieldSet.newBuilder(getUnknownFields()) - .mergeFrom(unknownFields) - .build()); - return (BuilderType) this; - } - - @Override - public Message.Builder getFieldBuilder(final FieldDescriptor field) { - throw new UnsupportedOperationException( - "getFieldBuilder() called on an unsupported message type."); - } - - @Override - public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) { - throw new UnsupportedOperationException( - "getRepeatedFieldBuilder() called on an unsupported message type."); - } - - @Override - public String toString() { - return TextFormat.printToString(this); - } - - /** - * Construct an UninitializedMessageException reporting missing fields in - * the given message. - */ - protected static UninitializedMessageException - newUninitializedMessageException(Message message) { - return new UninitializedMessageException( - MessageReflection.findMissingFields(message)); - } - - // =============================================================== - // The following definitions seem to be required in order to make javac - // not produce weird errors like: - // - // java/com/google/protobuf/DynamicMessage.java:203: types - // com.google.protobuf.AbstractMessage.Builder< - // com.google.protobuf.DynamicMessage.Builder> and - // com.google.protobuf.AbstractMessage.Builder< - // com.google.protobuf.DynamicMessage.Builder> are incompatible; both - // define mergeFrom(com.google.protobuf.ByteString), but with unrelated - // return types. - // - // Strangely, these lines are only needed if javac is invoked separately - // on AbstractMessage.java and AbstractMessageLite.java. If javac is - // invoked on both simultaneously, it works. (Or maybe the important - // point is whether or not DynamicMessage.java is compiled together with - // AbstractMessageLite.java -- not sure.) I suspect this is a compiler - // bug. - - @Override - public BuilderType mergeFrom(final ByteString data) - throws InvalidProtocolBufferException { - return (BuilderType) super.mergeFrom(data); - } - - @Override - public BuilderType mergeFrom( - final ByteString data, - final ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return (BuilderType) super.mergeFrom(data, extensionRegistry); - } - - @Override - public BuilderType mergeFrom(final byte[] data) - throws InvalidProtocolBufferException { - return (BuilderType) super.mergeFrom(data); - } - - @Override - public BuilderType mergeFrom( - final byte[] data, final int off, final int len) - throws InvalidProtocolBufferException { - return (BuilderType) super.mergeFrom(data, off, len); - } - - @Override - public BuilderType mergeFrom( - final byte[] data, - final ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return (BuilderType) super.mergeFrom(data, extensionRegistry); - } - - @Override - public BuilderType mergeFrom( - final byte[] data, final int off, final int len, - final ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return (BuilderType) super.mergeFrom(data, off, len, extensionRegistry); - } - - @Override - public BuilderType mergeFrom(final InputStream input) - throws IOException { - return (BuilderType) super.mergeFrom(input); - } - - @Override - public BuilderType mergeFrom( - final InputStream input, - final ExtensionRegistryLite extensionRegistry) - throws IOException { - return (BuilderType) super.mergeFrom(input, extensionRegistry); - } - - @Override - public boolean mergeDelimitedFrom(final InputStream input) - throws IOException { - return super.mergeDelimitedFrom(input); - } - - @Override - public boolean mergeDelimitedFrom( - final InputStream input, - final ExtensionRegistryLite extensionRegistry) - throws IOException { - return super.mergeDelimitedFrom(input, extensionRegistry); - } - } -} diff --git a/java/src/main/java/com/google/protobuf/AbstractMessageLite.java b/java/src/main/java/com/google/protobuf/AbstractMessageLite.java deleted file mode 100644 index 43736dd1..00000000 --- a/java/src/main/java/com/google/protobuf/AbstractMessageLite.java +++ /dev/null @@ -1,386 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package com.google.protobuf; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collection; - -/** - * A partial implementation of the {@link MessageLite} interface which - * implements as many methods of that interface as possible in terms of other - * methods. - * - * @author kenton@google.com Kenton Varda - */ -public abstract class AbstractMessageLite< - MessageType extends AbstractMessageLite<MessageType, BuilderType>, - BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>> - implements MessageLite { - protected int memoizedHashCode = 0; - - @Override - public ByteString toByteString() { - try { - final ByteString.CodedBuilder out = - ByteString.newCodedBuilder(getSerializedSize()); - writeTo(out.getCodedOutput()); - return out.build(); - } catch (IOException e) { - throw new RuntimeException( - "Serializing to a ByteString threw an IOException (should " + - "never happen).", e); - } - } - - @Override - 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( - "Serializing to a byte array threw an IOException " + - "(should never happen).", e); - } - } - - @Override - 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(); - } - - @Override - public void writeDelimitedTo(final OutputStream output) throws IOException { - final int serialized = getSerializedSize(); - final int bufferSize = CodedOutputStream.computePreferredBufferSize( - CodedOutputStream.computeRawVarint32Size(serialized) + serialized); - final CodedOutputStream codedOutput = - CodedOutputStream.newInstance(output, bufferSize); - codedOutput.writeRawVarint32(serialized); - writeTo(codedOutput); - codedOutput.flush(); - } - - - /** - * Package private helper method for AbstractParser to create - * UninitializedMessageException. - */ - UninitializedMessageException newUninitializedMessageException() { - return new UninitializedMessageException(this); - } - - protected static void checkByteStringIsUtf8(ByteString byteString) - throws IllegalArgumentException { - if (!byteString.isValidUtf8()) { - throw new IllegalArgumentException("Byte string is not UTF-8."); - } - } - - protected static <T> void addAll(final Iterable<T> values, - final Collection<? super T> list) { - Builder.addAll(values, list); - } - - /** - * A partial implementation of the {@link Message.Builder} interface which - * implements as many methods of that interface as possible in terms of - * other methods. - */ - @SuppressWarnings("unchecked") - public abstract static class Builder< - MessageType extends AbstractMessageLite<MessageType, BuilderType>, - BuilderType extends Builder<MessageType, BuilderType>> - implements MessageLite.Builder { - // The compiler produces an error if this is not declared explicitly. - @Override - public abstract BuilderType clone(); - - @Override - public BuilderType mergeFrom(final CodedInputStream input) throws IOException { - return mergeFrom(input, ExtensionRegistryLite.getEmptyRegistry()); - } - - // Re-defined here for return type covariance. - @Override - public abstract BuilderType mergeFrom( - final CodedInputStream input, final ExtensionRegistryLite extensionRegistry) - throws IOException; - - @Override - public BuilderType mergeFrom(final ByteString data) throws InvalidProtocolBufferException { - try { - final CodedInputStream input = data.newCodedInput(); - mergeFrom(input); - input.checkLastTagWas(0); - return (BuilderType) this; - } catch (InvalidProtocolBufferException e) { - throw e; - } catch (IOException e) { - throw new RuntimeException( - "Reading from a ByteString threw an IOException (should " + - "never happen).", e); - } - } - - @Override - public BuilderType mergeFrom( - final ByteString data, final ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - try { - final CodedInputStream input = data.newCodedInput(); - mergeFrom(input, extensionRegistry); - input.checkLastTagWas(0); - return (BuilderType) this; - } catch (InvalidProtocolBufferException e) { - throw e; - } catch (IOException e) { - throw new RuntimeException( - "Reading from a ByteString threw an IOException (should " + - "never happen).", e); - } - } - - @Override - public BuilderType mergeFrom(final byte[] data) throws InvalidProtocolBufferException { - return mergeFrom(data, 0, data.length); - } - - @Override - public BuilderType mergeFrom(final byte[] data, final int off, final int len) - throws InvalidProtocolBufferException { - try { - final CodedInputStream input = - CodedInputStream.newInstance(data, off, len); - mergeFrom(input); - input.checkLastTagWas(0); - return (BuilderType) this; - } catch (InvalidProtocolBufferException e) { - throw e; - } catch (IOException e) { - throw new RuntimeException( - "Reading from a byte array threw an IOException (should " + - "never happen).", e); - } - } - - @Override - public BuilderType mergeFrom(final byte[] data, final ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return mergeFrom(data, 0, data.length, extensionRegistry); - } - - @Override - public BuilderType mergeFrom( - final byte[] data, - final int off, - final int len, - final ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - try { - final CodedInputStream input = - CodedInputStream.newInstance(data, off, len); - mergeFrom(input, extensionRegistry); - input.checkLastTagWas(0); - return (BuilderType) this; - } catch (InvalidProtocolBufferException e) { - throw e; - } catch (IOException e) { - throw new RuntimeException( - "Reading from a byte array threw an IOException (should " + - "never happen).", e); - } - } - - @Override - public BuilderType mergeFrom(final InputStream input) throws IOException { - final CodedInputStream codedInput = CodedInputStream.newInstance(input); - mergeFrom(codedInput); - codedInput.checkLastTagWas(0); - return (BuilderType) this; - } - - @Override - public BuilderType mergeFrom( - final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException { - final CodedInputStream codedInput = CodedInputStream.newInstance(input); - mergeFrom(codedInput, extensionRegistry); - codedInput.checkLastTagWas(0); - return (BuilderType) this; - } - - /** - * An InputStream implementations which reads from some other InputStream - * but is limited to a particular number of bytes. Used by - * mergeDelimitedFrom(). This is intentionally package-private so that - * UnknownFieldSet can share it. - */ - 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 { - final long result = super.skip(Math.min(n, limit)); - if (result >= 0) { - 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 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 BuilderType mergeFrom(final MessageLite other) { - if (!getDefaultInstanceForType().getClass().isInstance(other)) { - throw new IllegalArgumentException( - "mergeFrom(MessageLite) can only merge messages of the same type."); - } - - return internalMergeFrom((MessageType) other); - } - - protected abstract BuilderType internalMergeFrom(MessageType message); - - /** - * Construct an UninitializedMessageException reporting missing fields in - * the given message. - */ - protected static UninitializedMessageException - newUninitializedMessageException(MessageLite message) { - return new UninitializedMessageException(message); - } - - /** - * 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. When that happens, some elements of - * {@code values} may have already been added to the result {@code list}. - */ - protected static <T> void addAll(final Iterable<T> values, - final Collection<? super T> list) { - if (values == null) { - throw new NullPointerException(); - } - if (values instanceof LazyStringList) { - // For StringOrByteStringLists, check the underlying elements to avoid - // forcing conversions of ByteStrings to Strings. - checkForNullValues(((LazyStringList) values).getUnderlyingElements()); - list.addAll((Collection<T>) values); - } else if (values instanceof Collection) { - checkForNullValues(values); - list.addAll((Collection<T>) values); - } else { - for (final T value : values) { - if (value == null) { - throw new NullPointerException(); - } - list.add(value); - } - } - } - - private static void checkForNullValues(final Iterable<?> values) { - for (final Object value : values) { - if (value == null) { - throw new NullPointerException(); - } - } - } - } -} diff --git a/java/src/main/java/com/google/protobuf/AbstractParser.java b/java/src/main/java/com/google/protobuf/AbstractParser.java deleted file mode 100644 index 66b0ee3b..00000000 --- a/java/src/main/java/com/google/protobuf/AbstractParser.java +++ /dev/null @@ -1,258 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package com.google.protobuf; - -import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream; - -import java.io.IOException; -import java.io.InputStream; - -/** - * A partial implementation of the {@link Parser} interface which implements - * as many methods of that interface as possible in terms of other methods. - * - * Note: This class implements all the convenience methods in the - * {@link Parser} interface. See {@link Parser} for related javadocs. - * Subclasses need to implement - * {@link Parser#parsePartialFrom(CodedInputStream, ExtensionRegistryLite)} - * - * @author liujisi@google.com (Pherl Liu) - */ -public abstract class AbstractParser<MessageType extends MessageLite> - implements Parser<MessageType> { - /** - * Creates an UninitializedMessageException for MessageType. - */ - private UninitializedMessageException - newUninitializedMessageException(MessageType message) { - if (message instanceof AbstractMessageLite) { - return ((AbstractMessageLite) message).newUninitializedMessageException(); - } - return new UninitializedMessageException(message); - } - - /** - * Helper method to check if message is initialized. - * - * @throws InvalidProtocolBufferException if it is not initialized. - * @return The message to check. - */ - private MessageType checkMessageInitialized(MessageType message) - throws InvalidProtocolBufferException { - if (message != null && !message.isInitialized()) { - throw newUninitializedMessageException(message) - .asInvalidProtocolBufferException() - .setUnfinishedMessage(message); - } - return message; - } - - private static final ExtensionRegistryLite EMPTY_REGISTRY - = ExtensionRegistryLite.getEmptyRegistry(); - - @Override - public MessageType parsePartialFrom(CodedInputStream input) - throws InvalidProtocolBufferException { - return parsePartialFrom(input, EMPTY_REGISTRY); - } - - @Override - public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(input, extensionRegistry)); - } - - @Override - public MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException { - return parseFrom(input, EMPTY_REGISTRY); - } - - @Override - public MessageType parsePartialFrom(ByteString data, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - MessageType message; - try { - CodedInputStream input = data.newCodedInput(); - message = parsePartialFrom(input, extensionRegistry); - try { - input.checkLastTagWas(0); - } catch (InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(message); - } - return message; - } catch (InvalidProtocolBufferException e) { - throw e; - } - } - - @Override - public MessageType parsePartialFrom(ByteString data) throws InvalidProtocolBufferException { - return parsePartialFrom(data, EMPTY_REGISTRY); - } - - @Override - public MessageType parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return checkMessageInitialized(parsePartialFrom(data, extensionRegistry)); - } - - @Override - public MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException { - return parseFrom(data, EMPTY_REGISTRY); - } - - @Override - public MessageType parsePartialFrom( - byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - try { - CodedInputStream input = CodedInputStream.newInstance(data, off, len); - MessageType message = parsePartialFrom(input, extensionRegistry); - try { - input.checkLastTagWas(0); - } catch (InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(message); - } - return message; - } catch (InvalidProtocolBufferException e) { - throw e; - } - } - - @Override - public MessageType parsePartialFrom(byte[] data, int off, int len) - throws InvalidProtocolBufferException { - return parsePartialFrom(data, off, len, EMPTY_REGISTRY); - } - - @Override - public MessageType parsePartialFrom(byte[] data, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return parsePartialFrom(data, 0, data.length, extensionRegistry); - } - - @Override - public MessageType parsePartialFrom(byte[] data) throws InvalidProtocolBufferException { - return parsePartialFrom(data, 0, data.length, EMPTY_REGISTRY); - } - - @Override - public MessageType parseFrom( - byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(data, off, len, extensionRegistry)); - } - - @Override - public MessageType parseFrom(byte[] data, int off, int len) - throws InvalidProtocolBufferException { - return parseFrom(data, off, len, EMPTY_REGISTRY); - } - - @Override - public MessageType parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return parseFrom(data, 0, data.length, extensionRegistry); - } - - @Override - public MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException { - return parseFrom(data, EMPTY_REGISTRY); - } - - @Override - public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - CodedInputStream codedInput = CodedInputStream.newInstance(input); - MessageType message = parsePartialFrom(codedInput, extensionRegistry); - try { - codedInput.checkLastTagWas(0); - } catch (InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(message); - } - return message; - } - - @Override - public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException { - return parsePartialFrom(input, EMPTY_REGISTRY); - } - - @Override - public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(input, extensionRegistry)); - } - - @Override - public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException { - return parseFrom(input, EMPTY_REGISTRY); - } - - @Override - public MessageType parsePartialDelimitedFrom( - InputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - int size; - try { - int firstByte = input.read(); - if (firstByte == -1) { - return null; - } - size = CodedInputStream.readRawVarint32(firstByte, input); - } catch (IOException e) { - throw new InvalidProtocolBufferException(e.getMessage()); - } - InputStream limitedInput = new LimitedInputStream(input, size); - return parsePartialFrom(limitedInput, extensionRegistry); - } - - @Override - public MessageType parsePartialDelimitedFrom(InputStream input) - throws InvalidProtocolBufferException { - return parsePartialDelimitedFrom(input, EMPTY_REGISTRY); - } - - @Override - public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) - throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialDelimitedFrom(input, extensionRegistry)); - } - - @Override - public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException { - return parseDelimitedFrom(input, EMPTY_REGISTRY); - } -} diff --git a/java/src/main/java/com/google/protobuf/AbstractProtobufList.java b/java/src/main/java/com/google/protobuf/AbstractProtobufList.java deleted file mode 100644 index b17db6e0..00000000 --- a/java/src/main/java/com/google/protobuf/AbstractProtobufList.java +++ /dev/null @@ -1,180 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package com.google.protobuf; - -import com.google.protobuf.Internal.ProtobufList; - -import java.util.AbstractList; -import java.util.Collection; -import java.util.List; -import java.util.RandomAccess; - -/** - * An abstract implementation of {@link ProtobufList} which manages mutability semantics. All mutate - * methods must check if the list is mutable before proceeding. Subclasses must invoke - * {@link #ensureIsMutable()} manually when overriding those methods. - * <p> - * This implementation assumes all subclasses are array based, supporting random access. - */ -abstract class AbstractProtobufList<E> extends AbstractList<E> implements ProtobufList<E> { - - protected static final int DEFAULT_CAPACITY = 10; - - /** - * Whether or not this list is modifiable. - */ - private boolean isMutable; - - /** - * Constructs a mutable list by default. - */ - AbstractProtobufList() { - isMutable = true; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof List)) { - return false; - } - // Handle lists that do not support RandomAccess as efficiently as possible by using an iterator - // based approach in our super class. Otherwise our index based approach will avoid those - // allocations. - if (!(o instanceof RandomAccess)) { - return super.equals(o); - } - - List<?> other = (List<?>) o; - final int size = size(); - if (size != other.size()) { - return false; - } - for (int i = 0; i < size; i++) { - if (!get(i).equals(other.get(i))) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - final int size = size(); - int hashCode = 1; - for (int i = 0; i < size; i++) { - hashCode = (31 * hashCode) + get(i).hashCode(); - } - return hashCode; - } - - @Override - public boolean add(E e) { - ensureIsMutable(); - return super.add(e); - } - - @Override - public void add(int index, E element) { - ensureIsMutable(); - super.add(index, element); - } - - @Override - public boolean addAll(Collection<? extends E> c) { - ensureIsMutable(); - return super.addAll(c); - } - - @Override - public boolean addAll(int index, Collection<? extends E> c) { - ensureIsMutable(); - return super.addAll(index, c); - } - - @Override - public void clear() { - ensureIsMutable(); - super.clear(); - } - - @Override - public boolean isModifiable() { - return isMutable; - } - - @Override - public final void makeImmutable() { - isMutable = false; - } - - @Override - public E remove(int index) { - ensureIsMutable(); - return super.remove(index); - } - - @Override - public boolean remove(Object o) { - ensureIsMutable(); - return super.remove(o); - } - - @Override - public boolean removeAll(Collection<?> c) { - ensureIsMutable(); - return super.removeAll(c); - } - - @Override - public boolean retainAll(Collection<?> c) { - ensureIsMutable(); - return super.retainAll(c); - } - - @Override - public E set(int index, E element) { - ensureIsMutable(); - return super.set(index, element); - } - - /** - * Throws an {@link UnsupportedOperationException} if the list is immutable. Subclasses are - * responsible for invoking this method on mutate operations. - */ - protected void ensureIsMutable() { - if (!isMutable) { - throw new UnsupportedOperationException(); - } - } -} diff --git a/java/src/main/java/com/google/protobuf/BlockingRpcChannel.java b/java/src/main/java/com/google/protobuf/BlockingRpcChannel.java deleted file mode 100644 index d535efb9..00000000 --- a/java/src/main/java/com/google/protobuf/BlockingRpcChannel.java +++ /dev/null @@ -1,51 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package com.google.protobuf; - -/** - * <p>Abstract interface for a blocking RPC channel. {@code BlockingRpcChannel} - * is the blocking equivalent to {@link RpcChannel}. - * - * @author kenton@google.com Kenton Varda - * @author cpovirk@google.com Chris Povirk - */ -public interface BlockingRpcChannel { - /** - * Call the given method of the remote service and blocks until it returns. - * {@code callBlockingMethod()} is the blocking equivalent to - * {@link RpcChannel#callMethod}. - */ - Message callBlockingMethod( - Descriptors.MethodDescriptor method, - RpcController controller, - Message request, - Message responsePrototype) throws ServiceException; -} diff --git a/java/src/main/java/com/google/protobuf/BlockingService.java b/java/src/main/java/com/google/protobuf/BlockingService.java deleted file mode 100644 index d01f0b8f..00000000 --- a/java/src/main/java/com/google/protobuf/BlockingService.java +++ /dev/null @@ -1,64 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package com.google.protobuf; - -/** - * Blocking equivalent to {@link Service}. - * - * @author kenton@google.com Kenton Varda - * @author cpovirk@google.com Chris Povirk - */ -public interface BlockingService { - /** - * Equivalent to {@link Service#getDescriptorForType}. - */ - Descriptors.ServiceDescriptor getDescriptorForType(); - - /** - * Equivalent to {@link Service#callMethod}, except that - * {@code callBlockingMethod()} returns the result of the RPC or throws a - * {@link ServiceException} if there is a failure, rather than passing the - * information to a callback. - */ - Message callBlockingMethod(Descriptors.MethodDescriptor method, - RpcController controller, - Message request) throws ServiceException; - - /** - * Equivalent to {@link Service#getRequestPrototype}. - */ - Message getRequestPrototype(Descriptors.MethodDescriptor method); - - /** - * Equivalent to {@link Service#getResponsePrototype}. - */ - Message getResponsePrototype(Descriptors.MethodDescriptor method); -} diff --git a/objectivec/GPBArray.h b/objectivec/GPBArray.h index 8c6396a9..afda57f3 100644 --- a/objectivec/GPBArray.h +++ b/objectivec/GPBArray.h @@ -53,9 +53,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBInt32Array *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const int32_t [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBInt32Array *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -92,9 +93,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBUInt32Array *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const uint32_t [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBUInt32Array *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -131,9 +133,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBInt64Array *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const int64_t [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBInt64Array *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -170,9 +173,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBUInt64Array *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const uint64_t [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBUInt64Array *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -209,9 +213,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBFloatArray *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const float [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBFloatArray *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -248,9 +253,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBDoubleArray *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const double [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBDoubleArray *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -287,9 +293,10 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValueArray:(GPBBoolArray *)array; + (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)init NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValues:(const BOOL [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBBoolArray *)array; - (instancetype)initWithCapacity:(NSUInteger)count; @@ -330,12 +337,13 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)count; -- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; +- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func + NS_DESIGNATED_INITIALIZER; // Initializes the array, copying the values. - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values - count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; + count:(NSUInteger)count; - (instancetype)initWithValueArray:(GPBEnumArray *)array; - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)count; @@ -422,9 +430,10 @@ NS_ASSUME_NONNULL_END //%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array; //%+ (instancetype)arrayWithCapacity:(NSUInteger)count; //% +//%- (instancetype)init NS_DESIGNATED_INITIALIZER; //%// Initializes the array, copying the values. //%- (instancetype)initWithValues:(const TYPE [])values -//% count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; +//% count:(NSUInteger)count; //%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array; //%- (instancetype)initWithCapacity:(NSUInteger)count; //% @@ -455,12 +464,13 @@ NS_ASSUME_NONNULL_END //%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func //% capacity:(NSUInteger)count; //% -//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; +//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func +//% NS_DESIGNATED_INITIALIZER; //% //%// Initializes the array, copying the values. //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% rawValues:(const TYPE [])values -//% count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; +//% count:(NSUInteger)count; //%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array; //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% capacity:(NSUInteger)count; diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m index 60b08ad1..426c7cbd 100644 --- a/objectivec/GPBArray.m +++ b/objectivec/GPBArray.m @@ -75,7 +75,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { //%@synthesize count = _count; //% //%+ (instancetype)array { -//% return [[[self alloc] initWithValues:NULL count:0] autorelease]; +//% return [[[self alloc] init] autorelease]; //%} //% //%+ (instancetype)arrayWithValue:(TYPE)value { @@ -93,7 +93,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { //%} //% //%- (instancetype)init { -//% return [self initWithValues:NULL count:0]; +//% self = [super init]; +//% // No work needed; +//% return self; //%} //% //%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array { @@ -101,11 +103,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { //%} //% //%- (instancetype)initWithValues:(const TYPE [])values count:(NSUInteger)count { -//% self = [super init]; +//% self = [self init]; //% if (self) { //% if (count && values) { -//% _values = malloc(count * sizeof(TYPE)); -//% if (values != NULL) { +//% _values = reallocf(_values, count * sizeof(TYPE)); +//% if (_values != NULL) { //% _capacity = count; //% memcpy(_values, values, count * sizeof(TYPE)); //% _count = count; @@ -299,7 +301,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(int32_t)value { @@ -317,7 +319,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBInt32Array *)array { @@ -325,11 +329,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const int32_t [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(int32_t)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(int32_t)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(int32_t)); _count = count; @@ -544,7 +548,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(uint32_t)value { @@ -562,7 +566,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBUInt32Array *)array { @@ -570,11 +576,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const uint32_t [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(uint32_t)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(uint32_t)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(uint32_t)); _count = count; @@ -789,7 +795,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(int64_t)value { @@ -807,7 +813,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBInt64Array *)array { @@ -815,11 +823,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const int64_t [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(int64_t)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(int64_t)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(int64_t)); _count = count; @@ -1034,7 +1042,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(uint64_t)value { @@ -1052,7 +1060,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBUInt64Array *)array { @@ -1060,11 +1070,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const uint64_t [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(uint64_t)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(uint64_t)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(uint64_t)); _count = count; @@ -1279,7 +1289,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(float)value { @@ -1297,7 +1307,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBFloatArray *)array { @@ -1305,11 +1317,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const float [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(float)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(float)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(float)); _count = count; @@ -1524,7 +1536,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(double)value { @@ -1542,7 +1554,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBDoubleArray *)array { @@ -1550,11 +1564,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const double [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(double)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(double)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(double)); _count = count; @@ -1769,7 +1783,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize count = _count; + (instancetype)array { - return [[[self alloc] initWithValues:NULL count:0] autorelease]; + return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(BOOL)value { @@ -1787,7 +1801,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValues:NULL count:0]; + self = [super init]; + // No work needed; + return self; } - (instancetype)initWithValueArray:(GPBBoolArray *)array { @@ -1795,11 +1811,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValues:(const BOOL [])values count:(NSUInteger)count { - self = [super init]; + self = [self init]; if (self) { if (count && values) { - _values = malloc(count * sizeof(BOOL)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(BOOL)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(BOOL)); _count = count; @@ -2015,15 +2031,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @synthesize validationFunc = _validationFunc; + (instancetype)array { - return [[[self alloc] initWithValidationFunction:NULL - rawValues:NULL - count:0] autorelease]; + return [[[self alloc] initWithValidationFunction:NULL] autorelease]; } + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func { - return [[[self alloc] initWithValidationFunction:func - rawValues:NULL - count:0] autorelease]; + return [[[self alloc] initWithValidationFunction:func] autorelease]; } + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func @@ -2043,7 +2055,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)init { - return [self initWithValidationFunction:NULL rawValues:NULL count:0]; + return [self initWithValidationFunction:NULL]; } - (instancetype)initWithValueArray:(GPBEnumArray *)array { @@ -2053,18 +2065,21 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { - return [self initWithValidationFunction:func rawValues:NULL count:0]; + self = [super init]; + if (self) { + _validationFunc = (func != NULL ? func : ArrayDefault_IsValidValue); + } + return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])values count:(NSUInteger)count { - self = [super init]; + self = [self initWithValidationFunction:func]; if (self) { - _validationFunc = (func != NULL ? func : ArrayDefault_IsValidValue); if (count && values) { - _values = malloc(count * sizeof(int32_t)); - if (values != NULL) { + _values = reallocf(_values, count * sizeof(int32_t)); + if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(int32_t)); _count = count; @@ -2081,7 +2096,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count { - self = [self initWithValidationFunction:func rawValues:NULL count:0]; + self = [self initWithValidationFunction:func]; if (self && count) { [self internalResizeToCapacity:count]; } diff --git a/python/google/protobuf/pyext/extension_dict.h b/python/google/protobuf/pyext/extension_dict.h index 049d2e45..2456eda1 100644 --- a/python/google/protobuf/pyext/extension_dict.h +++ b/python/google/protobuf/pyext/extension_dict.h @@ -48,7 +48,7 @@ class Message; class FieldDescriptor; #ifdef _SHARED_PTR_H -using shared_ptr; +using std::shared_ptr; #else using internal::shared_ptr; #endif diff --git a/python/google/protobuf/pyext/map_container.h b/python/google/protobuf/pyext/map_container.h index b11dfa34..fbd6713f 100644 --- a/python/google/protobuf/pyext/map_container.h +++ b/python/google/protobuf/pyext/map_container.h @@ -47,7 +47,7 @@ namespace protobuf { class Message; #ifdef _SHARED_PTR_H -using shared_ptr; +using std::shared_ptr; #else using internal::shared_ptr; #endif diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h index 9dce198f..3a4bec81 100644 --- a/python/google/protobuf/pyext/message.h +++ b/python/google/protobuf/pyext/message.h @@ -53,8 +53,8 @@ class DescriptorPool; class MessageFactory; #ifdef _SHARED_PTR_H -using shared_ptr; -using std::std::string; +using std::shared_ptr; +using ::std::string; #else using internal::shared_ptr; #endif diff --git a/python/google/protobuf/pyext/repeated_composite_container.h b/python/google/protobuf/pyext/repeated_composite_container.h index 25463037..a7b56b61 100644 --- a/python/google/protobuf/pyext/repeated_composite_container.h +++ b/python/google/protobuf/pyext/repeated_composite_container.h @@ -50,7 +50,7 @@ class FieldDescriptor; class Message; #ifdef _SHARED_PTR_H -using shared_ptr; +using std::shared_ptr; #else using internal::shared_ptr; #endif diff --git a/python/google/protobuf/pyext/repeated_scalar_container.h b/python/google/protobuf/pyext/repeated_scalar_container.h index 608222e0..555e621c 100644 --- a/python/google/protobuf/pyext/repeated_scalar_container.h +++ b/python/google/protobuf/pyext/repeated_scalar_container.h @@ -49,7 +49,7 @@ namespace protobuf { class Message; #ifdef _SHARED_PTR_H -using shared_ptr; +using std::shared_ptr; #else using internal::shared_ptr; #endif diff --git a/src/README.md b/src/README.md index 4e312c0c..63d6e24c 100644 --- a/src/README.md +++ b/src/README.md @@ -16,10 +16,13 @@ To build protobuf from source, the following tools are needed: * automake * libtool * curl (used to download gmock) + * make + * g++ + * unzip On Ubuntu, you can install them with: - $ sudo apt-get install autoconf automake libtool curl + $ sudo apt-get install autoconf automake libtool curl make g++ unzip On other platforms, please use the corresponding package managing tool to install them before proceeding. @@ -181,7 +184,7 @@ In the downloads section, download the zip file protoc-$VERSION-win32.zip. It contains the protoc binary as well as public proto files of protobuf library. -To build from source using Microsoft Visual C++, see cmake/README.md. +To build from source using Microsoft Visual C++, see [cmake/README.md](../cmake/README.md). To build from source using Cygwin or MinGW, follow the Unix installation instructions, above. diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc index 78a4c402..10252b39 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc @@ -36,6 +36,7 @@ #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/wire_format.h> namespace google { namespace protobuf { @@ -141,8 +142,9 @@ GenerateMergeFromCodedStream(io::Printer* printer) const { } else { printer->Print( "} else {\n" - " unknown_fields_stream.WriteVarint32(tag);\n" - " unknown_fields_stream.WriteVarint32(value);\n"); + " unknown_fields_stream.WriteVarint32($tag$);\n" + " unknown_fields_stream.WriteVarint32(value);\n", + "tag", SimpleItoa(internal::WireFormat::MakeTag(descriptor_))); } printer->Print(variables_, "}\n"); diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc index d1948ab5..3ca3fbaf 100644 --- a/src/google/protobuf/lite_unittest.cc +++ b/src/google/protobuf/lite_unittest.cc @@ -686,6 +686,33 @@ int main(int argc, char* argv[]) { EXPECT_TRUE(map_message.IsInitialized()); } + { + // Check that adding more values to enum does not corrupt message + // when passed through an old client. + protobuf_unittest::V2MessageLite v2_message; + v2_message.set_int_field(800); + // Set enum field to the value not understood by the old client. + v2_message.set_enum_field(protobuf_unittest::V2_SECOND); + string v2_bytes = v2_message.SerializeAsString(); + + protobuf_unittest::V1MessageLite v1_message; + v1_message.ParseFromString(v2_bytes); + EXPECT_TRUE(v1_message.IsInitialized()); + EXPECT_EQ(v1_message.int_field(), v2_message.int_field()); + // V1 client does not understand V2_SECOND value, so it discards it and + // uses default value instead. + EXPECT_EQ(v1_message.enum_field(), protobuf_unittest::V1_FIRST); + + // However, when re-serialized, it should preserve enum value. + string v1_bytes = v1_message.SerializeAsString(); + + protobuf_unittest::V2MessageLite same_v2_message; + same_v2_message.ParseFromString(v1_bytes); + + EXPECT_EQ(v2_message.int_field(), same_v2_message.int_field()); + EXPECT_EQ(v2_message.enum_field(), same_v2_message.enum_field()); + } + std::cout << "PASS" << std::endl; return 0; } diff --git a/src/google/protobuf/unittest_lite.proto b/src/google/protobuf/unittest_lite.proto index 41ed845f..878ec7c1 100644 --- a/src/google/protobuf/unittest_lite.proto +++ b/src/google/protobuf/unittest_lite.proto @@ -386,3 +386,22 @@ message TestEmptyMessageLite{ message TestEmptyMessageWithExtensionsLite { extensions 1 to max; } + +enum V1EnumLite { + V1_FIRST = 1; +} + +enum V2EnumLite { + V2_FIRST = 1; + V2_SECOND = 2; +} + +message V1MessageLite { + required int32 int_field = 1; + optional V1EnumLite enum_field = 2 [ default = V1_FIRST ]; +} + +message V2MessageLite { + required int32 int_field = 1; + optional V2EnumLite enum_field = 2 [ default = V2_FIRST ]; +} |