diff --git a/DataExtractionOSM/.classpath b/DataExtractionOSM/.classpath index 0f1e203d9f..e4fcdf539d 100644 --- a/DataExtractionOSM/.classpath +++ b/DataExtractionOSM/.classpath @@ -7,6 +7,5 @@ - diff --git a/DataExtractionOSM/build_proto.xml b/DataExtractionOSM/build_proto.xml new file mode 100644 index 0000000000..3fffbeb29f --- /dev/null +++ b/DataExtractionOSM/build_proto.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/DataExtractionOSM/lib/osm-pbf.jar b/DataExtractionOSM/lib/osm-pbf.jar deleted file mode 100644 index 354a639e4b..0000000000 Binary files a/DataExtractionOSM/lib/osm-pbf.jar and /dev/null differ diff --git a/DataExtractionOSM/protoc.exe b/DataExtractionOSM/protoc.exe new file mode 100644 index 0000000000..2c2877b951 Binary files /dev/null and b/DataExtractionOSM/protoc.exe differ diff --git a/DataExtractionOSM/src/com/google/protobuf/AbstractMessage.java b/DataExtractionOSM/src/com/google/protobuf/AbstractMessage.java new file mode 100644 index 0000000000..fb416bdc03 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/AbstractMessage.java @@ -0,0 +1,708 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; + +import java.io.InputStream; +import java.io.IOException; +import java.util.ArrayList; +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 extends AbstractMessageLite + implements Message { + @SuppressWarnings("unchecked") + public boolean isInitialized() { + // Check that all required fields are present. + for (final FieldDescriptor field : getDescriptorForType().getFields()) { + if (field.isRequired()) { + if (!hasField(field)) { + return false; + } + } + } + + // Check that embedded messages are initialized. + for (final Map.Entry entry : + getAllFields().entrySet()) { + final FieldDescriptor field = entry.getKey(); + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + for (final Message element : (List) entry.getValue()) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (!((Message) entry.getValue()).isInitialized()) { + return false; + } + } + } + } + + return true; + } + + @Override + public final String toString() { + return TextFormat.printToString(this); + } + + public void writeTo(final CodedOutputStream output) throws IOException { + final boolean isMessageSet = + getDescriptorForType().getOptions().getMessageSetWireFormat(); + + for (final Map.Entry entry : + getAllFields().entrySet()) { + final FieldDescriptor field = entry.getKey(); + final Object value = entry.getValue(); + if (isMessageSet && field.isExtension() && + field.getType() == FieldDescriptor.Type.MESSAGE && + !field.isRepeated()) { + output.writeMessageSetExtension(field.getNumber(), (Message) value); + } else { + FieldSet.writeField(field, value, output); + } + } + + final UnknownFieldSet unknownFields = getUnknownFields(); + if (isMessageSet) { + unknownFields.writeAsMessageSetTo(output); + } else { + unknownFields.writeTo(output); + } + } + + private int memoizedSize = -1; + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) { + return size; + } + + size = 0; + final boolean isMessageSet = + getDescriptorForType().getOptions().getMessageSetWireFormat(); + + for (final Map.Entry entry : + getAllFields().entrySet()) { + final FieldDescriptor field = entry.getKey(); + final Object value = entry.getValue(); + if (isMessageSet && field.isExtension() && + field.getType() == FieldDescriptor.Type.MESSAGE && + !field.isRepeated()) { + size += CodedOutputStream.computeMessageSetExtensionSize( + field.getNumber(), (Message) value); + } else { + size += FieldSet.computeFieldSize(field, value); + } + } + + final UnknownFieldSet unknownFields = getUnknownFields(); + if (isMessageSet) { + size += unknownFields.getSerializedSizeAsMessageSet(); + } else { + size += unknownFields.getSerializedSize(); + } + + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object other) { + if (other == this) { + return true; + } + if (!(other instanceof Message)) { + return false; + } + final Message otherMessage = (Message) other; + if (getDescriptorForType() != otherMessage.getDescriptorForType()) { + return false; + } + return getAllFields().equals(otherMessage.getAllFields()) && + getUnknownFields().equals(otherMessage.getUnknownFields()); + } + + @Override + public int hashCode() { + int hash = 41; + hash = (19 * hash) + getDescriptorForType().hashCode(); + hash = (53 * hash) + getAllFields().hashCode(); + hash = (29 * hash) + getUnknownFields().hashCode(); + return hash; + } + + // ================================================================= + + /** + * 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 + extends AbstractMessageLite.Builder + implements Message.Builder { + // The compiler produces an error if this is not declared explicitly. + @Override + public abstract BuilderType clone(); + + public BuilderType clear() { + for (final Map.Entry entry : + getAllFields().entrySet()) { + clearField(entry.getKey()); + } + return (BuilderType) this; + } + + 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 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; + } + + if (!mergeFieldFrom(input, unknownFields, extensionRegistry, + this, tag)) { + // end group tag + break; + } + } + setUnknownFields(unknownFields.build()); + return (BuilderType) this; + } + + /** + * Like {@link #mergeFrom(CodedInputStream, UnknownFieldSet.Builder, + * ExtensionRegistryLite, Message.Builder)}, but parses a single field. + * Package-private because it is used by GeneratedMessage.ExtendableMessage. + * @param tag The tag, which should have already been read. + * @return {@code true} unless the tag is an end-group tag. + */ + static boolean mergeFieldFrom( + final CodedInputStream input, + final UnknownFieldSet.Builder unknownFields, + final ExtensionRegistryLite extensionRegistry, + final Message.Builder builder, + final int tag) throws IOException { + final Descriptor type = builder.getDescriptorForType(); + + if (type.getOptions().getMessageSetWireFormat() && + tag == WireFormat.MESSAGE_SET_ITEM_TAG) { + mergeMessageSetExtensionFromCodedStream( + input, unknownFields, extensionRegistry, builder); + return true; + } + + final int wireType = WireFormat.getTagWireType(tag); + final int fieldNumber = WireFormat.getTagFieldNumber(tag); + + final FieldDescriptor field; + Message defaultInstance = null; + + if (type.isExtensionNumber(fieldNumber)) { + // extensionRegistry may be either ExtensionRegistry or + // ExtensionRegistryLite. Since the type we are parsing is a full + // message, only a full ExtensionRegistry could possibly contain + // extensions of it. Otherwise we will treat the registry as if it + // were empty. + if (extensionRegistry instanceof ExtensionRegistry) { + final ExtensionRegistry.ExtensionInfo extension = + ((ExtensionRegistry) extensionRegistry) + .findExtensionByNumber(type, fieldNumber); + if (extension == null) { + field = null; + } else { + field = extension.descriptor; + defaultInstance = extension.defaultInstance; + if (defaultInstance == null && + field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + throw new IllegalStateException( + "Message-typed extension lacked default instance: " + + field.getFullName()); + } + } + } else { + field = null; + } + } else { + field = type.findFieldByNumber(fieldNumber); + } + + boolean unknown = false; + boolean packed = false; + if (field == null) { + unknown = true; // Unknown field. + } else if (wireType == FieldSet.getWireFormatForFieldType( + field.getLiteType(), + false /* isPacked */)) { + packed = false; + } else if (field.isPackable() && + wireType == FieldSet.getWireFormatForFieldType( + field.getLiteType(), + true /* isPacked */)) { + packed = true; + } else { + unknown = true; // Unknown wire type. + } + + if (unknown) { // Unknown field or wrong wire type. Skip. + return unknownFields.mergeFieldFrom(tag, input); + } + + if (packed) { + final int length = input.readRawVarint32(); + final int limit = input.pushLimit(length); + if (field.getLiteType() == WireFormat.FieldType.ENUM) { + while (input.getBytesUntilLimit() > 0) { + final int rawValue = input.readEnum(); + final Object value = field.getEnumType().findValueByNumber(rawValue); + if (value == null) { + // If the number isn't recognized as a valid value for this + // enum, drop it (don't even add it to unknownFields). + return true; + } + builder.addRepeatedField(field, value); + } + } else { + while (input.getBytesUntilLimit() > 0) { + final Object value = + FieldSet.readPrimitiveField(input, field.getLiteType()); + builder.addRepeatedField(field, value); + } + } + input.popLimit(limit); + } else { + final Object value; + switch (field.getType()) { + case GROUP: { + final Message.Builder subBuilder; + if (defaultInstance != null) { + subBuilder = defaultInstance.newBuilderForType(); + } else { + subBuilder = builder.newBuilderForField(field); + } + if (!field.isRepeated()) { + subBuilder.mergeFrom((Message) builder.getField(field)); + } + input.readGroup(field.getNumber(), subBuilder, extensionRegistry); + value = subBuilder.build(); + break; + } + case MESSAGE: { + final Message.Builder subBuilder; + if (defaultInstance != null) { + subBuilder = defaultInstance.newBuilderForType(); + } else { + subBuilder = builder.newBuilderForField(field); + } + if (!field.isRepeated()) { + subBuilder.mergeFrom((Message) builder.getField(field)); + } + input.readMessage(subBuilder, extensionRegistry); + value = subBuilder.build(); + break; + } + case ENUM: + final int rawValue = input.readEnum(); + value = field.getEnumType().findValueByNumber(rawValue); + // If the number isn't recognized as a valid value for this enum, + // drop it. + if (value == null) { + unknownFields.mergeVarintField(fieldNumber, rawValue); + return true; + } + break; + default: + value = FieldSet.readPrimitiveField(input, field.getLiteType()); + break; + } + + if (field.isRepeated()) { + builder.addRepeatedField(field, value); + } else { + builder.setField(field, value); + } + } + + return true; + } + + /** Called by {@code #mergeFieldFrom()} to parse a MessageSet extension. */ + private static void mergeMessageSetExtensionFromCodedStream( + final CodedInputStream input, + final UnknownFieldSet.Builder unknownFields, + final ExtensionRegistryLite extensionRegistry, + final Message.Builder builder) throws IOException { + final Descriptor type = builder.getDescriptorForType(); + + // The wire format for MessageSet is: + // message MessageSet { + // repeated group Item = 1 { + // required int32 typeId = 2; + // required bytes message = 3; + // } + // } + // "typeId" is the extension's field number. The extension can only be + // a message type, where "message" contains the encoded bytes of that + // message. + // + // In practice, we will probably never see a MessageSet item in which + // the message appears before the type ID, or where either field does not + // appear exactly once. However, in theory such cases are valid, so we + // should be prepared to accept them. + + int typeId = 0; + ByteString rawBytes = null; // If we encounter "message" before "typeId" + Message.Builder subBuilder = null; + FieldDescriptor field = null; + + while (true) { + final int tag = input.readTag(); + if (tag == 0) { + break; + } + + if (tag == WireFormat.MESSAGE_SET_TYPE_ID_TAG) { + typeId = input.readUInt32(); + // Zero is not a valid type ID. + if (typeId != 0) { + final ExtensionRegistry.ExtensionInfo extension; + + // extensionRegistry may be either ExtensionRegistry or + // ExtensionRegistryLite. Since the type we are parsing is a full + // message, only a full ExtensionRegistry could possibly contain + // extensions of it. Otherwise we will treat the registry as if it + // were empty. + if (extensionRegistry instanceof ExtensionRegistry) { + extension = ((ExtensionRegistry) extensionRegistry) + .findExtensionByNumber(type, typeId); + } else { + extension = null; + } + + if (extension != null) { + field = extension.descriptor; + subBuilder = extension.defaultInstance.newBuilderForType(); + final Message originalMessage = (Message)builder.getField(field); + if (originalMessage != null) { + subBuilder.mergeFrom(originalMessage); + } + if (rawBytes != null) { + // We already encountered the message. Parse it now. + subBuilder.mergeFrom( + CodedInputStream.newInstance(rawBytes.newInput())); + rawBytes = null; + } + } else { + // Unknown extension number. If we already saw data, put it + // in rawBytes. + if (rawBytes != null) { + unknownFields.mergeField(typeId, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(rawBytes) + .build()); + rawBytes = null; + } + } + } + } else if (tag == WireFormat.MESSAGE_SET_MESSAGE_TAG) { + if (typeId == 0) { + // We haven't seen a type ID yet, so we have to store the raw bytes + // for now. + rawBytes = input.readBytes(); + } else if (subBuilder == null) { + // We don't know how to parse this. Ignore it. + unknownFields.mergeField(typeId, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(input.readBytes()) + .build()); + } else { + // We already know the type, so we can parse directly from the input + // with no copying. Hooray! + input.readMessage(subBuilder, extensionRegistry); + } + } else { + // Unknown tag. Skip it. + if (!input.skipField(tag)) { + break; // end of group + } + } + } + + input.checkLastTagWas(WireFormat.MESSAGE_SET_ITEM_END_TAG); + + if (subBuilder != null) { + builder.setField(field, subBuilder.build()); + } + } + + public BuilderType mergeUnknownFields(final UnknownFieldSet unknownFields) { + setUnknownFields( + UnknownFieldSet.newBuilder(getUnknownFields()) + .mergeFrom(unknownFields) + .build()); + return (BuilderType) this; + } + + /** + * Construct an UninitializedMessageException reporting missing fields in + * the given message. + */ + protected static UninitializedMessageException + newUninitializedMessageException(Message message) { + return new UninitializedMessageException(findMissingFields(message)); + } + + /** + * Populates {@code this.missingFields} with the full "path" of each + * missing required field in the given message. + */ + private static List findMissingFields(final Message message) { + final List results = new ArrayList(); + findMissingFields(message, "", results); + return results; + } + + /** Recursive helper implementing {@link #findMissingFields(Message)}. */ + private static void findMissingFields(final Message message, + final String prefix, + final List results) { + for (final FieldDescriptor field : + message.getDescriptorForType().getFields()) { + if (field.isRequired() && !message.hasField(field)) { + results.add(prefix + field.getName()); + } + } + + for (final Map.Entry entry : + message.getAllFields().entrySet()) { + final FieldDescriptor field = entry.getKey(); + final Object value = entry.getValue(); + + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + int i = 0; + for (final Object element : (List) value) { + findMissingFields((Message) element, + subMessagePrefix(prefix, field, i++), + results); + } + } else { + if (message.hasField(field)) { + findMissingFields((Message) value, + subMessagePrefix(prefix, field, -1), + results); + } + } + } + } + } + + private static String subMessagePrefix(final String prefix, + final FieldDescriptor field, + final int index) { + final StringBuilder result = new StringBuilder(prefix); + if (field.isExtension()) { + result.append('(') + .append(field.getFullName()) + .append(')'); + } else { + result.append(field.getName()); + } + if (index != -1) { + result.append('[') + .append(index) + .append(']'); + } + result.append('.'); + return result.toString(); + } + + // =============================================================== + // 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 super.mergeFrom(data); + } + + @Override + public BuilderType mergeFrom( + final ByteString data, + final ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + return super.mergeFrom(data, extensionRegistry); + } + + @Override + public BuilderType mergeFrom(final byte[] data) + throws InvalidProtocolBufferException { + return super.mergeFrom(data); + } + + @Override + public BuilderType mergeFrom( + final byte[] data, final int off, final int len) + throws InvalidProtocolBufferException { + return super.mergeFrom(data, off, len); + } + + @Override + public BuilderType mergeFrom( + final byte[] data, + final ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + return super.mergeFrom(data, extensionRegistry); + } + + @Override + public BuilderType mergeFrom( + final byte[] data, final int off, final int len, + final ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + return super.mergeFrom(data, off, len, extensionRegistry); + } + + @Override + public BuilderType mergeFrom(final InputStream input) + throws IOException { + return super.mergeFrom(input); + } + + @Override + public BuilderType mergeFrom( + final InputStream input, + final ExtensionRegistryLite extensionRegistry) + throws IOException { + return 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/DataExtractionOSM/src/com/google/protobuf/AbstractMessageLite.java b/DataExtractionOSM/src/com/google/protobuf/AbstractMessageLite.java new file mode 100644 index 0000000000..e4fe60fda7 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/AbstractMessageLite.java @@ -0,0 +1,326 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.InputStream; +import java.io.IOException; +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 implements MessageLite { + 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); + } + } + + 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); + } + } + + public void writeTo(final OutputStream output) throws IOException { + final int bufferSize = + CodedOutputStream.computePreferredBufferSize(getSerializedSize()); + final CodedOutputStream codedOutput = + CodedOutputStream.newInstance(output, bufferSize); + writeTo(codedOutput); + codedOutput.flush(); + } + + public void writeDelimitedTo(final OutputStream output) throws IOException { + final int serialized = getSerializedSize(); + final int bufferSize = CodedOutputStream.computePreferredBufferSize( + CodedOutputStream.computeRawVarint32Size(serialized) + serialized); + final CodedOutputStream codedOutput = + CodedOutputStream.newInstance(output, bufferSize); + codedOutput.writeRawVarint32(serialized); + writeTo(codedOutput); + codedOutput.flush(); + } + + /** + * 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 + implements MessageLite.Builder { + // The compiler produces an error if this is not declared explicitly. + @Override + public abstract BuilderType clone(); + + public BuilderType mergeFrom(final CodedInputStream input) + throws IOException { + return mergeFrom(input, ExtensionRegistryLite.getEmptyRegistry()); + } + + // Re-defined here for return type covariance. + public abstract BuilderType mergeFrom( + final CodedInputStream input, + final ExtensionRegistryLite extensionRegistry) + throws IOException; + + 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); + } + } + + 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); + } + } + + public BuilderType mergeFrom(final byte[] data) + throws InvalidProtocolBufferException { + return mergeFrom(data, 0, data.length); + } + + 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); + } + } + + public BuilderType mergeFrom( + final byte[] data, + final ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + return mergeFrom(data, 0, data.length, extensionRegistry); + } + + 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); + } + } + + public BuilderType mergeFrom(final InputStream input) throws IOException { + final CodedInputStream codedInput = CodedInputStream.newInstance(input); + mergeFrom(codedInput); + codedInput.checkLastTagWas(0); + return (BuilderType) this; + } + + 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; + } + } + + 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; + } + + public boolean mergeDelimitedFrom(final InputStream input) + throws IOException { + return mergeDelimitedFrom(input, + ExtensionRegistryLite.getEmptyRegistry()); + } + + /** + * 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 any of the elements of {@code values} is + * null. + */ + protected static void addAll(final Iterable values, + final Collection list) { + for (final T value : values) { + if (value == null) { + throw new NullPointerException(); + } + } + if (values instanceof Collection) { + final + Collection collection = (Collection) values; + list.addAll(collection); + } else { + for (final T value : values) { + list.add(value); + } + } + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/BlockingRpcChannel.java b/DataExtractionOSM/src/com/google/protobuf/BlockingRpcChannel.java new file mode 100644 index 0000000000..1e81143aea --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/BlockingRpcChannel.java @@ -0,0 +1,51 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + *

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/DataExtractionOSM/src/com/google/protobuf/BlockingService.java b/DataExtractionOSM/src/com/google/protobuf/BlockingService.java new file mode 100644 index 0000000000..ecc80096f5 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/BlockingService.java @@ -0,0 +1,64 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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/DataExtractionOSM/src/com/google/protobuf/ByteString.java b/DataExtractionOSM/src/com/google/protobuf/ByteString.java new file mode 100644 index 0000000000..5fade03ada --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/ByteString.java @@ -0,0 +1,391 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.InputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FilterOutputStream; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.util.List; + +/** + * Immutable array of bytes. + * + * @author crazybob@google.com Bob Lee + * @author kenton@google.com Kenton Varda + */ +public final class ByteString { + private final byte[] bytes; + + private ByteString(final byte[] bytes) { + this.bytes = bytes; + } + + /** + * Gets the byte at the given index. + * + * @throws ArrayIndexOutOfBoundsException {@code index} is < 0 or >= size + */ + public byte byteAt(final int index) { + return bytes[index]; + } + + /** + * Gets the number of bytes. + */ + public int size() { + return bytes.length; + } + + /** + * Returns {@code true} if the size is {@code 0}, {@code false} otherwise. + */ + public boolean isEmpty() { + return bytes.length == 0; + } + + // ================================================================= + // byte[] -> ByteString + + /** + * Empty ByteString. + */ + public static final ByteString EMPTY = new ByteString(new byte[0]); + + /** + * Copies the given bytes into a {@code ByteString}. + */ + public static ByteString copyFrom(final byte[] bytes, final int offset, + final int size) { + final byte[] copy = new byte[size]; + System.arraycopy(bytes, offset, copy, 0, size); + return new ByteString(copy); + } + + /** + * Copies the given bytes into a {@code ByteString}. + */ + public static ByteString copyFrom(final byte[] bytes) { + return copyFrom(bytes, 0, bytes.length); + } + + /** + * Copies {@code size} bytes from a {@code java.nio.ByteBuffer} into + * a {@code ByteString}. + */ + public static ByteString copyFrom(final ByteBuffer bytes, final int size) { + final byte[] copy = new byte[size]; + bytes.get(copy); + return new ByteString(copy); + } + + /** + * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into + * a {@code ByteString}. + */ + public static ByteString copyFrom(final ByteBuffer bytes) { + return copyFrom(bytes, bytes.remaining()); + } + + /** + * Encodes {@code text} into a sequence of bytes using the named charset + * and returns the result as a {@code ByteString}. + */ + public static ByteString copyFrom(final String text, final String charsetName) + throws UnsupportedEncodingException { + return new ByteString(text.getBytes(charsetName)); + } + + /** + * Encodes {@code text} into a sequence of UTF-8 bytes and returns the + * result as a {@code ByteString}. + */ + public static ByteString copyFromUtf8(final String text) { + try { + return new ByteString(text.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported?", e); + } + } + + /** + * Concatenates all byte strings in the list and returns the result. + * + *

The returned {@code ByteString} is not necessarily a unique object. + * If the list is empty, the returned object is the singleton empty + * {@code ByteString}. If the list has only one element, that + * {@code ByteString} will be returned without copying. + */ + public static ByteString copyFrom(List list) { + if (list.size() == 0) { + return EMPTY; + } else if (list.size() == 1) { + return list.get(0); + } + + int size = 0; + for (ByteString str : list) { + size += str.size(); + } + byte[] bytes = new byte[size]; + int pos = 0; + for (ByteString str : list) { + System.arraycopy(str.bytes, 0, bytes, pos, str.size()); + pos += str.size(); + } + return new ByteString(bytes); + } + + // ================================================================= + // ByteString -> byte[] + + /** + * Copies bytes into a buffer at the given offset. + * + * @param target buffer to copy into + * @param offset in the target buffer + */ + public void copyTo(final byte[] target, final int offset) { + System.arraycopy(bytes, 0, target, offset, bytes.length); + } + + /** + * Copies bytes into a buffer. + * + * @param target buffer to copy into + * @param sourceOffset offset within these bytes + * @param targetOffset offset within the target buffer + * @param size number of bytes to copy + */ + public void copyTo(final byte[] target, final int sourceOffset, + final int targetOffset, + final int size) { + System.arraycopy(bytes, sourceOffset, target, targetOffset, size); + } + + /** + * Copies bytes to a {@code byte[]}. + */ + public byte[] toByteArray() { + final int size = bytes.length; + final byte[] copy = new byte[size]; + System.arraycopy(bytes, 0, copy, 0, size); + return copy; + } + + /** + * Constructs a new read-only {@code java.nio.ByteBuffer} with the + * same backing byte array. + */ + public ByteBuffer asReadOnlyByteBuffer() { + final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); + return byteBuffer.asReadOnlyBuffer(); + } + + /** + * Constructs a new {@code String} by decoding the bytes using the + * specified charset. + */ + public String toString(final String charsetName) + throws UnsupportedEncodingException { + return new String(bytes, charsetName); + } + + /** + * Constructs a new {@code String} by decoding the bytes as UTF-8. + */ + public String toStringUtf8() { + try { + return new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported?", e); + } + } + + // ================================================================= + // equals() and hashCode() + + @Override + public boolean equals(final Object o) { + if (o == this) { + return true; + } + + if (!(o instanceof ByteString)) { + return false; + } + + final ByteString other = (ByteString) o; + final int size = bytes.length; + if (size != other.bytes.length) { + return false; + } + + final byte[] thisBytes = bytes; + final byte[] otherBytes = other.bytes; + for (int i = 0; i < size; i++) { + if (thisBytes[i] != otherBytes[i]) { + return false; + } + } + + return true; + } + + private volatile int hash = 0; + + @Override + public int hashCode() { + int h = hash; + + if (h == 0) { + final byte[] thisBytes = bytes; + final int size = bytes.length; + + h = size; + for (int i = 0; i < size; i++) { + h = h * 31 + thisBytes[i]; + } + if (h == 0) { + h = 1; + } + + hash = h; + } + + return h; + } + + // ================================================================= + // Input stream + + /** + * Creates an {@code InputStream} which can be used to read the bytes. + */ + public InputStream newInput() { + return new ByteArrayInputStream(bytes); + } + + /** + * Creates a {@link CodedInputStream} which can be used to read the bytes. + * Using this is more efficient than creating a {@link CodedInputStream} + * wrapping the result of {@link #newInput()}. + */ + public CodedInputStream newCodedInput() { + // We trust CodedInputStream not to modify the bytes, or to give anyone + // else access to them. + return CodedInputStream.newInstance(bytes); + } + + // ================================================================= + // Output stream + + /** + * Creates a new {@link Output} with the given initial capacity. + */ + public static Output newOutput(final int initialCapacity) { + return new Output(new ByteArrayOutputStream(initialCapacity)); + } + + /** + * Creates a new {@link Output}. + */ + public static Output newOutput() { + return newOutput(32); + } + + /** + * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to + * create the {@code ByteString} instance. + */ + public static final class Output extends FilterOutputStream { + private final ByteArrayOutputStream bout; + + /** + * Constructs a new output with the given initial capacity. + */ + private Output(final ByteArrayOutputStream bout) { + super(bout); + this.bout = bout; + } + + /** + * Creates a {@code ByteString} instance from this {@code Output}. + */ + public ByteString toByteString() { + final byte[] byteArray = bout.toByteArray(); + return new ByteString(byteArray); + } + } + + /** + * Constructs a new ByteString builder, which allows you to efficiently + * construct a {@code ByteString} by writing to a {@link CodedOutputStream}. + * Using this is much more efficient than calling {@code newOutput()} and + * wrapping that in a {@code CodedOutputStream}. + * + *

This is package-private because it's a somewhat confusing interface. + * Users can call {@link Message#toByteString()} instead of calling this + * directly. + * + * @param size The target byte size of the {@code ByteString}. You must + * write exactly this many bytes before building the result. + */ + static CodedBuilder newCodedBuilder(final int size) { + return new CodedBuilder(size); + } + + /** See {@link ByteString#newCodedBuilder(int)}. */ + static final class CodedBuilder { + private final CodedOutputStream output; + private final byte[] buffer; + + private CodedBuilder(final int size) { + buffer = new byte[size]; + output = CodedOutputStream.newInstance(buffer); + } + + public ByteString build() { + output.checkNoSpaceLeft(); + + // We can be confident that the CodedOutputStream will not modify the + // underlying bytes anymore because it already wrote all of them. So, + // no need to make a copy. + return new ByteString(buffer); + } + + public CodedOutputStream getCodedOutput() { + return output; + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/CodedInputStream.java b/DataExtractionOSM/src/com/google/protobuf/CodedInputStream.java new file mode 100644 index 0000000000..ad43f96d4f --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/CodedInputStream.java @@ -0,0 +1,865 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads and decodes protocol message fields. + * + * This class contains two kinds of methods: methods that read specific + * protocol message constructs and field types (e.g. {@link #readTag()} and + * {@link #readInt32()}) and methods that read low-level values (e.g. + * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading + * encoded protocol messages, you should use the former methods, but if you are + * reading some other format of your own design, use the latter. + * + * @author kenton@google.com Kenton Varda + */ +public final class CodedInputStream { + /** + * Create a new CodedInputStream wrapping the given InputStream. + */ + public static CodedInputStream newInstance(final InputStream input) { + return new CodedInputStream(input); + } + + /** + * Create a new CodedInputStream wrapping the given byte array. + */ + public static CodedInputStream newInstance(final byte[] buf) { + return newInstance(buf, 0, buf.length); + } + + /** + * Create a new CodedInputStream wrapping the given byte array slice. + */ + public static CodedInputStream newInstance(final byte[] buf, final int off, + final int len) { + return new CodedInputStream(buf, off, len); + } + + // ----------------------------------------------------------------- + + /** + * Attempt to read a field tag, returning zero if we have reached EOF. + * Protocol message parsers use this to read tags, since a protocol message + * may legally end wherever a tag occurs, and zero is not a valid tag number. + */ + public int readTag() throws IOException { + if (isAtEnd()) { + lastTag = 0; + return 0; + } + + lastTag = readRawVarint32(); + if (WireFormat.getTagFieldNumber(lastTag) == 0) { + // If we actually read zero (or any tag number corresponding to field + // number zero), that's not a valid tag. + throw InvalidProtocolBufferException.invalidTag(); + } + return lastTag; + } + + /** + * Verifies that the last call to readTag() returned the given tag value. + * This is used to verify that a nested group ended with the correct + * end tag. + * + * @throws InvalidProtocolBufferException {@code value} does not match the + * last tag. + */ + public void checkLastTagWas(final int value) + throws InvalidProtocolBufferException { + if (lastTag != value) { + throw InvalidProtocolBufferException.invalidEndTag(); + } + } + + /** + * Reads and discards a single field, given its tag value. + * + * @return {@code false} if the tag is an endgroup tag, in which case + * nothing is skipped. Otherwise, returns {@code true}. + */ + public boolean skipField(final int tag) throws IOException { + switch (WireFormat.getTagWireType(tag)) { + case WireFormat.WIRETYPE_VARINT: + readInt32(); + return true; + case WireFormat.WIRETYPE_FIXED64: + readRawLittleEndian64(); + return true; + case WireFormat.WIRETYPE_LENGTH_DELIMITED: + skipRawBytes(readRawVarint32()); + return true; + case WireFormat.WIRETYPE_START_GROUP: + skipMessage(); + checkLastTagWas( + WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), + WireFormat.WIRETYPE_END_GROUP)); + return true; + case WireFormat.WIRETYPE_END_GROUP: + return false; + case WireFormat.WIRETYPE_FIXED32: + readRawLittleEndian32(); + return true; + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + /** + * Reads and discards an entire message. This will read either until EOF + * or until an endgroup tag, whichever comes first. + */ + public void skipMessage() throws IOException { + while (true) { + final int tag = readTag(); + if (tag == 0 || !skipField(tag)) { + return; + } + } + } + + // ----------------------------------------------------------------- + + /** Read a {@code double} field value from the stream. */ + public double readDouble() throws IOException { + return Double.longBitsToDouble(readRawLittleEndian64()); + } + + /** Read a {@code float} field value from the stream. */ + public float readFloat() throws IOException { + return Float.intBitsToFloat(readRawLittleEndian32()); + } + + /** Read a {@code uint64} field value from the stream. */ + public long readUInt64() throws IOException { + return readRawVarint64(); + } + + /** Read an {@code int64} field value from the stream. */ + public long readInt64() throws IOException { + return readRawVarint64(); + } + + /** Read an {@code int32} field value from the stream. */ + public int readInt32() throws IOException { + return readRawVarint32(); + } + + /** Read a {@code fixed64} field value from the stream. */ + public long readFixed64() throws IOException { + return readRawLittleEndian64(); + } + + /** Read a {@code fixed32} field value from the stream. */ + public int readFixed32() throws IOException { + return readRawLittleEndian32(); + } + + /** Read a {@code bool} field value from the stream. */ + public boolean readBool() throws IOException { + return readRawVarint32() != 0; + } + + /** Read a {@code string} field value from the stream. */ + public String readString() throws IOException { + final int size = readRawVarint32(); + if (size <= (bufferSize - bufferPos) && size > 0) { + // Fast path: We already have the bytes in a contiguous buffer, so + // just copy directly from it. + final String result = new String(buffer, bufferPos, size, "UTF-8"); + bufferPos += size; + return result; + } else { + // Slow path: Build a byte array first then copy it. + return new String(readRawBytes(size), "UTF-8"); + } + } + + /** Read a {@code group} field value from the stream. */ + public void readGroup(final int fieldNumber, + final MessageLite.Builder builder, + final ExtensionRegistryLite extensionRegistry) + throws IOException { + if (recursionDepth >= recursionLimit) { + throw InvalidProtocolBufferException.recursionLimitExceeded(); + } + ++recursionDepth; + builder.mergeFrom(this, extensionRegistry); + checkLastTagWas( + WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); + --recursionDepth; + } + + /** + * Reads a {@code group} field value from the stream and merges it into the + * given {@link UnknownFieldSet}. + * + * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so + * you can just call {@link #readGroup}. + */ + @Deprecated + public void readUnknownGroup(final int fieldNumber, + final MessageLite.Builder builder) + throws IOException { + // We know that UnknownFieldSet will ignore any ExtensionRegistry so it + // is safe to pass null here. (We can't call + // ExtensionRegistry.getEmptyRegistry() because that would make this + // class depend on ExtensionRegistry, which is not part of the lite + // library.) + readGroup(fieldNumber, builder, null); + } + + /** Read an embedded message field value from the stream. */ + public void readMessage(final MessageLite.Builder builder, + final ExtensionRegistryLite extensionRegistry) + throws IOException { + final int length = readRawVarint32(); + if (recursionDepth >= recursionLimit) { + throw InvalidProtocolBufferException.recursionLimitExceeded(); + } + final int oldLimit = pushLimit(length); + ++recursionDepth; + builder.mergeFrom(this, extensionRegistry); + checkLastTagWas(0); + --recursionDepth; + popLimit(oldLimit); + } + + /** Read a {@code bytes} field value from the stream. */ + public ByteString readBytes() throws IOException { + final int size = readRawVarint32(); + if (size <= (bufferSize - bufferPos) && size > 0) { + // Fast path: We already have the bytes in a contiguous buffer, so + // just copy directly from it. + final ByteString result = ByteString.copyFrom(buffer, bufferPos, size); + bufferPos += size; + return result; + } else { + // Slow path: Build a byte array first then copy it. + return ByteString.copyFrom(readRawBytes(size)); + } + } + + /** Read a {@code uint32} field value from the stream. */ + public int readUInt32() throws IOException { + return readRawVarint32(); + } + + /** + * Read an enum field value from the stream. Caller is responsible + * for converting the numeric value to an actual enum. + */ + public int readEnum() throws IOException { + return readRawVarint32(); + } + + /** Read an {@code sfixed32} field value from the stream. */ + public int readSFixed32() throws IOException { + return readRawLittleEndian32(); + } + + /** Read an {@code sfixed64} field value from the stream. */ + public long readSFixed64() throws IOException { + return readRawLittleEndian64(); + } + + /** Read an {@code sint32} field value from the stream. */ + public int readSInt32() throws IOException { + return decodeZigZag32(readRawVarint32()); + } + + /** Read an {@code sint64} field value from the stream. */ + public long readSInt64() throws IOException { + return decodeZigZag64(readRawVarint64()); + } + + // ================================================================= + + /** + * Read a raw Varint from the stream. If larger than 32 bits, discard the + * upper bits. + */ + public int readRawVarint32() throws IOException { + byte tmp = readRawByte(); + if (tmp >= 0) { + return tmp; + } + int result = tmp & 0x7f; + if ((tmp = readRawByte()) >= 0) { + result |= tmp << 7; + } else { + result |= (tmp & 0x7f) << 7; + if ((tmp = readRawByte()) >= 0) { + result |= tmp << 14; + } else { + result |= (tmp & 0x7f) << 14; + if ((tmp = readRawByte()) >= 0) { + result |= tmp << 21; + } else { + result |= (tmp & 0x7f) << 21; + result |= (tmp = readRawByte()) << 28; + if (tmp < 0) { + // Discard upper 32 bits. + for (int i = 0; i < 5; i++) { + if (readRawByte() >= 0) { + return result; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + } + } + } + return result; + } + + /** + * Reads a varint from the input one byte at a time, so that it does not + * read any bytes after the end of the varint. If you simply wrapped the + * stream in a CodedInputStream and used {@link #readRawVarint32(InputStream)} + * then you would probably end up reading past the end of the varint since + * CodedInputStream buffers its input. + */ + static int readRawVarint32(final InputStream input) throws IOException { + final int firstByte = input.read(); + if (firstByte == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + return readRawVarint32(firstByte, input); + } + + /** + * Like {@link #readRawVarint32(InputStream)}, but expects that the caller + * has already read one byte. This allows the caller to determine if EOF + * has been reached before attempting to read. + */ + static int readRawVarint32(final int firstByte, + final InputStream input) throws IOException { + if ((firstByte & 0x80) == 0) { + return firstByte; + } + + int result = firstByte & 0x7f; + int offset = 7; + for (; offset < 32; offset += 7) { + final int b = input.read(); + if (b == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + result |= (b & 0x7f) << offset; + if ((b & 0x80) == 0) { + return result; + } + } + // Keep reading up to 64 bits. + for (; offset < 64; offset += 7) { + final int b = input.read(); + if (b == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + if ((b & 0x80) == 0) { + return result; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + /** Read a raw Varint from the stream. */ + public long readRawVarint64() throws IOException { + int shift = 0; + long result = 0; + while (shift < 64) { + final byte b = readRawByte(); + result |= (long)(b & 0x7F) << shift; + if ((b & 0x80) == 0) { + return result; + } + shift += 7; + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + /** Read a 32-bit little-endian integer from the stream. */ + public int readRawLittleEndian32() throws IOException { + final byte b1 = readRawByte(); + final byte b2 = readRawByte(); + final byte b3 = readRawByte(); + final byte b4 = readRawByte(); + return (((int)b1 & 0xff) ) | + (((int)b2 & 0xff) << 8) | + (((int)b3 & 0xff) << 16) | + (((int)b4 & 0xff) << 24); + } + + /** Read a 64-bit little-endian integer from the stream. */ + public long readRawLittleEndian64() throws IOException { + final byte b1 = readRawByte(); + final byte b2 = readRawByte(); + final byte b3 = readRawByte(); + final byte b4 = readRawByte(); + final byte b5 = readRawByte(); + final byte b6 = readRawByte(); + final byte b7 = readRawByte(); + final byte b8 = readRawByte(); + return (((long)b1 & 0xff) ) | + (((long)b2 & 0xff) << 8) | + (((long)b3 & 0xff) << 16) | + (((long)b4 & 0xff) << 24) | + (((long)b5 & 0xff) << 32) | + (((long)b6 & 0xff) << 40) | + (((long)b7 & 0xff) << 48) | + (((long)b8 & 0xff) << 56); + } + + /** + * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers + * into values that can be efficiently encoded with varint. (Otherwise, + * negative values must be sign-extended to 64 bits to be varint encoded, + * thus always taking 10 bytes on the wire.) + * + * @param n An unsigned 32-bit integer, stored in a signed int because + * Java has no explicit unsigned support. + * @return A signed 32-bit integer. + */ + public static int decodeZigZag32(final int n) { + return (n >>> 1) ^ -(n & 1); + } + + /** + * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers + * into values that can be efficiently encoded with varint. (Otherwise, + * negative values must be sign-extended to 64 bits to be varint encoded, + * thus always taking 10 bytes on the wire.) + * + * @param n An unsigned 64-bit integer, stored in a signed int because + * Java has no explicit unsigned support. + * @return A signed 64-bit integer. + */ + public static long decodeZigZag64(final long n) { + return (n >>> 1) ^ -(n & 1); + } + + // ----------------------------------------------------------------- + + private final byte[] buffer; + private int bufferSize; + private int bufferSizeAfterLimit; + private int bufferPos; + private final InputStream input; + private int lastTag; + + /** + * The total number of bytes read before the current buffer. The total + * bytes read up to the current position can be computed as + * {@code totalBytesRetired + bufferPos}. This value may be negative if + * reading started in the middle of the current buffer (e.g. if the + * constructor that takes a byte array and an offset was used). + */ + private int totalBytesRetired; + + /** The absolute position of the end of the current message. */ + private int currentLimit = Integer.MAX_VALUE; + + /** See setRecursionLimit() */ + private int recursionDepth; + private int recursionLimit = DEFAULT_RECURSION_LIMIT; + + /** See setSizeLimit() */ + private int sizeLimit = DEFAULT_SIZE_LIMIT; + + private static final int DEFAULT_RECURSION_LIMIT = 64; + private static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB + private static final int BUFFER_SIZE = 4096; + + private CodedInputStream(final byte[] buffer, final int off, final int len) { + this.buffer = buffer; + bufferSize = off + len; + bufferPos = off; + totalBytesRetired = -off; + input = null; + } + + private CodedInputStream(final InputStream input) { + buffer = new byte[BUFFER_SIZE]; + bufferSize = 0; + bufferPos = 0; + totalBytesRetired = 0; + this.input = input; + } + + /** + * Set the maximum message recursion depth. In order to prevent malicious + * messages from causing stack overflows, {@code CodedInputStream} limits + * how deeply messages may be nested. The default limit is 64. + * + * @return the old limit. + */ + public int setRecursionLimit(final int limit) { + if (limit < 0) { + throw new IllegalArgumentException( + "Recursion limit cannot be negative: " + limit); + } + final int oldLimit = recursionLimit; + recursionLimit = limit; + return oldLimit; + } + + /** + * Set the maximum message size. In order to prevent malicious + * messages from exhausting memory or causing integer overflows, + * {@code CodedInputStream} limits how large a message may be. + * The default limit is 64MB. You should set this limit as small + * as you can without harming your app's functionality. Note that + * size limits only apply when reading from an {@code InputStream}, not + * when constructed around a raw byte array (nor with + * {@link ByteString#newCodedInput}). + *

+ * If you want to read several messages from a single CodedInputStream, you + * could call {@link #resetSizeCounter()} after each one to avoid hitting the + * size limit. + * + * @return the old limit. + */ + public int setSizeLimit(final int limit) { + if (limit < 0) { + throw new IllegalArgumentException( + "Size limit cannot be negative: " + limit); + } + final int oldLimit = sizeLimit; + sizeLimit = limit; + return oldLimit; + } + + /** + * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). + */ + public void resetSizeCounter() { + totalBytesRetired = -bufferPos; + } + + /** + * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This + * is called when descending into a length-delimited embedded message. + * + *

Note that {@code pushLimit()} does NOT affect how many bytes the + * {@code CodedInputStream} reads from an underlying {@code InputStream} when + * refreshing its buffer. If you need to prevent reading past a certain + * point in the underlying {@code InputStream} (e.g. because you expect it to + * contain more data after the end of the message which you need to handle + * differently) then you must place a wrapper around you {@code InputStream} + * which limits the amount of data that can be read from it. + * + * @return the old limit. + */ + public int pushLimit(int byteLimit) throws InvalidProtocolBufferException { + if (byteLimit < 0) { + throw InvalidProtocolBufferException.negativeSize(); + } + byteLimit += totalBytesRetired + bufferPos; + final int oldLimit = currentLimit; + if (byteLimit > oldLimit) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + currentLimit = byteLimit; + + recomputeBufferSizeAfterLimit(); + + return oldLimit; + } + + private void recomputeBufferSizeAfterLimit() { + bufferSize += bufferSizeAfterLimit; + final int bufferEnd = totalBytesRetired + bufferSize; + if (bufferEnd > currentLimit) { + // Limit is in current buffer. + bufferSizeAfterLimit = bufferEnd - currentLimit; + bufferSize -= bufferSizeAfterLimit; + } else { + bufferSizeAfterLimit = 0; + } + } + + /** + * Discards the current limit, returning to the previous limit. + * + * @param oldLimit The old limit, as returned by {@code pushLimit}. + */ + public void popLimit(final int oldLimit) { + currentLimit = oldLimit; + recomputeBufferSizeAfterLimit(); + } + + /** + * Returns the number of bytes to be read before the current limit. + * If no limit is set, returns -1. + */ + public int getBytesUntilLimit() { + if (currentLimit == Integer.MAX_VALUE) { + return -1; + } + + final int currentAbsolutePosition = totalBytesRetired + bufferPos; + return currentLimit - currentAbsolutePosition; + } + + /** + * Returns true if the stream has reached the end of the input. This is the + * case if either the end of the underlying input source has been reached or + * if the stream has reached a limit created using {@link #pushLimit(int)}. + */ + public boolean isAtEnd() throws IOException { + return bufferPos == bufferSize && !refillBuffer(false); + } + + /** + * The total bytes read up to the current position. Calling + * {@link #resetSizeCounter()} resets this value to zero. + */ + public int getTotalBytesRead() { + return totalBytesRetired + bufferPos; + } + + /** + * Called with {@code this.buffer} is empty to read more bytes from the + * input. If {@code mustSucceed} is true, refillBuffer() gurantees that + * either there will be at least one byte in the buffer when it returns + * or it will throw an exception. If {@code mustSucceed} is false, + * refillBuffer() returns false if no more bytes were available. + */ + private boolean refillBuffer(final boolean mustSucceed) throws IOException { + if (bufferPos < bufferSize) { + throw new IllegalStateException( + "refillBuffer() called when buffer wasn't empty."); + } + + if (totalBytesRetired + bufferSize == currentLimit) { + // Oops, we hit a limit. + if (mustSucceed) { + throw InvalidProtocolBufferException.truncatedMessage(); + } else { + return false; + } + } + + totalBytesRetired += bufferSize; + + bufferPos = 0; + bufferSize = (input == null) ? -1 : input.read(buffer); + if (bufferSize == 0 || bufferSize < -1) { + throw new IllegalStateException( + "InputStream#read(byte[]) returned invalid result: " + bufferSize + + "\nThe InputStream implementation is buggy."); + } + if (bufferSize == -1) { + bufferSize = 0; + if (mustSucceed) { + throw InvalidProtocolBufferException.truncatedMessage(); + } else { + return false; + } + } else { + recomputeBufferSizeAfterLimit(); + final int totalBytesRead = + totalBytesRetired + bufferSize + bufferSizeAfterLimit; + if (totalBytesRead > sizeLimit || totalBytesRead < 0) { + throw InvalidProtocolBufferException.sizeLimitExceeded(); + } + return true; + } + } + + /** + * Read one byte from the input. + * + * @throws InvalidProtocolBufferException The end of the stream or the current + * limit was reached. + */ + public byte readRawByte() throws IOException { + if (bufferPos == bufferSize) { + refillBuffer(true); + } + return buffer[bufferPos++]; + } + + /** + * Read a fixed size of bytes from the input. + * + * @throws InvalidProtocolBufferException The end of the stream or the current + * limit was reached. + */ + public byte[] readRawBytes(final int size) throws IOException { + if (size < 0) { + throw InvalidProtocolBufferException.negativeSize(); + } + + if (totalBytesRetired + bufferPos + size > currentLimit) { + // Read to the end of the stream anyway. + skipRawBytes(currentLimit - totalBytesRetired - bufferPos); + // Then fail. + throw InvalidProtocolBufferException.truncatedMessage(); + } + + if (size <= bufferSize - bufferPos) { + // We have all the bytes we need already. + final byte[] bytes = new byte[size]; + System.arraycopy(buffer, bufferPos, bytes, 0, size); + bufferPos += size; + return bytes; + } else if (size < BUFFER_SIZE) { + // Reading more bytes than are in the buffer, but not an excessive number + // of bytes. We can safely allocate the resulting array ahead of time. + + // First copy what we have. + final byte[] bytes = new byte[size]; + int pos = bufferSize - bufferPos; + System.arraycopy(buffer, bufferPos, bytes, 0, pos); + bufferPos = bufferSize; + + // We want to use refillBuffer() and then copy from the buffer into our + // byte array rather than reading directly into our byte array because + // the input may be unbuffered. + refillBuffer(true); + + while (size - pos > bufferSize) { + System.arraycopy(buffer, 0, bytes, pos, bufferSize); + pos += bufferSize; + bufferPos = bufferSize; + refillBuffer(true); + } + + System.arraycopy(buffer, 0, bytes, pos, size - pos); + bufferPos = size - pos; + + return bytes; + } else { + // The size is very large. For security reasons, we can't allocate the + // entire byte array yet. The size comes directly from the input, so a + // maliciously-crafted message could provide a bogus very large size in + // order to trick the app into allocating a lot of memory. We avoid this + // by allocating and reading only a small chunk at a time, so that the + // malicious message must actually *be* extremely large to cause + // problems. Meanwhile, we limit the allowed size of a message elsewhere. + + // Remember the buffer markers since we'll have to copy the bytes out of + // it later. + final int originalBufferPos = bufferPos; + final int originalBufferSize = bufferSize; + + // Mark the current buffer consumed. + totalBytesRetired += bufferSize; + bufferPos = 0; + bufferSize = 0; + + // Read all the rest of the bytes we need. + int sizeLeft = size - (originalBufferSize - originalBufferPos); + final List chunks = new ArrayList(); + + while (sizeLeft > 0) { + final byte[] chunk = new byte[Math.min(sizeLeft, BUFFER_SIZE)]; + int pos = 0; + while (pos < chunk.length) { + final int n = (input == null) ? -1 : + input.read(chunk, pos, chunk.length - pos); + if (n == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + totalBytesRetired += n; + pos += n; + } + sizeLeft -= chunk.length; + chunks.add(chunk); + } + + // OK, got everything. Now concatenate it all into one buffer. + final byte[] bytes = new byte[size]; + + // Start by copying the leftover bytes from this.buffer. + int pos = originalBufferSize - originalBufferPos; + System.arraycopy(buffer, originalBufferPos, bytes, 0, pos); + + // And now all the chunks. + for (final byte[] chunk : chunks) { + System.arraycopy(chunk, 0, bytes, pos, chunk.length); + pos += chunk.length; + } + + // Done. + return bytes; + } + } + + /** + * Reads and discards {@code size} bytes. + * + * @throws InvalidProtocolBufferException The end of the stream or the current + * limit was reached. + */ + public void skipRawBytes(final int size) throws IOException { + if (size < 0) { + throw InvalidProtocolBufferException.negativeSize(); + } + + if (totalBytesRetired + bufferPos + size > currentLimit) { + // Read to the end of the stream anyway. + skipRawBytes(currentLimit - totalBytesRetired - bufferPos); + // Then fail. + throw InvalidProtocolBufferException.truncatedMessage(); + } + + if (size <= bufferSize - bufferPos) { + // We have all the bytes we need already. + bufferPos += size; + } else { + // Skipping more bytes than are in the buffer. First skip what we have. + int pos = bufferSize - bufferPos; + totalBytesRetired += pos; + bufferPos = 0; + bufferSize = 0; + + // Then skip directly from the InputStream for the rest. + while (pos < size) { + final int n = (input == null) ? -1 : (int) input.skip(size - pos); + if (n <= 0) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + pos += n; + totalBytesRetired += n; + } + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/CodedInputStreamRAF.java b/DataExtractionOSM/src/com/google/protobuf/CodedInputStreamRAF.java new file mode 100644 index 0000000000..8c38c2081a --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/CodedInputStreamRAF.java @@ -0,0 +1,814 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads and decodes protocol message fields. + * + * This class contains two kinds of methods: methods that read specific + * protocol message constructs and field types (e.g. {@link #readTag()} and + * {@link #readInt32()}) and methods that read low-level values (e.g. + * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading + * encoded protocol messages, you should use the former methods, but if you are + * reading some other format of your own design, use the latter. + * + * @author kenton@google.com Kenton Varda + */ +public final class CodedInputStreamRAF { + /** + * Create a new CodedInputStream wrapping the given InputStream. + */ + public static CodedInputStreamRAF newInstance(RandomAccessFile raf) { + return new CodedInputStreamRAF(raf, BUFFER_SIZE_DEF); + } + + public static CodedInputStreamRAF newInstance(RandomAccessFile raf, int bufferSize) { + return new CodedInputStreamRAF(raf, bufferSize); + } + + + // ----------------------------------------------------------------- + + /** + * Attempt to read a field tag, returning zero if we have reached EOF. + * Protocol message parsers use this to read tags, since a protocol message + * may legally end wherever a tag occurs, and zero is not a valid tag number. + */ + public int readTag() throws IOException { + if (isAtEnd()) { + lastTag = 0; + return 0; + } + + lastTag = readRawVarint32(); + if (WireFormat.getTagFieldNumber(lastTag) == 0) { + // If we actually read zero (or any tag number corresponding to field + // number zero), that's not a valid tag. + throw InvalidProtocolBufferException.invalidTag(); + } + return lastTag; + } + + /** + * Verifies that the last call to readTag() returned the given tag value. + * This is used to verify that a nested group ended with the correct + * end tag. + * + * @throws InvalidProtocolBufferException {@code value} does not match the + * last tag. + */ + public void checkLastTagWas(final int value) + throws InvalidProtocolBufferException { + if (lastTag != value) { + throw InvalidProtocolBufferException.invalidEndTag(); + } + } + + /** + * Reads and discards a single field, given its tag value. + * + * @return {@code false} if the tag is an endgroup tag, in which case + * nothing is skipped. Otherwise, returns {@code true}. + */ + public boolean skipField(final int tag) throws IOException { + switch (WireFormat.getTagWireType(tag)) { + case WireFormat.WIRETYPE_VARINT: + readInt32(); + return true; + case WireFormat.WIRETYPE_FIXED64: + readRawLittleEndian64(); + return true; + case WireFormat.WIRETYPE_LENGTH_DELIMITED: + skipRawBytes(readRawVarint32()); + return true; + case WireFormat.WIRETYPE_START_GROUP: + skipMessage(); + checkLastTagWas( + WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), + WireFormat.WIRETYPE_END_GROUP)); + return true; + case WireFormat.WIRETYPE_END_GROUP: + return false; + case WireFormat.WIRETYPE_FIXED32: + readRawLittleEndian32(); + return true; + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + /** + * Reads and discards an entire message. This will read either until EOF + * or until an endgroup tag, whichever comes first. + */ + public void skipMessage() throws IOException { + while (true) { + final int tag = readTag(); + if (tag == 0 || !skipField(tag)) { + return; + } + } + } + + // ----------------------------------------------------------------- + + /** Read a {@code double} field value from the stream. */ + public double readDouble() throws IOException { + return Double.longBitsToDouble(readRawLittleEndian64()); + } + + /** Read a {@code float} field value from the stream. */ + public float readFloat() throws IOException { + return Float.intBitsToFloat(readRawLittleEndian32()); + } + + /** Read a {@code uint64} field value from the stream. */ + public long readUInt64() throws IOException { + return readRawVarint64(); + } + + /** Read an {@code int64} field value from the stream. */ + public long readInt64() throws IOException { + return readRawVarint64(); + } + + /** Read an {@code int32} field value from the stream. */ + public int readInt32() throws IOException { + return readRawVarint32(); + } + + /** Read a {@code fixed64} field value from the stream. */ + public long readFixed64() throws IOException { + return readRawLittleEndian64(); + } + + /** Read a {@code fixed32} field value from the stream. */ + public int readFixed32() throws IOException { + return readRawLittleEndian32(); + } + + /** Read a {@code bool} field value from the stream. */ + public boolean readBool() throws IOException { + return readRawVarint32() != 0; + } + + /** Read a {@code string} field value from the stream. */ + public String readString() throws IOException { + final int size = readRawVarint32(); + if (size <= (bufferSize - bufferPos) && size > 0) { + // Fast path: We already have the bytes in a contiguous buffer, so + // just copy directly from it. + final String result = new String(buffer, bufferPos, size, "UTF-8"); + bufferPos += size; + return result; + } else { + // Slow path: Build a byte array first then copy it. + return new String(readRawBytes(size), "UTF-8"); + } + } + + + + + /** Read a {@code bytes} field value from the stream. */ + public ByteString readBytes() throws IOException { + final int size = readRawVarint32(); + if (size <= (bufferSize - bufferPos) && size > 0) { + // Fast path: We already have the bytes in a contiguous buffer, so + // just copy directly from it. + final ByteString result = ByteString.copyFrom(buffer, bufferPos, size); + bufferPos += size; + return result; + } else { + // Slow path: Build a byte array first then copy it. + return ByteString.copyFrom(readRawBytes(size)); + } + } + + /** Read a {@code uint32} field value from the stream. */ + public int readUInt32() throws IOException { + return readRawVarint32(); + } + + /** + * Read an enum field value from the stream. Caller is responsible + * for converting the numeric value to an actual enum. + */ + public int readEnum() throws IOException { + return readRawVarint32(); + } + + /** Read an {@code sfixed32} field value from the stream. */ + public int readSFixed32() throws IOException { + return readRawLittleEndian32(); + } + + /** Read an {@code sfixed64} field value from the stream. */ + public long readSFixed64() throws IOException { + return readRawLittleEndian64(); + } + + /** Read an {@code sint32} field value from the stream. */ + public int readSInt32() throws IOException { + return decodeZigZag32(readRawVarint32()); + } + + /** Read an {@code sint64} field value from the stream. */ + public long readSInt64() throws IOException { + return decodeZigZag64(readRawVarint64()); + } + + // ================================================================= + + /** + * Read a raw Varint from the stream. If larger than 32 bits, discard the + * upper bits. + */ + public int readRawVarint32() throws IOException { + byte tmp = readRawByte(); + if (tmp >= 0) { + return tmp; + } + int result = tmp & 0x7f; + if ((tmp = readRawByte()) >= 0) { + result |= tmp << 7; + } else { + result |= (tmp & 0x7f) << 7; + if ((tmp = readRawByte()) >= 0) { + result |= tmp << 14; + } else { + result |= (tmp & 0x7f) << 14; + if ((tmp = readRawByte()) >= 0) { + result |= tmp << 21; + } else { + result |= (tmp & 0x7f) << 21; + result |= (tmp = readRawByte()) << 28; + if (tmp < 0) { + // Discard upper 32 bits. + for (int i = 0; i < 5; i++) { + if (readRawByte() >= 0) { + return result; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + } + } + } + return result; + } + + /** + * Reads a varint from the input one byte at a time, so that it does not + * read any bytes after the end of the varint. If you simply wrapped the + * stream in a CodedInputStream and used {@link #readRawVarint32(InputStream)} + * then you would probably end up reading past the end of the varint since + * CodedInputStream buffers its input. + */ + static int readRawVarint32(final InputStream input) throws IOException { + final int firstByte = input.read(); + if (firstByte == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + return readRawVarint32(firstByte, input); + } + + /** + * Like {@link #readRawVarint32(InputStream)}, but expects that the caller + * has already read one byte. This allows the caller to determine if EOF + * has been reached before attempting to read. + */ + static int readRawVarint32(final int firstByte, + final InputStream input) throws IOException { + if ((firstByte & 0x80) == 0) { + return firstByte; + } + + int result = firstByte & 0x7f; + int offset = 7; + for (; offset < 32; offset += 7) { + final int b = input.read(); + if (b == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + result |= (b & 0x7f) << offset; + if ((b & 0x80) == 0) { + return result; + } + } + // Keep reading up to 64 bits. + for (; offset < 64; offset += 7) { + final int b = input.read(); + if (b == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + if ((b & 0x80) == 0) { + return result; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + /** Read a raw Varint from the stream. */ + public long readRawVarint64() throws IOException { + int shift = 0; + long result = 0; + while (shift < 64) { + final byte b = readRawByte(); + result |= (long)(b & 0x7F) << shift; + if ((b & 0x80) == 0) { + return result; + } + shift += 7; + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + /** Read a 32-bit little-endian integer from the stream. */ + public int readRawLittleEndian32() throws IOException { + final byte b1 = readRawByte(); + final byte b2 = readRawByte(); + final byte b3 = readRawByte(); + final byte b4 = readRawByte(); + return (((int)b1 & 0xff) ) | + (((int)b2 & 0xff) << 8) | + (((int)b3 & 0xff) << 16) | + (((int)b4 & 0xff) << 24); + } + + /** Read a 64-bit little-endian integer from the stream. */ + public long readRawLittleEndian64() throws IOException { + final byte b1 = readRawByte(); + final byte b2 = readRawByte(); + final byte b3 = readRawByte(); + final byte b4 = readRawByte(); + final byte b5 = readRawByte(); + final byte b6 = readRawByte(); + final byte b7 = readRawByte(); + final byte b8 = readRawByte(); + return (((long)b1 & 0xff) ) | + (((long)b2 & 0xff) << 8) | + (((long)b3 & 0xff) << 16) | + (((long)b4 & 0xff) << 24) | + (((long)b5 & 0xff) << 32) | + (((long)b6 & 0xff) << 40) | + (((long)b7 & 0xff) << 48) | + (((long)b8 & 0xff) << 56); + } + + /** + * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers + * into values that can be efficiently encoded with varint. (Otherwise, + * negative values must be sign-extended to 64 bits to be varint encoded, + * thus always taking 10 bytes on the wire.) + * + * @param n An unsigned 32-bit integer, stored in a signed int because + * Java has no explicit unsigned support. + * @return A signed 32-bit integer. + */ + public static int decodeZigZag32(final int n) { + return (n >>> 1) ^ -(n & 1); + } + + /** + * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers + * into values that can be efficiently encoded with varint. (Otherwise, + * negative values must be sign-extended to 64 bits to be varint encoded, + * thus always taking 10 bytes on the wire.) + * + * @param n An unsigned 64-bit integer, stored in a signed int because + * Java has no explicit unsigned support. + * @return A signed 64-bit integer. + */ + public static long decodeZigZag64(final long n) { + return (n >>> 1) ^ -(n & 1); + } + + // ----------------------------------------------------------------- + + private final byte[] buffer; + private int bufferSize; + private int bufferSizeAfterLimit; + private int bufferPos; + private final RandomAccessFile raf; + private int lastTag; + + /** + * The total number of bytes read before the current buffer. The total + * bytes read up to the current position can be computed as + * {@code totalBytesRetired + bufferPos}. This value may be negative if + * reading started in the middle of the current buffer (e.g. if the + * constructor that takes a byte array and an offset was used). + */ + private int totalBytesRetired; + + /** The absolute position of the end of the current message. */ + private int currentLimit = Integer.MAX_VALUE; + + /** See setRecursionLimit() */ + private int recursionDepth; + private int recursionLimit = DEFAULT_RECURSION_LIMIT; + + /** See setSizeLimit() */ + private int sizeLimit = DEFAULT_SIZE_LIMIT; + + private static final int DEFAULT_RECURSION_LIMIT = 64; + private static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB + private static final int BUFFER_SIZE_DEF = 4096; + private int BUFFER_SIZE = BUFFER_SIZE_DEF; + + + private CodedInputStreamRAF(final RandomAccessFile raf, int bufferSize) { + BUFFER_SIZE = bufferSize; + buffer = new byte[BUFFER_SIZE]; + bufferSize = 0; + bufferPos = 0; + totalBytesRetired = 0; + this.raf = raf; + } + + /** + * Set the maximum message recursion depth. In order to prevent malicious + * messages from causing stack overflows, {@code CodedInputStream} limits + * how deeply messages may be nested. The default limit is 64. + * + * @return the old limit. + */ + public int setRecursionLimit(final int limit) { + if (limit < 0) { + throw new IllegalArgumentException( + "Recursion limit cannot be negative: " + limit); + } + final int oldLimit = recursionLimit; + recursionLimit = limit; + return oldLimit; + } + + /** + * Set the maximum message size. In order to prevent malicious + * messages from exhausting memory or causing integer overflows, + * {@code CodedInputStream} limits how large a message may be. + * The default limit is 64MB. You should set this limit as small + * as you can without harming your app's functionality. Note that + * size limits only apply when reading from an {@code InputStream}, not + * when constructed around a raw byte array (nor with + * {@link ByteString#newCodedInput}). + *

+ * If you want to read several messages from a single CodedInputStream, you + * could call {@link #resetSizeCounter()} after each one to avoid hitting the + * size limit. + * + * @return the old limit. + */ + public int setSizeLimit(final int limit) { + if (limit < 0) { + throw new IllegalArgumentException( + "Size limit cannot be negative: " + limit); + } + final int oldLimit = sizeLimit; + sizeLimit = limit; + return oldLimit; + } + + /** + * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). + */ + public void resetSizeCounter() { + totalBytesRetired = -bufferPos; + } + + /** + * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This + * is called when descending into a length-delimited embedded message. + * + *

Note that {@code pushLimit()} does NOT affect how many bytes the + * {@code CodedInputStream} reads from an underlying {@code InputStream} when + * refreshing its buffer. If you need to prevent reading past a certain + * point in the underlying {@code InputStream} (e.g. because you expect it to + * contain more data after the end of the message which you need to handle + * differently) then you must place a wrapper around you {@code InputStream} + * which limits the amount of data that can be read from it. + * + * @return the old limit. + */ + public int pushLimit(int byteLimit) throws InvalidProtocolBufferException { + if (byteLimit < 0) { + throw InvalidProtocolBufferException.negativeSize(); + } + byteLimit += totalBytesRetired + bufferPos; + final int oldLimit = currentLimit; + if (byteLimit > oldLimit) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + currentLimit = byteLimit; + + recomputeBufferSizeAfterLimit(); + + return oldLimit; + } + + private void recomputeBufferSizeAfterLimit() { + bufferSize += bufferSizeAfterLimit; + final int bufferEnd = totalBytesRetired + bufferSize; + if (bufferEnd > currentLimit) { + // Limit is in current buffer. + bufferSizeAfterLimit = bufferEnd - currentLimit; + bufferSize -= bufferSizeAfterLimit; + } else { + bufferSizeAfterLimit = 0; + } + } + + /** + * Discards the current limit, returning to the previous limit. + * + * @param oldLimit The old limit, as returned by {@code pushLimit}. + */ + public void popLimit(final int oldLimit) { + currentLimit = oldLimit; + recomputeBufferSizeAfterLimit(); + } + + /** + * Returns the number of bytes to be read before the current limit. + * If no limit is set, returns -1. + */ + public int getBytesUntilLimit() { + if (currentLimit == Integer.MAX_VALUE) { + return -1; + } + + final int currentAbsolutePosition = totalBytesRetired + bufferPos; + return currentLimit - currentAbsolutePosition; + } + + /** + * Returns true if the stream has reached the end of the input. This is the + * case if either the end of the underlying input source has been reached or + * if the stream has reached a limit created using {@link #pushLimit(int)}. + */ + public boolean isAtEnd() throws IOException { + return bufferPos == bufferSize && !refillBuffer(false); + } + + /** + * The total bytes read up to the current position. Calling + * {@link #resetSizeCounter()} resets this value to zero. + */ + public int getTotalBytesRead() { + return totalBytesRetired + bufferPos; + } + + /** + * Called with {@code this.buffer} is empty to read more bytes from the + * input. If {@code mustSucceed} is true, refillBuffer() gurantees that + * either there will be at least one byte in the buffer when it returns + * or it will throw an exception. If {@code mustSucceed} is false, + * refillBuffer() returns false if no more bytes were available. + */ + private boolean refillBuffer(final boolean mustSucceed) throws IOException { + if (bufferPos < bufferSize) { + throw new IllegalStateException( + "refillBuffer() called when buffer wasn't empty."); + } + + if (totalBytesRetired + bufferSize == currentLimit) { + // Oops, we hit a limit. + if (mustSucceed) { + throw InvalidProtocolBufferException.truncatedMessage(); + } else { + return false; + } + } + + totalBytesRetired += bufferSize; + + bufferPos = 0; + bufferSize = raf.read(buffer); + if (bufferSize == 0 || bufferSize < -1) { + throw new IllegalStateException( + "InputStream#read(byte[]) returned invalid result: " + bufferSize + + "\nThe InputStream implementation is buggy."); + } + if (bufferSize == -1) { + bufferSize = 0; + if (mustSucceed) { + throw InvalidProtocolBufferException.truncatedMessage(); + } else { + return false; + } + } else { + recomputeBufferSizeAfterLimit(); + final int totalBytesRead = + totalBytesRetired + bufferSize + bufferSizeAfterLimit; + if (totalBytesRead > sizeLimit || totalBytesRead < 0) { + throw InvalidProtocolBufferException.sizeLimitExceeded(); + } + return true; + } + } + + /** + * Read one byte from the input. + * + * @throws InvalidProtocolBufferException The end of the stream or the current + * limit was reached. + */ + public byte readRawByte() throws IOException { + if (bufferPos == bufferSize) { + refillBuffer(true); + } + return buffer[bufferPos++]; + } + + /** + * Read a fixed size of bytes from the input. + * + * @throws InvalidProtocolBufferException The end of the stream or the current + * limit was reached. + */ + public byte[] readRawBytes(final int size) throws IOException { + if (size < 0) { + throw InvalidProtocolBufferException.negativeSize(); + } + + if (totalBytesRetired + bufferPos + size > currentLimit) { + // Read to the end of the stream anyway. + skipRawBytes(currentLimit - totalBytesRetired - bufferPos); + // Then fail. + throw InvalidProtocolBufferException.truncatedMessage(); + } + + if (size <= bufferSize - bufferPos) { + // We have all the bytes we need already. + final byte[] bytes = new byte[size]; + System.arraycopy(buffer, bufferPos, bytes, 0, size); + bufferPos += size; + return bytes; + } else if (size < BUFFER_SIZE) { + // Reading more bytes than are in the buffer, but not an excessive number + // of bytes. We can safely allocate the resulting array ahead of time. + + // First copy what we have. + final byte[] bytes = new byte[size]; + int pos = bufferSize - bufferPos; + System.arraycopy(buffer, bufferPos, bytes, 0, pos); + bufferPos = bufferSize; + + // We want to use refillBuffer() and then copy from the buffer into our + // byte array rather than reading directly into our byte array because + // the input may be unbuffered. + refillBuffer(true); + + while (size - pos > bufferSize) { + System.arraycopy(buffer, 0, bytes, pos, bufferSize); + pos += bufferSize; + bufferPos = bufferSize; + refillBuffer(true); + } + + System.arraycopy(buffer, 0, bytes, pos, size - pos); + bufferPos = size - pos; + + return bytes; + } else { + // The size is very large. For security reasons, we can't allocate the + // entire byte array yet. The size comes directly from the input, so a + // maliciously-crafted message could provide a bogus very large size in + // order to trick the app into allocating a lot of memory. We avoid this + // by allocating and reading only a small chunk at a time, so that the + // malicious message must actually *be* extremely large to cause + // problems. Meanwhile, we limit the allowed size of a message elsewhere. + + // Remember the buffer markers since we'll have to copy the bytes out of + // it later. + final int originalBufferPos = bufferPos; + final int originalBufferSize = bufferSize; + + // Mark the current buffer consumed. + totalBytesRetired += bufferSize; + bufferPos = 0; + bufferSize = 0; + + // Read all the rest of the bytes we need. + int sizeLeft = size - (originalBufferSize - originalBufferPos); + final List chunks = new ArrayList(); + + while (sizeLeft > 0) { + final byte[] chunk = new byte[Math.min(sizeLeft, BUFFER_SIZE)]; + int pos = 0; + while (pos < chunk.length) { + final int n = raf.read(chunk, pos, chunk.length - pos); + if (n == -1) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + totalBytesRetired += n; + pos += n; + } + sizeLeft -= chunk.length; + chunks.add(chunk); + } + + // OK, got everything. Now concatenate it all into one buffer. + final byte[] bytes = new byte[size]; + + // Start by copying the leftover bytes from this.buffer. + int pos = originalBufferSize - originalBufferPos; + System.arraycopy(buffer, originalBufferPos, bytes, 0, pos); + + // And now all the chunks. + for (final byte[] chunk : chunks) { + System.arraycopy(chunk, 0, bytes, pos, chunk.length); + pos += chunk.length; + } + + // Done. + return bytes; + } + } + + /** + * Reads and discards {@code size} bytes. + * + * @throws InvalidProtocolBufferException The end of the stream or the current + * limit was reached. + */ + public void skipRawBytes(final int size) throws IOException { + if (size < 0) { + throw InvalidProtocolBufferException.negativeSize(); + } + + if (totalBytesRetired + bufferPos + size > currentLimit) { + // Read to the end of the stream anyway. + skipRawBytes(currentLimit - totalBytesRetired - bufferPos); + // Then fail. + throw InvalidProtocolBufferException.truncatedMessage(); + } + + if (size <= bufferSize - bufferPos) { + // We have all the bytes we need already. + bufferPos += size; + } else { + // Skipping more bytes than are in the buffer. First skip what we have. + int pos = bufferSize - bufferPos; + totalBytesRetired += bufferSize; + bufferPos = 0; + bufferSize = 0; + + // Then skip directly from the InputStream for the rest. + while (pos < size) { + final int n = raf.skipBytes(size - pos); + if (n <= 0) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + pos += n; + totalBytesRetired += n; + } + } + } + + public void seek(long pointer) throws IOException{ + if(pointer - totalBytesRetired >= 0 && pointer - totalBytesRetired < bufferSize){ + skipRawBytes((int) (pointer - getTotalBytesRead())); + } else { + totalBytesRetired = (int) pointer; + raf.seek(pointer); + bufferPos = 0; + bufferSize = 0; + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/CodedOutputStream.java b/DataExtractionOSM/src/com/google/protobuf/CodedOutputStream.java new file mode 100644 index 0000000000..58dd150673 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/CodedOutputStream.java @@ -0,0 +1,1029 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.OutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +/** + * Encodes and writes protocol message fields. + * + *

This class contains two kinds of methods: methods that write specific + * protocol message constructs and field types (e.g. {@link #writeTag} and + * {@link #writeInt32}) and methods that write low-level values (e.g. + * {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are + * writing encoded protocol messages, you should use the former methods, but if + * you are writing some other format of your own design, use the latter. + * + *

This class is totally unsynchronized. + * + * @author kneton@google.com Kenton Varda + */ +public final class CodedOutputStream { + private final byte[] buffer; + private final int limit; + private int position; + + private final OutputStream output; + + /** + * The buffer size used in {@link #newInstance(OutputStream)}. + */ + public static final int DEFAULT_BUFFER_SIZE = 4096; + + /** + * Returns the buffer size to efficiently write dataLength bytes to this + * CodedOutputStream. Used by AbstractMessageLite. + * + * @return the buffer size to efficiently write dataLength bytes to this + * CodedOutputStream. + */ + static int computePreferredBufferSize(int dataLength) { + if (dataLength > DEFAULT_BUFFER_SIZE) return DEFAULT_BUFFER_SIZE; + return dataLength; + } + + private CodedOutputStream(final byte[] buffer, final int offset, + final int length) { + output = null; + this.buffer = buffer; + position = offset; + limit = offset + length; + } + + private CodedOutputStream(final OutputStream output, final byte[] buffer) { + this.output = output; + this.buffer = buffer; + position = 0; + limit = buffer.length; + } + + /** + * Create a new {@code CodedOutputStream} wrapping the given + * {@code OutputStream}. + */ + public static CodedOutputStream newInstance(final OutputStream output) { + return newInstance(output, DEFAULT_BUFFER_SIZE); + } + + /** + * Create a new {@code CodedOutputStream} wrapping the given + * {@code OutputStream} with a given buffer size. + */ + public static CodedOutputStream newInstance(final OutputStream output, + final int bufferSize) { + return new CodedOutputStream(output, new byte[bufferSize]); + } + + /** + * Create a new {@code CodedOutputStream} that writes directly to the given + * byte array. If more bytes are written than fit in the array, + * {@link OutOfSpaceException} will be thrown. Writing directly to a flat + * array is faster than writing to an {@code OutputStream}. See also + * {@link ByteString#newCodedBuilder}. + */ + public static CodedOutputStream newInstance(final byte[] flatArray) { + return newInstance(flatArray, 0, flatArray.length); + } + + /** + * Create a new {@code CodedOutputStream} that writes directly to the given + * byte array slice. If more bytes are written than fit in the slice, + * {@link OutOfSpaceException} will be thrown. Writing directly to a flat + * array is faster than writing to an {@code OutputStream}. See also + * {@link ByteString#newCodedBuilder}. + */ + public static CodedOutputStream newInstance(final byte[] flatArray, + final int offset, + final int length) { + return new CodedOutputStream(flatArray, offset, length); + } + + // ----------------------------------------------------------------- + + /** Write a {@code double} field, including tag, to the stream. */ + public void writeDouble(final int fieldNumber, final double value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64); + writeDoubleNoTag(value); + } + + /** Write a {@code float} field, including tag, to the stream. */ + public void writeFloat(final int fieldNumber, final float value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32); + writeFloatNoTag(value); + } + + /** Write a {@code uint64} field, including tag, to the stream. */ + public void writeUInt64(final int fieldNumber, final long value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeUInt64NoTag(value); + } + + /** Write an {@code int64} field, including tag, to the stream. */ + public void writeInt64(final int fieldNumber, final long value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeInt64NoTag(value); + } + + /** Write an {@code int32} field, including tag, to the stream. */ + public void writeInt32(final int fieldNumber, final int value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeInt32NoTag(value); + } + + /** Write a {@code fixed64} field, including tag, to the stream. */ + public void writeFixed64(final int fieldNumber, final long value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64); + writeFixed64NoTag(value); + } + + /** Write a {@code fixed32} field, including tag, to the stream. */ + public void writeFixed32(final int fieldNumber, final int value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32); + writeFixed32NoTag(value); + } + + /** Write a {@code bool} field, including tag, to the stream. */ + public void writeBool(final int fieldNumber, final boolean value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeBoolNoTag(value); + } + + /** Write a {@code string} field, including tag, to the stream. */ + public void writeString(final int fieldNumber, final String value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); + writeStringNoTag(value); + } + + /** Write a {@code group} field, including tag, to the stream. */ + public void writeGroup(final int fieldNumber, final MessageLite value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP); + writeGroupNoTag(value); + writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP); + } + + /** + * Write a group represented by an {@link UnknownFieldSet}. + * + * @deprecated UnknownFieldSet now implements MessageLite, so you can just + * call {@link #writeGroup}. + */ + @Deprecated + public void writeUnknownGroup(final int fieldNumber, + final MessageLite value) + throws IOException { + writeGroup(fieldNumber, value); + } + + /** Write an embedded message field, including tag, to the stream. */ + public void writeMessage(final int fieldNumber, final MessageLite value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); + writeMessageNoTag(value); + } + + /** Write a {@code bytes} field, including tag, to the stream. */ + public void writeBytes(final int fieldNumber, final ByteString value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); + writeBytesNoTag(value); + } + + /** Write a {@code uint32} field, including tag, to the stream. */ + public void writeUInt32(final int fieldNumber, final int value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeUInt32NoTag(value); + } + + /** + * Write an enum field, including tag, to the stream. Caller is responsible + * for converting the enum value to its numeric value. + */ + public void writeEnum(final int fieldNumber, final int value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeEnumNoTag(value); + } + + /** Write an {@code sfixed32} field, including tag, to the stream. */ + public void writeSFixed32(final int fieldNumber, final int value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32); + writeSFixed32NoTag(value); + } + + /** Write an {@code sfixed64} field, including tag, to the stream. */ + public void writeSFixed64(final int fieldNumber, final long value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64); + writeSFixed64NoTag(value); + } + + /** Write an {@code sint32} field, including tag, to the stream. */ + public void writeSInt32(final int fieldNumber, final int value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeSInt32NoTag(value); + } + + /** Write an {@code sint64} field, including tag, to the stream. */ + public void writeSInt64(final int fieldNumber, final long value) + throws IOException { + writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT); + writeSInt64NoTag(value); + } + + /** + * Write a MessageSet extension field to the stream. For historical reasons, + * the wire format differs from normal fields. + */ + public void writeMessageSetExtension(final int fieldNumber, + final MessageLite value) + throws IOException { + writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP); + writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber); + writeMessage(WireFormat.MESSAGE_SET_MESSAGE, value); + writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP); + } + + /** + * Write an unparsed MessageSet extension field to the stream. For + * historical reasons, the wire format differs from normal fields. + */ + public void writeRawMessageSetExtension(final int fieldNumber, + final ByteString value) + throws IOException { + writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP); + writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber); + writeBytes(WireFormat.MESSAGE_SET_MESSAGE, value); + writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP); + } + + // ----------------------------------------------------------------- + + /** Write a {@code double} field to the stream. */ + public void writeDoubleNoTag(final double value) throws IOException { + writeRawLittleEndian64(Double.doubleToRawLongBits(value)); + } + + /** Write a {@code float} field to the stream. */ + public void writeFloatNoTag(final float value) throws IOException { + writeRawLittleEndian32(Float.floatToRawIntBits(value)); + } + + /** Write a {@code uint64} field to the stream. */ + public void writeUInt64NoTag(final long value) throws IOException { + writeRawVarint64(value); + } + + /** Write an {@code int64} field to the stream. */ + public void writeInt64NoTag(final long value) throws IOException { + writeRawVarint64(value); + } + + /** Write an {@code int32} field to the stream. */ + public void writeInt32NoTag(final int value) throws IOException { + if (value >= 0) { + writeRawVarint32(value); + } else { + // Must sign-extend. + writeRawVarint64(value); + } + } + + /** Write a {@code fixed64} field to the stream. */ + public void writeFixed64NoTag(final long value) throws IOException { + writeRawLittleEndian64(value); + } + + /** Write a {@code fixed32} field to the stream. */ + public void writeFixed32NoTag(final int value) throws IOException { + writeRawLittleEndian32(value); + } + + /** Write a {@code bool} field to the stream. */ + public void writeBoolNoTag(final boolean value) throws IOException { + writeRawByte(value ? 1 : 0); + } + + /** Write a {@code string} field to the stream. */ + public void writeStringNoTag(final String value) throws IOException { + // Unfortunately there does not appear to be any way to tell Java to encode + // UTF-8 directly into our buffer, so we have to let it create its own byte + // array and then copy. + final byte[] bytes = value.getBytes("UTF-8"); + writeRawVarint32(bytes.length); + writeRawBytes(bytes); + } + + /** Write a {@code group} field to the stream. */ + public void writeGroupNoTag(final MessageLite value) throws IOException { + value.writeTo(this); + } + + /** + * Write a group represented by an {@link UnknownFieldSet}. + * + * @deprecated UnknownFieldSet now implements MessageLite, so you can just + * call {@link #writeGroupNoTag}. + */ + @Deprecated + public void writeUnknownGroupNoTag(final MessageLite value) + throws IOException { + writeGroupNoTag(value); + } + + /** Write an embedded message field to the stream. */ + public void writeMessageNoTag(final MessageLite value) throws IOException { + writeRawVarint32(value.getSerializedSize()); + value.writeTo(this); + } + + /** Write a {@code bytes} field to the stream. */ + public void writeBytesNoTag(final ByteString value) throws IOException { + final byte[] bytes = value.toByteArray(); + writeRawVarint32(bytes.length); + writeRawBytes(bytes); + } + + /** Write a {@code uint32} field to the stream. */ + public void writeUInt32NoTag(final int value) throws IOException { + writeRawVarint32(value); + } + + /** + * Write an enum field to the stream. Caller is responsible + * for converting the enum value to its numeric value. + */ + public void writeEnumNoTag(final int value) throws IOException { + writeRawVarint32(value); + } + + /** Write an {@code sfixed32} field to the stream. */ + public void writeSFixed32NoTag(final int value) throws IOException { + writeRawLittleEndian32(value); + } + + /** Write an {@code sfixed64} field to the stream. */ + public void writeSFixed64NoTag(final long value) throws IOException { + writeRawLittleEndian64(value); + } + + /** Write an {@code sint32} field to the stream. */ + public void writeSInt32NoTag(final int value) throws IOException { + writeRawVarint32(encodeZigZag32(value)); + } + + /** Write an {@code sint64} field to the stream. */ + public void writeSInt64NoTag(final long value) throws IOException { + writeRawVarint64(encodeZigZag64(value)); + } + + // ================================================================= + + /** + * Compute the number of bytes that would be needed to encode a + * {@code double} field, including tag. + */ + public static int computeDoubleSize(final int fieldNumber, + final double value) { + return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code float} field, including tag. + */ + public static int computeFloatSize(final int fieldNumber, final float value) { + return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code uint64} field, including tag. + */ + public static int computeUInt64Size(final int fieldNumber, final long value) { + return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code int64} field, including tag. + */ + public static int computeInt64Size(final int fieldNumber, final long value) { + return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code int32} field, including tag. + */ + public static int computeInt32Size(final int fieldNumber, final int value) { + return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code fixed64} field, including tag. + */ + public static int computeFixed64Size(final int fieldNumber, + final long value) { + return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code fixed32} field, including tag. + */ + public static int computeFixed32Size(final int fieldNumber, + final int value) { + return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code bool} field, including tag. + */ + public static int computeBoolSize(final int fieldNumber, + final boolean value) { + return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code string} field, including tag. + */ + public static int computeStringSize(final int fieldNumber, + final String value) { + return computeTagSize(fieldNumber) + computeStringSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code group} field, including tag. + */ + public static int computeGroupSize(final int fieldNumber, + final MessageLite value) { + return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code group} field represented by an {@code UnknownFieldSet}, including + * tag. + * + * @deprecated UnknownFieldSet now implements MessageLite, so you can just + * call {@link #computeGroupSize}. + */ + @Deprecated + public static int computeUnknownGroupSize(final int fieldNumber, + final MessageLite value) { + return computeGroupSize(fieldNumber, value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * embedded message field, including tag. + */ + public static int computeMessageSize(final int fieldNumber, + final MessageLite value) { + return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code bytes} field, including tag. + */ + public static int computeBytesSize(final int fieldNumber, + final ByteString value) { + return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code uint32} field, including tag. + */ + public static int computeUInt32Size(final int fieldNumber, final int value) { + return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * enum field, including tag. Caller is responsible for converting the + * enum value to its numeric value. + */ + public static int computeEnumSize(final int fieldNumber, final int value) { + return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sfixed32} field, including tag. + */ + public static int computeSFixed32Size(final int fieldNumber, + final int value) { + return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sfixed64} field, including tag. + */ + public static int computeSFixed64Size(final int fieldNumber, + final long value) { + return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sint32} field, including tag. + */ + public static int computeSInt32Size(final int fieldNumber, final int value) { + return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sint64} field, including tag. + */ + public static int computeSInt64Size(final int fieldNumber, final long value) { + return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * MessageSet extension to the stream. For historical reasons, + * the wire format differs from normal fields. + */ + public static int computeMessageSetExtensionSize( + final int fieldNumber, final MessageLite value) { + return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 + + computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) + + computeMessageSize(WireFormat.MESSAGE_SET_MESSAGE, value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * unparsed MessageSet extension field to the stream. For + * historical reasons, the wire format differs from normal fields. + */ + public static int computeRawMessageSetExtensionSize( + final int fieldNumber, final ByteString value) { + return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 + + computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) + + computeBytesSize(WireFormat.MESSAGE_SET_MESSAGE, value); + } + + // ----------------------------------------------------------------- + + /** + * Compute the number of bytes that would be needed to encode a + * {@code double} field, including tag. + */ + public static int computeDoubleSizeNoTag(final double value) { + return LITTLE_ENDIAN_64_SIZE; + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code float} field, including tag. + */ + public static int computeFloatSizeNoTag(final float value) { + return LITTLE_ENDIAN_32_SIZE; + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code uint64} field, including tag. + */ + public static int computeUInt64SizeNoTag(final long value) { + return computeRawVarint64Size(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code int64} field, including tag. + */ + public static int computeInt64SizeNoTag(final long value) { + return computeRawVarint64Size(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code int32} field, including tag. + */ + public static int computeInt32SizeNoTag(final int value) { + if (value >= 0) { + return computeRawVarint32Size(value); + } else { + // Must sign-extend. + return 10; + } + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code fixed64} field. + */ + public static int computeFixed64SizeNoTag(final long value) { + return LITTLE_ENDIAN_64_SIZE; + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code fixed32} field. + */ + public static int computeFixed32SizeNoTag(final int value) { + return LITTLE_ENDIAN_32_SIZE; + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code bool} field. + */ + public static int computeBoolSizeNoTag(final boolean value) { + return 1; + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code string} field. + */ + public static int computeStringSizeNoTag(final String value) { + try { + final byte[] bytes = value.getBytes("UTF-8"); + return computeRawVarint32Size(bytes.length) + + bytes.length; + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported.", e); + } + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code group} field. + */ + public static int computeGroupSizeNoTag(final MessageLite value) { + return value.getSerializedSize(); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code group} field represented by an {@code UnknownFieldSet}, including + * tag. + * + * @deprecated UnknownFieldSet now implements MessageLite, so you can just + * call {@link #computeUnknownGroupSizeNoTag}. + */ + @Deprecated + public static int computeUnknownGroupSizeNoTag(final MessageLite value) { + return computeGroupSizeNoTag(value); + } + + /** + * Compute the number of bytes that would be needed to encode an embedded + * message field. + */ + public static int computeMessageSizeNoTag(final MessageLite value) { + final int size = value.getSerializedSize(); + return computeRawVarint32Size(size) + size; + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code bytes} field. + */ + public static int computeBytesSizeNoTag(final ByteString value) { + return computeRawVarint32Size(value.size()) + + value.size(); + } + + /** + * Compute the number of bytes that would be needed to encode a + * {@code uint32} field. + */ + public static int computeUInt32SizeNoTag(final int value) { + return computeRawVarint32Size(value); + } + + /** + * Compute the number of bytes that would be needed to encode an enum field. + * Caller is responsible for converting the enum value to its numeric value. + */ + public static int computeEnumSizeNoTag(final int value) { + return computeRawVarint32Size(value); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sfixed32} field. + */ + public static int computeSFixed32SizeNoTag(final int value) { + return LITTLE_ENDIAN_32_SIZE; + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sfixed64} field. + */ + public static int computeSFixed64SizeNoTag(final long value) { + return LITTLE_ENDIAN_64_SIZE; + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sint32} field. + */ + public static int computeSInt32SizeNoTag(final int value) { + return computeRawVarint32Size(encodeZigZag32(value)); + } + + /** + * Compute the number of bytes that would be needed to encode an + * {@code sint64} field. + */ + public static int computeSInt64SizeNoTag(final long value) { + return computeRawVarint64Size(encodeZigZag64(value)); + } + + // ================================================================= + + /** + * Internal helper that writes the current buffer to the output. The + * buffer position is reset to its initial value when this returns. + */ + private void refreshBuffer() throws IOException { + if (output == null) { + // We're writing to a single buffer. + throw new OutOfSpaceException(); + } + + // Since we have an output stream, this is our buffer + // and buffer offset == 0 + output.write(buffer, 0, position); + position = 0; + } + + /** + * Flushes the stream and forces any buffered bytes to be written. This + * does not flush the underlying OutputStream. + */ + public void flush() throws IOException { + if (output != null) { + refreshBuffer(); + } + } + + /** + * If writing to a flat array, return the space left in the array. + * Otherwise, throws {@code UnsupportedOperationException}. + */ + public int spaceLeft() { + if (output == null) { + return limit - position; + } else { + throw new UnsupportedOperationException( + "spaceLeft() can only be called on CodedOutputStreams that are " + + "writing to a flat array."); + } + } + + /** + * Verifies that {@link #spaceLeft()} returns zero. It's common to create + * a byte array that is exactly big enough to hold a message, then write to + * it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()} + * after writing verifies that the message was actually as big as expected, + * which can help catch bugs. + */ + public void checkNoSpaceLeft() { + if (spaceLeft() != 0) { + throw new IllegalStateException( + "Did not write as much data as expected."); + } + } + + /** + * If you create a CodedOutputStream around a simple flat array, you must + * not attempt to write more bytes than the array has space. Otherwise, + * this exception will be thrown. + */ + public static class OutOfSpaceException extends IOException { + private static final long serialVersionUID = -6947486886997889499L; + + OutOfSpaceException() { + super("CodedOutputStream was writing to a flat byte array and ran " + + "out of space."); + } + } + + /** Write a single byte. */ + public void writeRawByte(final byte value) throws IOException { + if (position == limit) { + refreshBuffer(); + } + + buffer[position++] = value; + } + + /** Write a single byte, represented by an integer value. */ + public void writeRawByte(final int value) throws IOException { + writeRawByte((byte) value); + } + + /** Write an array of bytes. */ + public void writeRawBytes(final byte[] value) throws IOException { + writeRawBytes(value, 0, value.length); + } + + /** Write part of an array of bytes. */ + public void writeRawBytes(final byte[] value, int offset, int length) + throws IOException { + if (limit - position >= length) { + // We have room in the current buffer. + System.arraycopy(value, offset, buffer, position, length); + position += length; + } else { + // Write extends past current buffer. Fill the rest of this buffer and + // flush. + final int bytesWritten = limit - position; + System.arraycopy(value, offset, buffer, position, bytesWritten); + offset += bytesWritten; + length -= bytesWritten; + position = limit; + refreshBuffer(); + + // Now deal with the rest. + // Since we have an output stream, this is our buffer + // and buffer offset == 0 + if (length <= limit) { + // Fits in new buffer. + System.arraycopy(value, offset, buffer, 0, length); + position = length; + } else { + // Write is very big. Let's do it all at once. + output.write(value, offset, length); + } + } + } + + /** Encode and write a tag. */ + public void writeTag(final int fieldNumber, final int wireType) + throws IOException { + writeRawVarint32(WireFormat.makeTag(fieldNumber, wireType)); + } + + /** Compute the number of bytes that would be needed to encode a tag. */ + public static int computeTagSize(final int fieldNumber) { + return computeRawVarint32Size(WireFormat.makeTag(fieldNumber, 0)); + } + + /** + * Encode and write a varint. {@code value} is treated as + * unsigned, so it won't be sign-extended if negative. + */ + public void writeRawVarint32(int value) throws IOException { + while (true) { + if ((value & ~0x7F) == 0) { + writeRawByte(value); + return; + } else { + writeRawByte((value & 0x7F) | 0x80); + value >>>= 7; + } + } + } + + /** + * Compute the number of bytes that would be needed to encode a varint. + * {@code value} is treated as unsigned, so it won't be sign-extended if + * negative. + */ + public static int computeRawVarint32Size(final int value) { + if ((value & (0xffffffff << 7)) == 0) return 1; + if ((value & (0xffffffff << 14)) == 0) return 2; + if ((value & (0xffffffff << 21)) == 0) return 3; + if ((value & (0xffffffff << 28)) == 0) return 4; + return 5; + } + + /** Encode and write a varint. */ + public void writeRawVarint64(long value) throws IOException { + while (true) { + if ((value & ~0x7FL) == 0) { + writeRawByte((int)value); + return; + } else { + writeRawByte(((int)value & 0x7F) | 0x80); + value >>>= 7; + } + } + } + + /** Compute the number of bytes that would be needed to encode a varint. */ + public static int computeRawVarint64Size(final long value) { + if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; + if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; + if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; + if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; + if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; + if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; + if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; + if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; + if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; + return 10; + } + + /** Write a little-endian 32-bit integer. */ + public void writeRawLittleEndian32(final int value) throws IOException { + writeRawByte((value ) & 0xFF); + writeRawByte((value >> 8) & 0xFF); + writeRawByte((value >> 16) & 0xFF); + writeRawByte((value >> 24) & 0xFF); + } + + public static final int LITTLE_ENDIAN_32_SIZE = 4; + + /** Write a little-endian 64-bit integer. */ + public void writeRawLittleEndian64(final long value) throws IOException { + writeRawByte((int)(value ) & 0xFF); + writeRawByte((int)(value >> 8) & 0xFF); + writeRawByte((int)(value >> 16) & 0xFF); + writeRawByte((int)(value >> 24) & 0xFF); + writeRawByte((int)(value >> 32) & 0xFF); + writeRawByte((int)(value >> 40) & 0xFF); + writeRawByte((int)(value >> 48) & 0xFF); + writeRawByte((int)(value >> 56) & 0xFF); + } + + public static final int LITTLE_ENDIAN_64_SIZE = 8; + + /** + * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers + * into values that can be efficiently encoded with varint. (Otherwise, + * negative values must be sign-extended to 64 bits to be varint encoded, + * thus always taking 10 bytes on the wire.) + * + * @param n A signed 32-bit integer. + * @return An unsigned 32-bit integer, stored in a signed int because + * Java has no explicit unsigned support. + */ + public static int encodeZigZag32(final int n) { + // Note: the right-shift must be arithmetic + return (n << 1) ^ (n >> 31); + } + + /** + * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers + * into values that can be efficiently encoded with varint. (Otherwise, + * negative values must be sign-extended to 64 bits to be varint encoded, + * thus always taking 10 bytes on the wire.) + * + * @param n A signed 64-bit integer. + * @return An unsigned 64-bit integer, stored in a signed int because + * Java has no explicit unsigned support. + */ + public static long encodeZigZag64(final long n) { + // Note: the right-shift must be arithmetic + return (n << 1) ^ (n >> 63); + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/DescriptorProtos.java b/DataExtractionOSM/src/com/google/protobuf/DescriptorProtos.java new file mode 100644 index 0000000000..b1bc828854 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/DescriptorProtos.java @@ -0,0 +1,9088 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/descriptor.proto + +package com.google.protobuf; + +public final class DescriptorProtos { + private DescriptorProtos() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public static final class FileDescriptorSet extends + com.google.protobuf.GeneratedMessage { + // Use FileDescriptorSet.newBuilder() to construct. + private FileDescriptorSet() { + initFields(); + } + private FileDescriptorSet(boolean noInit) {} + + private static final FileDescriptorSet defaultInstance; + public static FileDescriptorSet getDefaultInstance() { + return defaultInstance; + } + + public FileDescriptorSet getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_FileDescriptorSet_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_FileDescriptorSet_fieldAccessorTable; + } + + // repeated .google.protobuf.FileDescriptorProto file = 1; + public static final int FILE_FIELD_NUMBER = 1; + private java.util.List file_ = + java.util.Collections.emptyList(); + public java.util.List getFileList() { + return file_; + } + public int getFileCount() { return file_.size(); } + public com.google.protobuf.DescriptorProtos.FileDescriptorProto getFile(int index) { + return file_.get(index); + } + + private void initFields() { + } + public final boolean isInitialized() { + for (com.google.protobuf.DescriptorProtos.FileDescriptorProto element : getFileList()) { + if (!element.isInitialized()) return false; + } + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + for (com.google.protobuf.DescriptorProtos.FileDescriptorProto element : getFileList()) { + output.writeMessage(1, element); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + for (com.google.protobuf.DescriptorProtos.FileDescriptorProto element : getFileList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, element); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorSet parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.google.protobuf.DescriptorProtos.FileDescriptorSet prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private com.google.protobuf.DescriptorProtos.FileDescriptorSet result; + + // Construct using com.google.protobuf.DescriptorProtos.FileDescriptorSet.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new com.google.protobuf.DescriptorProtos.FileDescriptorSet(); + return builder; + } + + protected com.google.protobuf.DescriptorProtos.FileDescriptorSet internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new com.google.protobuf.DescriptorProtos.FileDescriptorSet(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.google.protobuf.DescriptorProtos.FileDescriptorSet.getDescriptor(); + } + + public com.google.protobuf.DescriptorProtos.FileDescriptorSet getDefaultInstanceForType() { + return com.google.protobuf.DescriptorProtos.FileDescriptorSet.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public com.google.protobuf.DescriptorProtos.FileDescriptorSet build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private com.google.protobuf.DescriptorProtos.FileDescriptorSet buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public com.google.protobuf.DescriptorProtos.FileDescriptorSet buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.file_ != java.util.Collections.EMPTY_LIST) { + result.file_ = + java.util.Collections.unmodifiableList(result.file_); + } + com.google.protobuf.DescriptorProtos.FileDescriptorSet returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.google.protobuf.DescriptorProtos.FileDescriptorSet) { + return mergeFrom((com.google.protobuf.DescriptorProtos.FileDescriptorSet)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.google.protobuf.DescriptorProtos.FileDescriptorSet other) { + if (other == com.google.protobuf.DescriptorProtos.FileDescriptorSet.getDefaultInstance()) return this; + if (!other.file_.isEmpty()) { + if (result.file_.isEmpty()) { + result.file_ = new java.util.ArrayList(); + } + result.file_.addAll(other.file_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + com.google.protobuf.DescriptorProtos.FileDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.FileDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addFile(subBuilder.buildPartial()); + break; + } + } + } + } + + + // repeated .google.protobuf.FileDescriptorProto file = 1; + public java.util.List getFileList() { + return java.util.Collections.unmodifiableList(result.file_); + } + public int getFileCount() { + return result.getFileCount(); + } + public com.google.protobuf.DescriptorProtos.FileDescriptorProto getFile(int index) { + return result.getFile(index); + } + public Builder setFile(int index, com.google.protobuf.DescriptorProtos.FileDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.file_.set(index, value); + return this; + } + public Builder setFile(int index, com.google.protobuf.DescriptorProtos.FileDescriptorProto.Builder builderForValue) { + result.file_.set(index, builderForValue.build()); + return this; + } + public Builder addFile(com.google.protobuf.DescriptorProtos.FileDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.file_.isEmpty()) { + result.file_ = new java.util.ArrayList(); + } + result.file_.add(value); + return this; + } + public Builder addFile(com.google.protobuf.DescriptorProtos.FileDescriptorProto.Builder builderForValue) { + if (result.file_.isEmpty()) { + result.file_ = new java.util.ArrayList(); + } + result.file_.add(builderForValue.build()); + return this; + } + public Builder addAllFile( + java.lang.Iterable values) { + if (result.file_.isEmpty()) { + result.file_ = new java.util.ArrayList(); + } + super.addAll(values, result.file_); + return this; + } + public Builder clearFile() { + result.file_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:google.protobuf.FileDescriptorSet) + } + + static { + defaultInstance = new FileDescriptorSet(true); + com.google.protobuf.DescriptorProtos.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorSet) + } + + public static final class FileDescriptorProto extends + com.google.protobuf.GeneratedMessage { + // Use FileDescriptorProto.newBuilder() to construct. + private FileDescriptorProto() { + initFields(); + } + private FileDescriptorProto(boolean noInit) {} + + private static final FileDescriptorProto defaultInstance; + public static FileDescriptorProto getDefaultInstance() { + return defaultInstance; + } + + public FileDescriptorProto getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_FileDescriptorProto_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_FileDescriptorProto_fieldAccessorTable; + } + + // optional string name = 1; + public static final int NAME_FIELD_NUMBER = 1; + private boolean hasName; + private java.lang.String name_ = ""; + public boolean hasName() { return hasName; } + public java.lang.String getName() { return name_; } + + // optional string package = 2; + public static final int PACKAGE_FIELD_NUMBER = 2; + private boolean hasPackage; + private java.lang.String package_ = ""; + public boolean hasPackage() { return hasPackage; } + public java.lang.String getPackage() { return package_; } + + // repeated string dependency = 3; + public static final int DEPENDENCY_FIELD_NUMBER = 3; + private java.util.List dependency_ = + java.util.Collections.emptyList(); + public java.util.List getDependencyList() { + return dependency_; + } + public int getDependencyCount() { return dependency_.size(); } + public java.lang.String getDependency(int index) { + return dependency_.get(index); + } + + // repeated .google.protobuf.DescriptorProto message_type = 4; + public static final int MESSAGE_TYPE_FIELD_NUMBER = 4; + private java.util.List messageType_ = + java.util.Collections.emptyList(); + public java.util.List getMessageTypeList() { + return messageType_; + } + public int getMessageTypeCount() { return messageType_.size(); } + public com.google.protobuf.DescriptorProtos.DescriptorProto getMessageType(int index) { + return messageType_.get(index); + } + + // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; + public static final int ENUM_TYPE_FIELD_NUMBER = 5; + private java.util.List enumType_ = + java.util.Collections.emptyList(); + public java.util.List getEnumTypeList() { + return enumType_; + } + public int getEnumTypeCount() { return enumType_.size(); } + public com.google.protobuf.DescriptorProtos.EnumDescriptorProto getEnumType(int index) { + return enumType_.get(index); + } + + // repeated .google.protobuf.ServiceDescriptorProto service = 6; + public static final int SERVICE_FIELD_NUMBER = 6; + private java.util.List service_ = + java.util.Collections.emptyList(); + public java.util.List getServiceList() { + return service_; + } + public int getServiceCount() { return service_.size(); } + public com.google.protobuf.DescriptorProtos.ServiceDescriptorProto getService(int index) { + return service_.get(index); + } + + // repeated .google.protobuf.FieldDescriptorProto extension = 7; + public static final int EXTENSION_FIELD_NUMBER = 7; + private java.util.List extension_ = + java.util.Collections.emptyList(); + public java.util.List getExtensionList() { + return extension_; + } + public int getExtensionCount() { return extension_.size(); } + public com.google.protobuf.DescriptorProtos.FieldDescriptorProto getExtension(int index) { + return extension_.get(index); + } + + // optional .google.protobuf.FileOptions options = 8; + public static final int OPTIONS_FIELD_NUMBER = 8; + private boolean hasOptions; + private com.google.protobuf.DescriptorProtos.FileOptions options_; + public boolean hasOptions() { return hasOptions; } + public com.google.protobuf.DescriptorProtos.FileOptions getOptions() { return options_; } + + private void initFields() { + options_ = com.google.protobuf.DescriptorProtos.FileOptions.getDefaultInstance(); + } + public final boolean isInitialized() { + for (com.google.protobuf.DescriptorProtos.DescriptorProto element : getMessageTypeList()) { + if (!element.isInitialized()) return false; + } + for (com.google.protobuf.DescriptorProtos.EnumDescriptorProto element : getEnumTypeList()) { + if (!element.isInitialized()) return false; + } + for (com.google.protobuf.DescriptorProtos.ServiceDescriptorProto element : getServiceList()) { + if (!element.isInitialized()) return false; + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getExtensionList()) { + if (!element.isInitialized()) return false; + } + if (hasOptions()) { + if (!getOptions().isInitialized()) return false; + } + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasName()) { + output.writeString(1, getName()); + } + if (hasPackage()) { + output.writeString(2, getPackage()); + } + for (java.lang.String element : getDependencyList()) { + output.writeString(3, element); + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto element : getMessageTypeList()) { + output.writeMessage(4, element); + } + for (com.google.protobuf.DescriptorProtos.EnumDescriptorProto element : getEnumTypeList()) { + output.writeMessage(5, element); + } + for (com.google.protobuf.DescriptorProtos.ServiceDescriptorProto element : getServiceList()) { + output.writeMessage(6, element); + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getExtensionList()) { + output.writeMessage(7, element); + } + if (hasOptions()) { + output.writeMessage(8, getOptions()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasName()) { + size += com.google.protobuf.CodedOutputStream + .computeStringSize(1, getName()); + } + if (hasPackage()) { + size += com.google.protobuf.CodedOutputStream + .computeStringSize(2, getPackage()); + } + { + int dataSize = 0; + for (java.lang.String element : getDependencyList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeStringSizeNoTag(element); + } + size += dataSize; + size += 1 * getDependencyList().size(); + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto element : getMessageTypeList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, element); + } + for (com.google.protobuf.DescriptorProtos.EnumDescriptorProto element : getEnumTypeList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, element); + } + for (com.google.protobuf.DescriptorProtos.ServiceDescriptorProto element : getServiceList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, element); + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getExtensionList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(7, element); + } + if (hasOptions()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(8, getOptions()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.FileDescriptorProto parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.google.protobuf.DescriptorProtos.FileDescriptorProto prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private com.google.protobuf.DescriptorProtos.FileDescriptorProto result; + + // Construct using com.google.protobuf.DescriptorProtos.FileDescriptorProto.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new com.google.protobuf.DescriptorProtos.FileDescriptorProto(); + return builder; + } + + protected com.google.protobuf.DescriptorProtos.FileDescriptorProto internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new com.google.protobuf.DescriptorProtos.FileDescriptorProto(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.google.protobuf.DescriptorProtos.FileDescriptorProto.getDescriptor(); + } + + public com.google.protobuf.DescriptorProtos.FileDescriptorProto getDefaultInstanceForType() { + return com.google.protobuf.DescriptorProtos.FileDescriptorProto.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public com.google.protobuf.DescriptorProtos.FileDescriptorProto build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private com.google.protobuf.DescriptorProtos.FileDescriptorProto buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public com.google.protobuf.DescriptorProtos.FileDescriptorProto buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.dependency_ != java.util.Collections.EMPTY_LIST) { + result.dependency_ = + java.util.Collections.unmodifiableList(result.dependency_); + } + if (result.messageType_ != java.util.Collections.EMPTY_LIST) { + result.messageType_ = + java.util.Collections.unmodifiableList(result.messageType_); + } + if (result.enumType_ != java.util.Collections.EMPTY_LIST) { + result.enumType_ = + java.util.Collections.unmodifiableList(result.enumType_); + } + if (result.service_ != java.util.Collections.EMPTY_LIST) { + result.service_ = + java.util.Collections.unmodifiableList(result.service_); + } + if (result.extension_ != java.util.Collections.EMPTY_LIST) { + result.extension_ = + java.util.Collections.unmodifiableList(result.extension_); + } + com.google.protobuf.DescriptorProtos.FileDescriptorProto returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.google.protobuf.DescriptorProtos.FileDescriptorProto) { + return mergeFrom((com.google.protobuf.DescriptorProtos.FileDescriptorProto)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.google.protobuf.DescriptorProtos.FileDescriptorProto other) { + if (other == com.google.protobuf.DescriptorProtos.FileDescriptorProto.getDefaultInstance()) return this; + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasPackage()) { + setPackage(other.getPackage()); + } + if (!other.dependency_.isEmpty()) { + if (result.dependency_.isEmpty()) { + result.dependency_ = new java.util.ArrayList(); + } + result.dependency_.addAll(other.dependency_); + } + if (!other.messageType_.isEmpty()) { + if (result.messageType_.isEmpty()) { + result.messageType_ = new java.util.ArrayList(); + } + result.messageType_.addAll(other.messageType_); + } + if (!other.enumType_.isEmpty()) { + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + result.enumType_.addAll(other.enumType_); + } + if (!other.service_.isEmpty()) { + if (result.service_.isEmpty()) { + result.service_ = new java.util.ArrayList(); + } + result.service_.addAll(other.service_); + } + if (!other.extension_.isEmpty()) { + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + result.extension_.addAll(other.extension_); + } + if (other.hasOptions()) { + mergeOptions(other.getOptions()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + setName(input.readString()); + break; + } + case 18: { + setPackage(input.readString()); + break; + } + case 26: { + addDependency(input.readString()); + break; + } + case 34: { + com.google.protobuf.DescriptorProtos.DescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.DescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addMessageType(subBuilder.buildPartial()); + break; + } + case 42: { + com.google.protobuf.DescriptorProtos.EnumDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.EnumDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addEnumType(subBuilder.buildPartial()); + break; + } + case 50: { + com.google.protobuf.DescriptorProtos.ServiceDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.ServiceDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addService(subBuilder.buildPartial()); + break; + } + case 58: { + com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.FieldDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addExtension(subBuilder.buildPartial()); + break; + } + case 66: { + com.google.protobuf.DescriptorProtos.FileOptions.Builder subBuilder = com.google.protobuf.DescriptorProtos.FileOptions.newBuilder(); + if (hasOptions()) { + subBuilder.mergeFrom(getOptions()); + } + input.readMessage(subBuilder, extensionRegistry); + setOptions(subBuilder.buildPartial()); + break; + } + } + } + } + + + // optional string name = 1; + public boolean hasName() { + return result.hasName(); + } + public java.lang.String getName() { + return result.getName(); + } + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasName = true; + result.name_ = value; + return this; + } + public Builder clearName() { + result.hasName = false; + result.name_ = getDefaultInstance().getName(); + return this; + } + + // optional string package = 2; + public boolean hasPackage() { + return result.hasPackage(); + } + public java.lang.String getPackage() { + return result.getPackage(); + } + public Builder setPackage(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasPackage = true; + result.package_ = value; + return this; + } + public Builder clearPackage() { + result.hasPackage = false; + result.package_ = getDefaultInstance().getPackage(); + return this; + } + + // repeated string dependency = 3; + public java.util.List getDependencyList() { + return java.util.Collections.unmodifiableList(result.dependency_); + } + public int getDependencyCount() { + return result.getDependencyCount(); + } + public java.lang.String getDependency(int index) { + return result.getDependency(index); + } + public Builder setDependency(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.dependency_.set(index, value); + return this; + } + public Builder addDependency(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.dependency_.isEmpty()) { + result.dependency_ = new java.util.ArrayList(); + } + result.dependency_.add(value); + return this; + } + public Builder addAllDependency( + java.lang.Iterable values) { + if (result.dependency_.isEmpty()) { + result.dependency_ = new java.util.ArrayList(); + } + super.addAll(values, result.dependency_); + return this; + } + public Builder clearDependency() { + result.dependency_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.DescriptorProto message_type = 4; + public java.util.List getMessageTypeList() { + return java.util.Collections.unmodifiableList(result.messageType_); + } + public int getMessageTypeCount() { + return result.getMessageTypeCount(); + } + public com.google.protobuf.DescriptorProtos.DescriptorProto getMessageType(int index) { + return result.getMessageType(index); + } + public Builder setMessageType(int index, com.google.protobuf.DescriptorProtos.DescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.messageType_.set(index, value); + return this; + } + public Builder setMessageType(int index, com.google.protobuf.DescriptorProtos.DescriptorProto.Builder builderForValue) { + result.messageType_.set(index, builderForValue.build()); + return this; + } + public Builder addMessageType(com.google.protobuf.DescriptorProtos.DescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.messageType_.isEmpty()) { + result.messageType_ = new java.util.ArrayList(); + } + result.messageType_.add(value); + return this; + } + public Builder addMessageType(com.google.protobuf.DescriptorProtos.DescriptorProto.Builder builderForValue) { + if (result.messageType_.isEmpty()) { + result.messageType_ = new java.util.ArrayList(); + } + result.messageType_.add(builderForValue.build()); + return this; + } + public Builder addAllMessageType( + java.lang.Iterable values) { + if (result.messageType_.isEmpty()) { + result.messageType_ = new java.util.ArrayList(); + } + super.addAll(values, result.messageType_); + return this; + } + public Builder clearMessageType() { + result.messageType_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; + public java.util.List getEnumTypeList() { + return java.util.Collections.unmodifiableList(result.enumType_); + } + public int getEnumTypeCount() { + return result.getEnumTypeCount(); + } + public com.google.protobuf.DescriptorProtos.EnumDescriptorProto getEnumType(int index) { + return result.getEnumType(index); + } + public Builder setEnumType(int index, com.google.protobuf.DescriptorProtos.EnumDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.enumType_.set(index, value); + return this; + } + public Builder setEnumType(int index, com.google.protobuf.DescriptorProtos.EnumDescriptorProto.Builder builderForValue) { + result.enumType_.set(index, builderForValue.build()); + return this; + } + public Builder addEnumType(com.google.protobuf.DescriptorProtos.EnumDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + result.enumType_.add(value); + return this; + } + public Builder addEnumType(com.google.protobuf.DescriptorProtos.EnumDescriptorProto.Builder builderForValue) { + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + result.enumType_.add(builderForValue.build()); + return this; + } + public Builder addAllEnumType( + java.lang.Iterable values) { + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + super.addAll(values, result.enumType_); + return this; + } + public Builder clearEnumType() { + result.enumType_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.ServiceDescriptorProto service = 6; + public java.util.List getServiceList() { + return java.util.Collections.unmodifiableList(result.service_); + } + public int getServiceCount() { + return result.getServiceCount(); + } + public com.google.protobuf.DescriptorProtos.ServiceDescriptorProto getService(int index) { + return result.getService(index); + } + public Builder setService(int index, com.google.protobuf.DescriptorProtos.ServiceDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.service_.set(index, value); + return this; + } + public Builder setService(int index, com.google.protobuf.DescriptorProtos.ServiceDescriptorProto.Builder builderForValue) { + result.service_.set(index, builderForValue.build()); + return this; + } + public Builder addService(com.google.protobuf.DescriptorProtos.ServiceDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.service_.isEmpty()) { + result.service_ = new java.util.ArrayList(); + } + result.service_.add(value); + return this; + } + public Builder addService(com.google.protobuf.DescriptorProtos.ServiceDescriptorProto.Builder builderForValue) { + if (result.service_.isEmpty()) { + result.service_ = new java.util.ArrayList(); + } + result.service_.add(builderForValue.build()); + return this; + } + public Builder addAllService( + java.lang.Iterable values) { + if (result.service_.isEmpty()) { + result.service_ = new java.util.ArrayList(); + } + super.addAll(values, result.service_); + return this; + } + public Builder clearService() { + result.service_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.FieldDescriptorProto extension = 7; + public java.util.List getExtensionList() { + return java.util.Collections.unmodifiableList(result.extension_); + } + public int getExtensionCount() { + return result.getExtensionCount(); + } + public com.google.protobuf.DescriptorProtos.FieldDescriptorProto getExtension(int index) { + return result.getExtension(index); + } + public Builder setExtension(int index, com.google.protobuf.DescriptorProtos.FieldDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.extension_.set(index, value); + return this; + } + public Builder setExtension(int index, com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder builderForValue) { + result.extension_.set(index, builderForValue.build()); + return this; + } + public Builder addExtension(com.google.protobuf.DescriptorProtos.FieldDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + result.extension_.add(value); + return this; + } + public Builder addExtension(com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder builderForValue) { + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + result.extension_.add(builderForValue.build()); + return this; + } + public Builder addAllExtension( + java.lang.Iterable values) { + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + super.addAll(values, result.extension_); + return this; + } + public Builder clearExtension() { + result.extension_ = java.util.Collections.emptyList(); + return this; + } + + // optional .google.protobuf.FileOptions options = 8; + public boolean hasOptions() { + return result.hasOptions(); + } + public com.google.protobuf.DescriptorProtos.FileOptions getOptions() { + return result.getOptions(); + } + public Builder setOptions(com.google.protobuf.DescriptorProtos.FileOptions value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasOptions = true; + result.options_ = value; + return this; + } + public Builder setOptions(com.google.protobuf.DescriptorProtos.FileOptions.Builder builderForValue) { + result.hasOptions = true; + result.options_ = builderForValue.build(); + return this; + } + public Builder mergeOptions(com.google.protobuf.DescriptorProtos.FileOptions value) { + if (result.hasOptions() && + result.options_ != com.google.protobuf.DescriptorProtos.FileOptions.getDefaultInstance()) { + result.options_ = + com.google.protobuf.DescriptorProtos.FileOptions.newBuilder(result.options_).mergeFrom(value).buildPartial(); + } else { + result.options_ = value; + } + result.hasOptions = true; + return this; + } + public Builder clearOptions() { + result.hasOptions = false; + result.options_ = com.google.protobuf.DescriptorProtos.FileOptions.getDefaultInstance(); + return this; + } + + // @@protoc_insertion_point(builder_scope:google.protobuf.FileDescriptorProto) + } + + static { + defaultInstance = new FileDescriptorProto(true); + com.google.protobuf.DescriptorProtos.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto) + } + + public static final class DescriptorProto extends + com.google.protobuf.GeneratedMessage { + // Use DescriptorProto.newBuilder() to construct. + private DescriptorProto() { + initFields(); + } + private DescriptorProto(boolean noInit) {} + + private static final DescriptorProto defaultInstance; + public static DescriptorProto getDefaultInstance() { + return defaultInstance; + } + + public DescriptorProto getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_DescriptorProto_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_DescriptorProto_fieldAccessorTable; + } + + public static final class ExtensionRange extends + com.google.protobuf.GeneratedMessage { + // Use ExtensionRange.newBuilder() to construct. + private ExtensionRange() { + initFields(); + } + private ExtensionRange(boolean noInit) {} + + private static final ExtensionRange defaultInstance; + public static ExtensionRange getDefaultInstance() { + return defaultInstance; + } + + public ExtensionRange getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_DescriptorProto_ExtensionRange_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_DescriptorProto_ExtensionRange_fieldAccessorTable; + } + + // optional int32 start = 1; + public static final int START_FIELD_NUMBER = 1; + private boolean hasStart; + private int start_ = 0; + public boolean hasStart() { return hasStart; } + public int getStart() { return start_; } + + // optional int32 end = 2; + public static final int END_FIELD_NUMBER = 2; + private boolean hasEnd; + private int end_ = 0; + public boolean hasEnd() { return hasEnd; } + public int getEnd() { return end_; } + + private void initFields() { + } + public final boolean isInitialized() { + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasStart()) { + output.writeInt32(1, getStart()); + } + if (hasEnd()) { + output.writeInt32(2, getEnd()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasStart()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, getStart()); + } + if (hasEnd()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, getEnd()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange result; + + // Construct using com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange(); + return builder; + } + + protected com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.getDescriptor(); + } + + public com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange getDefaultInstanceForType() { + return com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange) { + return mergeFrom((com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange other) { + if (other == com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.getDefaultInstance()) return this; + if (other.hasStart()) { + setStart(other.getStart()); + } + if (other.hasEnd()) { + setEnd(other.getEnd()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setStart(input.readInt32()); + break; + } + case 16: { + setEnd(input.readInt32()); + break; + } + } + } + } + + + // optional int32 start = 1; + public boolean hasStart() { + return result.hasStart(); + } + public int getStart() { + return result.getStart(); + } + public Builder setStart(int value) { + result.hasStart = true; + result.start_ = value; + return this; + } + public Builder clearStart() { + result.hasStart = false; + result.start_ = 0; + return this; + } + + // optional int32 end = 2; + public boolean hasEnd() { + return result.hasEnd(); + } + public int getEnd() { + return result.getEnd(); + } + public Builder setEnd(int value) { + result.hasEnd = true; + result.end_ = value; + return this; + } + public Builder clearEnd() { + result.hasEnd = false; + result.end_ = 0; + return this; + } + + // @@protoc_insertion_point(builder_scope:google.protobuf.DescriptorProto.ExtensionRange) + } + + static { + defaultInstance = new ExtensionRange(true); + com.google.protobuf.DescriptorProtos.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ExtensionRange) + } + + // optional string name = 1; + public static final int NAME_FIELD_NUMBER = 1; + private boolean hasName; + private java.lang.String name_ = ""; + public boolean hasName() { return hasName; } + public java.lang.String getName() { return name_; } + + // repeated .google.protobuf.FieldDescriptorProto field = 2; + public static final int FIELD_FIELD_NUMBER = 2; + private java.util.List field_ = + java.util.Collections.emptyList(); + public java.util.List getFieldList() { + return field_; + } + public int getFieldCount() { return field_.size(); } + public com.google.protobuf.DescriptorProtos.FieldDescriptorProto getField(int index) { + return field_.get(index); + } + + // repeated .google.protobuf.FieldDescriptorProto extension = 6; + public static final int EXTENSION_FIELD_NUMBER = 6; + private java.util.List extension_ = + java.util.Collections.emptyList(); + public java.util.List getExtensionList() { + return extension_; + } + public int getExtensionCount() { return extension_.size(); } + public com.google.protobuf.DescriptorProtos.FieldDescriptorProto getExtension(int index) { + return extension_.get(index); + } + + // repeated .google.protobuf.DescriptorProto nested_type = 3; + public static final int NESTED_TYPE_FIELD_NUMBER = 3; + private java.util.List nestedType_ = + java.util.Collections.emptyList(); + public java.util.List getNestedTypeList() { + return nestedType_; + } + public int getNestedTypeCount() { return nestedType_.size(); } + public com.google.protobuf.DescriptorProtos.DescriptorProto getNestedType(int index) { + return nestedType_.get(index); + } + + // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; + public static final int ENUM_TYPE_FIELD_NUMBER = 4; + private java.util.List enumType_ = + java.util.Collections.emptyList(); + public java.util.List getEnumTypeList() { + return enumType_; + } + public int getEnumTypeCount() { return enumType_.size(); } + public com.google.protobuf.DescriptorProtos.EnumDescriptorProto getEnumType(int index) { + return enumType_.get(index); + } + + // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; + public static final int EXTENSION_RANGE_FIELD_NUMBER = 5; + private java.util.List extensionRange_ = + java.util.Collections.emptyList(); + public java.util.List getExtensionRangeList() { + return extensionRange_; + } + public int getExtensionRangeCount() { return extensionRange_.size(); } + public com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange getExtensionRange(int index) { + return extensionRange_.get(index); + } + + // optional .google.protobuf.MessageOptions options = 7; + public static final int OPTIONS_FIELD_NUMBER = 7; + private boolean hasOptions; + private com.google.protobuf.DescriptorProtos.MessageOptions options_; + public boolean hasOptions() { return hasOptions; } + public com.google.protobuf.DescriptorProtos.MessageOptions getOptions() { return options_; } + + private void initFields() { + options_ = com.google.protobuf.DescriptorProtos.MessageOptions.getDefaultInstance(); + } + public final boolean isInitialized() { + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getFieldList()) { + if (!element.isInitialized()) return false; + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getExtensionList()) { + if (!element.isInitialized()) return false; + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto element : getNestedTypeList()) { + if (!element.isInitialized()) return false; + } + for (com.google.protobuf.DescriptorProtos.EnumDescriptorProto element : getEnumTypeList()) { + if (!element.isInitialized()) return false; + } + if (hasOptions()) { + if (!getOptions().isInitialized()) return false; + } + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasName()) { + output.writeString(1, getName()); + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getFieldList()) { + output.writeMessage(2, element); + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto element : getNestedTypeList()) { + output.writeMessage(3, element); + } + for (com.google.protobuf.DescriptorProtos.EnumDescriptorProto element : getEnumTypeList()) { + output.writeMessage(4, element); + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange element : getExtensionRangeList()) { + output.writeMessage(5, element); + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getExtensionList()) { + output.writeMessage(6, element); + } + if (hasOptions()) { + output.writeMessage(7, getOptions()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasName()) { + size += com.google.protobuf.CodedOutputStream + .computeStringSize(1, getName()); + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getFieldList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, element); + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto element : getNestedTypeList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, element); + } + for (com.google.protobuf.DescriptorProtos.EnumDescriptorProto element : getEnumTypeList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, element); + } + for (com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange element : getExtensionRangeList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, element); + } + for (com.google.protobuf.DescriptorProtos.FieldDescriptorProto element : getExtensionList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, element); + } + if (hasOptions()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(7, getOptions()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.google.protobuf.DescriptorProtos.DescriptorProto parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.google.protobuf.DescriptorProtos.DescriptorProto prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private com.google.protobuf.DescriptorProtos.DescriptorProto result; + + // Construct using com.google.protobuf.DescriptorProtos.DescriptorProto.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new com.google.protobuf.DescriptorProtos.DescriptorProto(); + return builder; + } + + protected com.google.protobuf.DescriptorProtos.DescriptorProto internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new com.google.protobuf.DescriptorProtos.DescriptorProto(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.google.protobuf.DescriptorProtos.DescriptorProto.getDescriptor(); + } + + public com.google.protobuf.DescriptorProtos.DescriptorProto getDefaultInstanceForType() { + return com.google.protobuf.DescriptorProtos.DescriptorProto.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public com.google.protobuf.DescriptorProtos.DescriptorProto build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private com.google.protobuf.DescriptorProtos.DescriptorProto buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public com.google.protobuf.DescriptorProtos.DescriptorProto buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.field_ != java.util.Collections.EMPTY_LIST) { + result.field_ = + java.util.Collections.unmodifiableList(result.field_); + } + if (result.extension_ != java.util.Collections.EMPTY_LIST) { + result.extension_ = + java.util.Collections.unmodifiableList(result.extension_); + } + if (result.nestedType_ != java.util.Collections.EMPTY_LIST) { + result.nestedType_ = + java.util.Collections.unmodifiableList(result.nestedType_); + } + if (result.enumType_ != java.util.Collections.EMPTY_LIST) { + result.enumType_ = + java.util.Collections.unmodifiableList(result.enumType_); + } + if (result.extensionRange_ != java.util.Collections.EMPTY_LIST) { + result.extensionRange_ = + java.util.Collections.unmodifiableList(result.extensionRange_); + } + com.google.protobuf.DescriptorProtos.DescriptorProto returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.google.protobuf.DescriptorProtos.DescriptorProto) { + return mergeFrom((com.google.protobuf.DescriptorProtos.DescriptorProto)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.google.protobuf.DescriptorProtos.DescriptorProto other) { + if (other == com.google.protobuf.DescriptorProtos.DescriptorProto.getDefaultInstance()) return this; + if (other.hasName()) { + setName(other.getName()); + } + if (!other.field_.isEmpty()) { + if (result.field_.isEmpty()) { + result.field_ = new java.util.ArrayList(); + } + result.field_.addAll(other.field_); + } + if (!other.extension_.isEmpty()) { + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + result.extension_.addAll(other.extension_); + } + if (!other.nestedType_.isEmpty()) { + if (result.nestedType_.isEmpty()) { + result.nestedType_ = new java.util.ArrayList(); + } + result.nestedType_.addAll(other.nestedType_); + } + if (!other.enumType_.isEmpty()) { + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + result.enumType_.addAll(other.enumType_); + } + if (!other.extensionRange_.isEmpty()) { + if (result.extensionRange_.isEmpty()) { + result.extensionRange_ = new java.util.ArrayList(); + } + result.extensionRange_.addAll(other.extensionRange_); + } + if (other.hasOptions()) { + mergeOptions(other.getOptions()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + setName(input.readString()); + break; + } + case 18: { + com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.FieldDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addField(subBuilder.buildPartial()); + break; + } + case 26: { + com.google.protobuf.DescriptorProtos.DescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.DescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addNestedType(subBuilder.buildPartial()); + break; + } + case 34: { + com.google.protobuf.DescriptorProtos.EnumDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.EnumDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addEnumType(subBuilder.buildPartial()); + break; + } + case 42: { + com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.Builder subBuilder = com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addExtensionRange(subBuilder.buildPartial()); + break; + } + case 50: { + com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder subBuilder = com.google.protobuf.DescriptorProtos.FieldDescriptorProto.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addExtension(subBuilder.buildPartial()); + break; + } + case 58: { + com.google.protobuf.DescriptorProtos.MessageOptions.Builder subBuilder = com.google.protobuf.DescriptorProtos.MessageOptions.newBuilder(); + if (hasOptions()) { + subBuilder.mergeFrom(getOptions()); + } + input.readMessage(subBuilder, extensionRegistry); + setOptions(subBuilder.buildPartial()); + break; + } + } + } + } + + + // optional string name = 1; + public boolean hasName() { + return result.hasName(); + } + public java.lang.String getName() { + return result.getName(); + } + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasName = true; + result.name_ = value; + return this; + } + public Builder clearName() { + result.hasName = false; + result.name_ = getDefaultInstance().getName(); + return this; + } + + // repeated .google.protobuf.FieldDescriptorProto field = 2; + public java.util.List getFieldList() { + return java.util.Collections.unmodifiableList(result.field_); + } + public int getFieldCount() { + return result.getFieldCount(); + } + public com.google.protobuf.DescriptorProtos.FieldDescriptorProto getField(int index) { + return result.getField(index); + } + public Builder setField(int index, com.google.protobuf.DescriptorProtos.FieldDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.field_.set(index, value); + return this; + } + public Builder setField(int index, com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder builderForValue) { + result.field_.set(index, builderForValue.build()); + return this; + } + public Builder addField(com.google.protobuf.DescriptorProtos.FieldDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.field_.isEmpty()) { + result.field_ = new java.util.ArrayList(); + } + result.field_.add(value); + return this; + } + public Builder addField(com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder builderForValue) { + if (result.field_.isEmpty()) { + result.field_ = new java.util.ArrayList(); + } + result.field_.add(builderForValue.build()); + return this; + } + public Builder addAllField( + java.lang.Iterable values) { + if (result.field_.isEmpty()) { + result.field_ = new java.util.ArrayList(); + } + super.addAll(values, result.field_); + return this; + } + public Builder clearField() { + result.field_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.FieldDescriptorProto extension = 6; + public java.util.List getExtensionList() { + return java.util.Collections.unmodifiableList(result.extension_); + } + public int getExtensionCount() { + return result.getExtensionCount(); + } + public com.google.protobuf.DescriptorProtos.FieldDescriptorProto getExtension(int index) { + return result.getExtension(index); + } + public Builder setExtension(int index, com.google.protobuf.DescriptorProtos.FieldDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.extension_.set(index, value); + return this; + } + public Builder setExtension(int index, com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder builderForValue) { + result.extension_.set(index, builderForValue.build()); + return this; + } + public Builder addExtension(com.google.protobuf.DescriptorProtos.FieldDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + result.extension_.add(value); + return this; + } + public Builder addExtension(com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Builder builderForValue) { + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + result.extension_.add(builderForValue.build()); + return this; + } + public Builder addAllExtension( + java.lang.Iterable values) { + if (result.extension_.isEmpty()) { + result.extension_ = new java.util.ArrayList(); + } + super.addAll(values, result.extension_); + return this; + } + public Builder clearExtension() { + result.extension_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.DescriptorProto nested_type = 3; + public java.util.List getNestedTypeList() { + return java.util.Collections.unmodifiableList(result.nestedType_); + } + public int getNestedTypeCount() { + return result.getNestedTypeCount(); + } + public com.google.protobuf.DescriptorProtos.DescriptorProto getNestedType(int index) { + return result.getNestedType(index); + } + public Builder setNestedType(int index, com.google.protobuf.DescriptorProtos.DescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.nestedType_.set(index, value); + return this; + } + public Builder setNestedType(int index, com.google.protobuf.DescriptorProtos.DescriptorProto.Builder builderForValue) { + result.nestedType_.set(index, builderForValue.build()); + return this; + } + public Builder addNestedType(com.google.protobuf.DescriptorProtos.DescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.nestedType_.isEmpty()) { + result.nestedType_ = new java.util.ArrayList(); + } + result.nestedType_.add(value); + return this; + } + public Builder addNestedType(com.google.protobuf.DescriptorProtos.DescriptorProto.Builder builderForValue) { + if (result.nestedType_.isEmpty()) { + result.nestedType_ = new java.util.ArrayList(); + } + result.nestedType_.add(builderForValue.build()); + return this; + } + public Builder addAllNestedType( + java.lang.Iterable values) { + if (result.nestedType_.isEmpty()) { + result.nestedType_ = new java.util.ArrayList(); + } + super.addAll(values, result.nestedType_); + return this; + } + public Builder clearNestedType() { + result.nestedType_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; + public java.util.List getEnumTypeList() { + return java.util.Collections.unmodifiableList(result.enumType_); + } + public int getEnumTypeCount() { + return result.getEnumTypeCount(); + } + public com.google.protobuf.DescriptorProtos.EnumDescriptorProto getEnumType(int index) { + return result.getEnumType(index); + } + public Builder setEnumType(int index, com.google.protobuf.DescriptorProtos.EnumDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + result.enumType_.set(index, value); + return this; + } + public Builder setEnumType(int index, com.google.protobuf.DescriptorProtos.EnumDescriptorProto.Builder builderForValue) { + result.enumType_.set(index, builderForValue.build()); + return this; + } + public Builder addEnumType(com.google.protobuf.DescriptorProtos.EnumDescriptorProto value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + result.enumType_.add(value); + return this; + } + public Builder addEnumType(com.google.protobuf.DescriptorProtos.EnumDescriptorProto.Builder builderForValue) { + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + result.enumType_.add(builderForValue.build()); + return this; + } + public Builder addAllEnumType( + java.lang.Iterable values) { + if (result.enumType_.isEmpty()) { + result.enumType_ = new java.util.ArrayList(); + } + super.addAll(values, result.enumType_); + return this; + } + public Builder clearEnumType() { + result.enumType_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; + public java.util.List getExtensionRangeList() { + return java.util.Collections.unmodifiableList(result.extensionRange_); + } + public int getExtensionRangeCount() { + return result.getExtensionRangeCount(); + } + public com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange getExtensionRange(int index) { + return result.getExtensionRange(index); + } + public Builder setExtensionRange(int index, com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange value) { + if (value == null) { + throw new NullPointerException(); + } + result.extensionRange_.set(index, value); + return this; + } + public Builder setExtensionRange(int index, com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.Builder builderForValue) { + result.extensionRange_.set(index, builderForValue.build()); + return this; + } + public Builder addExtensionRange(com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.extensionRange_.isEmpty()) { + result.extensionRange_ = new java.util.ArrayList(); + } + result.extensionRange_.add(value); + return this; + } + public Builder addExtensionRange(com.google.protobuf.DescriptorProtos.DescriptorProto.ExtensionRange.Builder builderForValue) { + if (result.extensionRange_.isEmpty()) { + result.extensionRange_ = new java.util.ArrayList(); + } + result.extensionRange_.add(builderForValue.build()); + return this; + } + public Builder addAllExtensionRange( + java.lang.Iterable values) { + if (result.extensionRange_.isEmpty()) { + result.extensionRange_ = new java.util.ArrayList(); + } + super.addAll(values, result.extensionRange_); + return this; + } + public Builder clearExtensionRange() { + result.extensionRange_ = java.util.Collections.emptyList(); + return this; + } + + // optional .google.protobuf.MessageOptions options = 7; + public boolean hasOptions() { + return result.hasOptions(); + } + public com.google.protobuf.DescriptorProtos.MessageOptions getOptions() { + return result.getOptions(); + } + public Builder setOptions(com.google.protobuf.DescriptorProtos.MessageOptions value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasOptions = true; + result.options_ = value; + return this; + } + public Builder setOptions(com.google.protobuf.DescriptorProtos.MessageOptions.Builder builderForValue) { + result.hasOptions = true; + result.options_ = builderForValue.build(); + return this; + } + public Builder mergeOptions(com.google.protobuf.DescriptorProtos.MessageOptions value) { + if (result.hasOptions() && + result.options_ != com.google.protobuf.DescriptorProtos.MessageOptions.getDefaultInstance()) { + result.options_ = + com.google.protobuf.DescriptorProtos.MessageOptions.newBuilder(result.options_).mergeFrom(value).buildPartial(); + } else { + result.options_ = value; + } + result.hasOptions = true; + return this; + } + public Builder clearOptions() { + result.hasOptions = false; + result.options_ = com.google.protobuf.DescriptorProtos.MessageOptions.getDefaultInstance(); + return this; + } + + // @@protoc_insertion_point(builder_scope:google.protobuf.DescriptorProto) + } + + static { + defaultInstance = new DescriptorProto(true); + com.google.protobuf.DescriptorProtos.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto) + } + + public static final class FieldDescriptorProto extends + com.google.protobuf.GeneratedMessage { + // Use FieldDescriptorProto.newBuilder() to construct. + private FieldDescriptorProto() { + initFields(); + } + private FieldDescriptorProto(boolean noInit) {} + + private static final FieldDescriptorProto defaultInstance; + public static FieldDescriptorProto getDefaultInstance() { + return defaultInstance; + } + + public FieldDescriptorProto getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_FieldDescriptorProto_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.google.protobuf.DescriptorProtos.internal_static_google_protobuf_FieldDescriptorProto_fieldAccessorTable; + } + + public enum Type + implements com.google.protobuf.ProtocolMessageEnum { + TYPE_DOUBLE(0, 1), + TYPE_FLOAT(1, 2), + TYPE_INT64(2, 3), + TYPE_UINT64(3, 4), + TYPE_INT32(4, 5), + TYPE_FIXED64(5, 6), + TYPE_FIXED32(6, 7), + TYPE_BOOL(7, 8), + TYPE_STRING(8, 9), + TYPE_GROUP(9, 10), + TYPE_MESSAGE(10, 11), + TYPE_BYTES(11, 12), + TYPE_UINT32(12, 13), + TYPE_ENUM(13, 14), + TYPE_SFIXED32(14, 15), + TYPE_SFIXED64(15, 16), + TYPE_SINT32(16, 17), + TYPE_SINT64(17, 18), + ; + + + public final int getNumber() { return value; } + + public static Type valueOf(int value) { + switch (value) { + case 1: return TYPE_DOUBLE; + case 2: return TYPE_FLOAT; + case 3: return TYPE_INT64; + case 4: return TYPE_UINT64; + case 5: return TYPE_INT32; + case 6: return TYPE_FIXED64; + case 7: return TYPE_FIXED32; + case 8: return TYPE_BOOL; + case 9: return TYPE_STRING; + case 10: return TYPE_GROUP; + case 11: return TYPE_MESSAGE; + case 12: return TYPE_BYTES; + case 13: return TYPE_UINT32; + case 14: return TYPE_ENUM; + case 15: return TYPE_SFIXED32; + case 16: return TYPE_SFIXED64; + case 17: return TYPE_SINT32; + case 18: return TYPE_SINT64; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public Type findValueByNumber(int number) { + return Type.valueOf(number) + ; } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.google.protobuf.DescriptorProtos.FieldDescriptorProto.getDescriptor().getEnumTypes().get(0); + } + + private static final Type[] VALUES = { + TYPE_DOUBLE, TYPE_FLOAT, TYPE_INT64, TYPE_UINT64, TYPE_INT32, TYPE_FIXED64, TYPE_FIXED32, TYPE_BOOL, TYPE_STRING, TYPE_GROUP, TYPE_MESSAGE, TYPE_BYTES, TYPE_UINT32, TYPE_ENUM, TYPE_SFIXED32, TYPE_SFIXED64, TYPE_SINT32, TYPE_SINT64, + }; + public static Type valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + private final int index; + private final int value; + private Type(int index, int value) { + this.index = index; + this.value = value; + } + + static { + com.google.protobuf.DescriptorProtos.getDescriptor(); + } + + // @@protoc_insertion_point(enum_scope:google.protobuf.FieldDescriptorProto.Type) + } + + public enum Label + implements com.google.protobuf.ProtocolMessageEnum { + LABEL_OPTIONAL(0, 1), + LABEL_REQUIRED(1, 2), + LABEL_REPEATED(2, 3), + ; + + + public final int getNumber() { return value; } + + public static Label valueOf(int value) { + switch (value) { + case 1: return LABEL_OPTIONAL; + case 2: return LABEL_REQUIRED; + case 3: return LABEL_REPEATED; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap

+     *   for all i in [0, file.getMessageTypeCount()):
+     *     file.getMessageType(i).getIndex() == i
+     * 
+ * Similarly, for a {@link Descriptor} {@code messageType}: + *
+     *   for all i in [0, messageType.getNestedTypeCount()):
+     *     messageType.getNestedType(i).getIndex() == i
+     * 
+ */ + public int getIndex() { return index; } + + /** Convert the descriptor to its protocol message representation. */ + public DescriptorProto toProto() { return proto; } + + /** Get the type's unqualified name. */ + public String getName() { return proto.getName(); } + + /** + * Get the type's fully-qualified name, within the proto language's + * namespace. This differs from the Java name. For example, given this + * {@code .proto}: + *
+     *   package foo.bar;
+     *   option java_package = "com.example.protos"
+     *   message Baz {}
+     * 
+ * {@code Baz}'s full name is "foo.bar.Baz". + */ + public String getFullName() { return fullName; } + + /** Get the {@link FileDescriptor} containing this descriptor. */ + public FileDescriptor getFile() { return file; } + + /** If this is a nested type, get the outer descriptor, otherwise null. */ + public Descriptor getContainingType() { return containingType; } + + /** Get the {@code MessageOptions}, defined in {@code descriptor.proto}. */ + public MessageOptions getOptions() { return proto.getOptions(); } + + /** Get a list of this message type's fields. */ + public List getFields() { + return Collections.unmodifiableList(Arrays.asList(fields)); + } + + /** Get a list of this message type's extensions. */ + public List getExtensions() { + return Collections.unmodifiableList(Arrays.asList(extensions)); + } + + /** Get a list of message types nested within this one. */ + public List getNestedTypes() { + return Collections.unmodifiableList(Arrays.asList(nestedTypes)); + } + + /** Get a list of enum types nested within this one. */ + public List getEnumTypes() { + return Collections.unmodifiableList(Arrays.asList(enumTypes)); + } + + /** Determines if the given field number is an extension. */ + public boolean isExtensionNumber(final int number) { + for (final DescriptorProto.ExtensionRange range : + proto.getExtensionRangeList()) { + if (range.getStart() <= number && number < range.getEnd()) { + return true; + } + } + return false; + } + + /** + * Finds a field by name. + * @param name The unqualified name of the field (e.g. "foo"). + * @return The field's descriptor, or {@code null} if not found. + */ + public FieldDescriptor findFieldByName(final String name) { + final GenericDescriptor result = + file.pool.findSymbol(fullName + '.' + name); + if (result != null && result instanceof FieldDescriptor) { + return (FieldDescriptor)result; + } else { + return null; + } + } + + /** + * Finds a field by field number. + * @param number The field number within this message type. + * @return The field's descriptor, or {@code null} if not found. + */ + public FieldDescriptor findFieldByNumber(final int number) { + return file.pool.fieldsByNumber.get( + new DescriptorPool.DescriptorIntPair(this, number)); + } + + /** + * Finds a nested message type by name. + * @param name The unqualified name of the nested type (e.g. "Foo"). + * @return The types's descriptor, or {@code null} if not found. + */ + public Descriptor findNestedTypeByName(final String name) { + final GenericDescriptor result = + file.pool.findSymbol(fullName + '.' + name); + if (result != null && result instanceof Descriptor) { + return (Descriptor)result; + } else { + return null; + } + } + + /** + * Finds a nested enum type by name. + * @param name The unqualified name of the nested type (e.g. "Foo"). + * @return The types's descriptor, or {@code null} if not found. + */ + public EnumDescriptor findEnumTypeByName(final String name) { + final GenericDescriptor result = + file.pool.findSymbol(fullName + '.' + name); + if (result != null && result instanceof EnumDescriptor) { + return (EnumDescriptor)result; + } else { + return null; + } + } + + private final int index; + private DescriptorProto proto; + private final String fullName; + private final FileDescriptor file; + private final Descriptor containingType; + private final Descriptor[] nestedTypes; + private final EnumDescriptor[] enumTypes; + private final FieldDescriptor[] fields; + private final FieldDescriptor[] extensions; + + private Descriptor(final DescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index) + throws DescriptorValidationException { + this.index = index; + this.proto = proto; + fullName = computeFullName(file, parent, proto.getName()); + this.file = file; + containingType = parent; + + nestedTypes = new Descriptor[proto.getNestedTypeCount()]; + for (int i = 0; i < proto.getNestedTypeCount(); i++) { + nestedTypes[i] = new Descriptor( + proto.getNestedType(i), file, this, i); + } + + enumTypes = new EnumDescriptor[proto.getEnumTypeCount()]; + for (int i = 0; i < proto.getEnumTypeCount(); i++) { + enumTypes[i] = new EnumDescriptor( + proto.getEnumType(i), file, this, i); + } + + fields = new FieldDescriptor[proto.getFieldCount()]; + for (int i = 0; i < proto.getFieldCount(); i++) { + fields[i] = new FieldDescriptor( + proto.getField(i), file, this, i, false); + } + + extensions = new FieldDescriptor[proto.getExtensionCount()]; + for (int i = 0; i < proto.getExtensionCount(); i++) { + extensions[i] = new FieldDescriptor( + proto.getExtension(i), file, this, i, true); + } + + file.pool.addSymbol(this); + } + + /** Look up and cross-link all field types, etc. */ + private void crossLink() throws DescriptorValidationException { + for (final Descriptor nestedType : nestedTypes) { + nestedType.crossLink(); + } + + for (final FieldDescriptor field : fields) { + field.crossLink(); + } + + for (final FieldDescriptor extension : extensions) { + extension.crossLink(); + } + } + + /** See {@link FileDescriptor#setProto}. */ + private void setProto(final DescriptorProto proto) { + this.proto = proto; + + for (int i = 0; i < nestedTypes.length; i++) { + nestedTypes[i].setProto(proto.getNestedType(i)); + } + + for (int i = 0; i < enumTypes.length; i++) { + enumTypes[i].setProto(proto.getEnumType(i)); + } + + for (int i = 0; i < fields.length; i++) { + fields[i].setProto(proto.getField(i)); + } + + for (int i = 0; i < extensions.length; i++) { + extensions[i].setProto(proto.getExtension(i)); + } + } + } + + // ================================================================= + + /** Describes a field of a message type. */ + public static final class FieldDescriptor + implements GenericDescriptor, Comparable, + FieldSet.FieldDescriptorLite { + /** + * Get the index of this descriptor within its parent. + * @see Descriptor#getIndex() + */ + public int getIndex() { return index; } + + /** Convert the descriptor to its protocol message representation. */ + public FieldDescriptorProto toProto() { return proto; } + + /** Get the field's unqualified name. */ + public String getName() { return proto.getName(); } + + /** Get the field's number. */ + public int getNumber() { return proto.getNumber(); } + + /** + * Get the field's fully-qualified name. + * @see Descriptor#getFullName() + */ + public String getFullName() { return fullName; } + + /** + * Get the field's java type. This is just for convenience. Every + * {@code FieldDescriptorProto.Type} maps to exactly one Java type. + */ + public JavaType getJavaType() { return type.getJavaType(); } + + /** For internal use only. */ + public WireFormat.JavaType getLiteJavaType() { + return getLiteType().getJavaType(); + } + + /** Get the {@code FileDescriptor} containing this descriptor. */ + public FileDescriptor getFile() { return file; } + + /** Get the field's declared type. */ + public Type getType() { return type; } + + /** For internal use only. */ + public WireFormat.FieldType getLiteType() { + return table[type.ordinal()]; + } + // I'm pretty sure values() constructs a new array every time, since there + // is nothing stopping the caller from mutating the array. Therefore we + // make a static copy here. + private static final WireFormat.FieldType[] table = + WireFormat.FieldType.values(); + + /** Is this field declared required? */ + public boolean isRequired() { + return proto.getLabel() == FieldDescriptorProto.Label.LABEL_REQUIRED; + } + + /** Is this field declared optional? */ + public boolean isOptional() { + return proto.getLabel() == FieldDescriptorProto.Label.LABEL_OPTIONAL; + } + + /** Is this field declared repeated? */ + public boolean isRepeated() { + return proto.getLabel() == FieldDescriptorProto.Label.LABEL_REPEATED; + } + + /** Does this field have the {@code [packed = true]} option? */ + public boolean isPacked() { + return getOptions().getPacked(); + } + + /** Can this field be packed? i.e. is it a repeated primitive field? */ + public boolean isPackable() { + return isRepeated() && getLiteType().isPackable(); + } + + /** Returns true if the field had an explicitly-defined default value. */ + public boolean hasDefaultValue() { return proto.hasDefaultValue(); } + + /** + * Returns the field's default value. Valid for all types except for + * messages and groups. For all other types, the object returned is of + * the same class that would returned by Message.getField(this). + */ + public Object getDefaultValue() { + if (getJavaType() == JavaType.MESSAGE) { + throw new UnsupportedOperationException( + "FieldDescriptor.getDefaultValue() called on an embedded message " + + "field."); + } + return defaultValue; + } + + /** Get the {@code FieldOptions}, defined in {@code descriptor.proto}. */ + public FieldOptions getOptions() { return proto.getOptions(); } + + /** Is this field an extension? */ + public boolean isExtension() { return proto.hasExtendee(); } + + /** + * Get the field's containing type. For extensions, this is the type being + * extended, not the location where the extension was defined. See + * {@link #getExtensionScope()}. + */ + public Descriptor getContainingType() { return containingType; } + + /** + * For extensions defined nested within message types, gets the outer + * type. Not valid for non-extension fields. For example, consider + * this {@code .proto} file: + *
+     *   message Foo {
+     *     extensions 1000 to max;
+     *   }
+     *   extend Foo {
+     *     optional int32 baz = 1234;
+     *   }
+     *   message Bar {
+     *     extend Foo {
+     *       optional int32 qux = 4321;
+     *     }
+     *   }
+     * 
+ * Both {@code baz}'s and {@code qux}'s containing type is {@code Foo}. + * However, {@code baz}'s extension scope is {@code null} while + * {@code qux}'s extension scope is {@code Bar}. + */ + public Descriptor getExtensionScope() { + if (!isExtension()) { + throw new UnsupportedOperationException( + "This field is not an extension."); + } + return extensionScope; + } + + /** For embedded message and group fields, gets the field's type. */ + public Descriptor getMessageType() { + if (getJavaType() != JavaType.MESSAGE) { + throw new UnsupportedOperationException( + "This field is not of message type."); + } + return messageType; + } + + /** For enum fields, gets the field's type. */ + public EnumDescriptor getEnumType() { + if (getJavaType() != JavaType.ENUM) { + throw new UnsupportedOperationException( + "This field is not of enum type."); + } + return enumType; + } + + /** + * Compare with another {@code FieldDescriptor}. This orders fields in + * "canonical" order, which simply means ascending order by field number. + * {@code other} must be a field of the same type -- i.e. + * {@code getContainingType()} must return the same {@code Descriptor} for + * both fields. + * + * @return negative, zero, or positive if {@code this} is less than, + * equal to, or greater than {@code other}, respectively. + */ + public int compareTo(final FieldDescriptor other) { + if (other.containingType != containingType) { + throw new IllegalArgumentException( + "FieldDescriptors can only be compared to other FieldDescriptors " + + "for fields of the same message type."); + } + return getNumber() - other.getNumber(); + } + + private final int index; + + private FieldDescriptorProto proto; + private final String fullName; + private final FileDescriptor file; + private final Descriptor extensionScope; + + // Possibly initialized during cross-linking. + private Type type; + private Descriptor containingType; + private Descriptor messageType; + private EnumDescriptor enumType; + private Object defaultValue; + + public enum Type { + DOUBLE (JavaType.DOUBLE ), + FLOAT (JavaType.FLOAT ), + INT64 (JavaType.LONG ), + UINT64 (JavaType.LONG ), + INT32 (JavaType.INT ), + FIXED64 (JavaType.LONG ), + FIXED32 (JavaType.INT ), + BOOL (JavaType.BOOLEAN ), + STRING (JavaType.STRING ), + GROUP (JavaType.MESSAGE ), + MESSAGE (JavaType.MESSAGE ), + BYTES (JavaType.BYTE_STRING), + UINT32 (JavaType.INT ), + ENUM (JavaType.ENUM ), + SFIXED32(JavaType.INT ), + SFIXED64(JavaType.LONG ), + SINT32 (JavaType.INT ), + SINT64 (JavaType.LONG ); + + Type(final JavaType javaType) { + this.javaType = javaType; + } + + private JavaType javaType; + + public FieldDescriptorProto.Type toProto() { + return FieldDescriptorProto.Type.valueOf(ordinal() + 1); + } + public JavaType getJavaType() { return javaType; } + + public static Type valueOf(final FieldDescriptorProto.Type type) { + return values()[type.getNumber() - 1]; + } + } + + static { + // Refuse to init if someone added a new declared type. + if (Type.values().length != FieldDescriptorProto.Type.values().length) { + throw new RuntimeException( + "descriptor.proto has a new declared type but Desrciptors.java " + + "wasn't updated."); + } + } + + public enum JavaType { + INT(0), + LONG(0L), + FLOAT(0F), + DOUBLE(0D), + BOOLEAN(false), + STRING(""), + BYTE_STRING(ByteString.EMPTY), + ENUM(null), + MESSAGE(null); + + JavaType(final Object defaultDefault) { + this.defaultDefault = defaultDefault; + } + + /** + * The default default value for fields of this type, if it's a primitive + * type. This is meant for use inside this file only, hence is private. + */ + private final Object defaultDefault; + } + + private FieldDescriptor(final FieldDescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index, + final boolean isExtension) + throws DescriptorValidationException { + this.index = index; + this.proto = proto; + fullName = computeFullName(file, parent, proto.getName()); + this.file = file; + + if (proto.hasType()) { + type = Type.valueOf(proto.getType()); + } + + if (getNumber() <= 0) { + throw new DescriptorValidationException(this, + "Field numbers must be positive integers."); + } + + // Only repeated primitive fields may be packed. + if (proto.getOptions().getPacked() && !isPackable()) { + throw new DescriptorValidationException(this, + "[packed = true] can only be specified for repeated primitive " + + "fields."); + } + + if (isExtension) { + if (!proto.hasExtendee()) { + throw new DescriptorValidationException(this, + "FieldDescriptorProto.extendee not set for extension field."); + } + containingType = null; // Will be filled in when cross-linking + if (parent != null) { + extensionScope = parent; + } else { + extensionScope = null; + } + } else { + if (proto.hasExtendee()) { + throw new DescriptorValidationException(this, + "FieldDescriptorProto.extendee set for non-extension field."); + } + containingType = parent; + extensionScope = null; + } + + file.pool.addSymbol(this); + } + + /** Look up and cross-link all field types, etc. */ + private void crossLink() throws DescriptorValidationException { + if (proto.hasExtendee()) { + final GenericDescriptor extendee = + file.pool.lookupSymbol(proto.getExtendee(), this); + if (!(extendee instanceof Descriptor)) { + throw new DescriptorValidationException(this, + '\"' + proto.getExtendee() + "\" is not a message type."); + } + containingType = (Descriptor)extendee; + + if (!getContainingType().isExtensionNumber(getNumber())) { + throw new DescriptorValidationException(this, + '\"' + getContainingType().getFullName() + + "\" does not declare " + getNumber() + + " as an extension number."); + } + } + + if (proto.hasTypeName()) { + final GenericDescriptor typeDescriptor = + file.pool.lookupSymbol(proto.getTypeName(), this); + + if (!proto.hasType()) { + // Choose field type based on symbol. + if (typeDescriptor instanceof Descriptor) { + type = Type.MESSAGE; + } else if (typeDescriptor instanceof EnumDescriptor) { + type = Type.ENUM; + } else { + throw new DescriptorValidationException(this, + '\"' + proto.getTypeName() + "\" is not a type."); + } + } + + if (getJavaType() == JavaType.MESSAGE) { + if (!(typeDescriptor instanceof Descriptor)) { + throw new DescriptorValidationException(this, + '\"' + proto.getTypeName() + "\" is not a message type."); + } + messageType = (Descriptor)typeDescriptor; + + if (proto.hasDefaultValue()) { + throw new DescriptorValidationException(this, + "Messages can't have default values."); + } + } else if (getJavaType() == JavaType.ENUM) { + if (!(typeDescriptor instanceof EnumDescriptor)) { + throw new DescriptorValidationException(this, + '\"' + proto.getTypeName() + "\" is not an enum type."); + } + enumType = (EnumDescriptor)typeDescriptor; + } else { + throw new DescriptorValidationException(this, + "Field with primitive type has type_name."); + } + } else { + if (getJavaType() == JavaType.MESSAGE || + getJavaType() == JavaType.ENUM) { + throw new DescriptorValidationException(this, + "Field with message or enum type missing type_name."); + } + } + + // We don't attempt to parse the default value until here because for + // enums we need the enum type's descriptor. + if (proto.hasDefaultValue()) { + if (isRepeated()) { + throw new DescriptorValidationException(this, + "Repeated fields cannot have default values."); + } + + try { + switch (getType()) { + case INT32: + case SINT32: + case SFIXED32: + defaultValue = TextFormat.parseInt32(proto.getDefaultValue()); + break; + case UINT32: + case FIXED32: + defaultValue = TextFormat.parseUInt32(proto.getDefaultValue()); + break; + case INT64: + case SINT64: + case SFIXED64: + defaultValue = TextFormat.parseInt64(proto.getDefaultValue()); + break; + case UINT64: + case FIXED64: + defaultValue = TextFormat.parseUInt64(proto.getDefaultValue()); + break; + case FLOAT: + if (proto.getDefaultValue().equals("inf")) { + defaultValue = Float.POSITIVE_INFINITY; + } else if (proto.getDefaultValue().equals("-inf")) { + defaultValue = Float.NEGATIVE_INFINITY; + } else if (proto.getDefaultValue().equals("nan")) { + defaultValue = Float.NaN; + } else { + defaultValue = Float.valueOf(proto.getDefaultValue()); + } + break; + case DOUBLE: + if (proto.getDefaultValue().equals("inf")) { + defaultValue = Double.POSITIVE_INFINITY; + } else if (proto.getDefaultValue().equals("-inf")) { + defaultValue = Double.NEGATIVE_INFINITY; + } else if (proto.getDefaultValue().equals("nan")) { + defaultValue = Double.NaN; + } else { + defaultValue = Double.valueOf(proto.getDefaultValue()); + } + break; + case BOOL: + defaultValue = Boolean.valueOf(proto.getDefaultValue()); + break; + case STRING: + defaultValue = proto.getDefaultValue(); + break; + case BYTES: + try { + defaultValue = + TextFormat.unescapeBytes(proto.getDefaultValue()); + } catch (TextFormat.InvalidEscapeSequenceException e) { + throw new DescriptorValidationException(this, + "Couldn't parse default value: " + e.getMessage(), e); + } + break; + case ENUM: + defaultValue = enumType.findValueByName(proto.getDefaultValue()); + if (defaultValue == null) { + throw new DescriptorValidationException(this, + "Unknown enum default value: \"" + + proto.getDefaultValue() + '\"'); + } + break; + case MESSAGE: + case GROUP: + throw new DescriptorValidationException(this, + "Message type had default value."); + } + } catch (NumberFormatException e) { + throw new DescriptorValidationException(this, + "Could not parse default value: \"" + + proto.getDefaultValue() + '\"', e); + } + } else { + // Determine the default default for this field. + if (isRepeated()) { + defaultValue = Collections.emptyList(); + } else { + switch (getJavaType()) { + case ENUM: + // We guarantee elsewhere that an enum type always has at least + // one possible value. + defaultValue = enumType.getValues().get(0); + break; + case MESSAGE: + defaultValue = null; + break; + default: + defaultValue = getJavaType().defaultDefault; + break; + } + } + } + + if (!isExtension()) { + file.pool.addFieldByNumber(this); + } + + if (containingType != null && + containingType.getOptions().getMessageSetWireFormat()) { + if (isExtension()) { + if (!isOptional() || getType() != Type.MESSAGE) { + throw new DescriptorValidationException(this, + "Extensions of MessageSets must be optional messages."); + } + } else { + throw new DescriptorValidationException(this, + "MessageSets cannot have fields, only extensions."); + } + } + } + + /** See {@link FileDescriptor#setProto}. */ + private void setProto(final FieldDescriptorProto proto) { + this.proto = proto; + } + + /** + * For internal use only. This is to satisfy the FieldDescriptorLite + * interface. + */ + public MessageLite.Builder internalMergeFrom( + MessageLite.Builder to, MessageLite from) { + // FieldDescriptors are only used with non-lite messages so we can just + // down-cast and call mergeFrom directly. + return ((Message.Builder) to).mergeFrom((Message) from); + } + } + + // ================================================================= + + /** Describes an enum type. */ + public static final class EnumDescriptor + implements GenericDescriptor, Internal.EnumLiteMap { + /** + * Get the index of this descriptor within its parent. + * @see Descriptor#getIndex() + */ + public int getIndex() { return index; } + + /** Convert the descriptor to its protocol message representation. */ + public EnumDescriptorProto toProto() { return proto; } + + /** Get the type's unqualified name. */ + public String getName() { return proto.getName(); } + + /** + * Get the type's fully-qualified name. + * @see Descriptor#getFullName() + */ + public String getFullName() { return fullName; } + + /** Get the {@link FileDescriptor} containing this descriptor. */ + public FileDescriptor getFile() { return file; } + + /** If this is a nested type, get the outer descriptor, otherwise null. */ + public Descriptor getContainingType() { return containingType; } + + /** Get the {@code EnumOptions}, defined in {@code descriptor.proto}. */ + public EnumOptions getOptions() { return proto.getOptions(); } + + /** Get a list of defined values for this enum. */ + public List getValues() { + return Collections.unmodifiableList(Arrays.asList(values)); + } + + /** + * Find an enum value by name. + * @param name The unqualified name of the value (e.g. "FOO"). + * @return the value's decsriptor, or {@code null} if not found. + */ + public EnumValueDescriptor findValueByName(final String name) { + final GenericDescriptor result = + file.pool.findSymbol(fullName + '.' + name); + if (result != null && result instanceof EnumValueDescriptor) { + return (EnumValueDescriptor)result; + } else { + return null; + } + } + + /** + * Find an enum value by number. If multiple enum values have the same + * number, this returns the first defined value with that number. + * @param number The value's number. + * @return the value's decsriptor, or {@code null} if not found. + */ + public EnumValueDescriptor findValueByNumber(final int number) { + return file.pool.enumValuesByNumber.get( + new DescriptorPool.DescriptorIntPair(this, number)); + } + + private final int index; + private EnumDescriptorProto proto; + private final String fullName; + private final FileDescriptor file; + private final Descriptor containingType; + private EnumValueDescriptor[] values; + + private EnumDescriptor(final EnumDescriptorProto proto, + final FileDescriptor file, + final Descriptor parent, + final int index) + throws DescriptorValidationException { + this.index = index; + this.proto = proto; + fullName = computeFullName(file, parent, proto.getName()); + this.file = file; + containingType = parent; + + if (proto.getValueCount() == 0) { + // We cannot allow enums with no values because this would mean there + // would be no valid default value for fields of this type. + throw new DescriptorValidationException(this, + "Enums must contain at least one value."); + } + + values = new EnumValueDescriptor[proto.getValueCount()]; + for (int i = 0; i < proto.getValueCount(); i++) { + values[i] = new EnumValueDescriptor( + proto.getValue(i), file, this, i); + } + + file.pool.addSymbol(this); + } + + /** See {@link FileDescriptor#setProto}. */ + private void setProto(final EnumDescriptorProto proto) { + this.proto = proto; + + for (int i = 0; i < values.length; i++) { + values[i].setProto(proto.getValue(i)); + } + } + } + + // ================================================================= + + /** + * Describes one value within an enum type. Note that multiple defined + * values may have the same number. In generated Java code, all values + * with the same number after the first become aliases of the first. + * However, they still have independent EnumValueDescriptors. + */ + public static final class EnumValueDescriptor + implements GenericDescriptor, Internal.EnumLite { + /** + * Get the index of this descriptor within its parent. + * @see Descriptor#getIndex() + */ + public int getIndex() { return index; } + + /** Convert the descriptor to its protocol message representation. */ + public EnumValueDescriptorProto toProto() { return proto; } + + /** Get the value's unqualified name. */ + public String getName() { return proto.getName(); } + + /** Get the value's number. */ + public int getNumber() { return proto.getNumber(); } + + /** + * Get the value's fully-qualified name. + * @see Descriptor#getFullName() + */ + public String getFullName() { return fullName; } + + /** Get the {@link FileDescriptor} containing this descriptor. */ + public FileDescriptor getFile() { return file; } + + /** Get the value's enum type. */ + public EnumDescriptor getType() { return type; } + + /** + * Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}. + */ + public EnumValueOptions getOptions() { return proto.getOptions(); } + + private final int index; + private EnumValueDescriptorProto proto; + private final String fullName; + private final FileDescriptor file; + private final EnumDescriptor type; + + private EnumValueDescriptor(final EnumValueDescriptorProto proto, + final FileDescriptor file, + final EnumDescriptor parent, + final int index) + throws DescriptorValidationException { + this.index = index; + this.proto = proto; + this.file = file; + type = parent; + + fullName = parent.getFullName() + '.' + proto.getName(); + + file.pool.addSymbol(this); + file.pool.addEnumValueByNumber(this); + } + + /** See {@link FileDescriptor#setProto}. */ + private void setProto(final EnumValueDescriptorProto proto) { + this.proto = proto; + } + } + + // ================================================================= + + /** Describes a service type. */ + public static final class ServiceDescriptor implements GenericDescriptor { + /** + * Get the index of this descriptor within its parent. + * * @see Descriptors.Descriptor#getIndex() + */ + public int getIndex() { return index; } + + /** Convert the descriptor to its protocol message representation. */ + public ServiceDescriptorProto toProto() { return proto; } + + /** Get the type's unqualified name. */ + public String getName() { return proto.getName(); } + + /** + * Get the type's fully-qualified name. + * @see Descriptor#getFullName() + */ + public String getFullName() { return fullName; } + + /** Get the {@link FileDescriptor} containing this descriptor. */ + public FileDescriptor getFile() { return file; } + + /** Get the {@code ServiceOptions}, defined in {@code descriptor.proto}. */ + public ServiceOptions getOptions() { return proto.getOptions(); } + + /** Get a list of methods for this service. */ + public List getMethods() { + return Collections.unmodifiableList(Arrays.asList(methods)); + } + + /** + * Find a method by name. + * @param name The unqualified name of the method (e.g. "Foo"). + * @return the method's decsriptor, or {@code null} if not found. + */ + public MethodDescriptor findMethodByName(final String name) { + final GenericDescriptor result = + file.pool.findSymbol(fullName + '.' + name); + if (result != null && result instanceof MethodDescriptor) { + return (MethodDescriptor)result; + } else { + return null; + } + } + + private final int index; + private ServiceDescriptorProto proto; + private final String fullName; + private final FileDescriptor file; + private MethodDescriptor[] methods; + + private ServiceDescriptor(final ServiceDescriptorProto proto, + final FileDescriptor file, + final int index) + throws DescriptorValidationException { + this.index = index; + this.proto = proto; + fullName = computeFullName(file, null, proto.getName()); + this.file = file; + + methods = new MethodDescriptor[proto.getMethodCount()]; + for (int i = 0; i < proto.getMethodCount(); i++) { + methods[i] = new MethodDescriptor( + proto.getMethod(i), file, this, i); + } + + file.pool.addSymbol(this); + } + + private void crossLink() throws DescriptorValidationException { + for (final MethodDescriptor method : methods) { + method.crossLink(); + } + } + + /** See {@link FileDescriptor#setProto}. */ + private void setProto(final ServiceDescriptorProto proto) { + this.proto = proto; + + for (int i = 0; i < methods.length; i++) { + methods[i].setProto(proto.getMethod(i)); + } + } + } + + // ================================================================= + + /** + * Describes one method within a service type. + */ + public static final class MethodDescriptor implements GenericDescriptor { + /** + * Get the index of this descriptor within its parent. + * * @see Descriptors.Descriptor#getIndex() + */ + public int getIndex() { return index; } + + /** Convert the descriptor to its protocol message representation. */ + public MethodDescriptorProto toProto() { return proto; } + + /** Get the method's unqualified name. */ + public String getName() { return proto.getName(); } + + /** + * Get the method's fully-qualified name. + * @see Descriptor#getFullName() + */ + public String getFullName() { return fullName; } + + /** Get the {@link FileDescriptor} containing this descriptor. */ + public FileDescriptor getFile() { return file; } + + /** Get the method's service type. */ + public ServiceDescriptor getService() { return service; } + + /** Get the method's input type. */ + public Descriptor getInputType() { return inputType; } + + /** Get the method's output type. */ + public Descriptor getOutputType() { return outputType; } + + /** + * Get the {@code MethodOptions}, defined in {@code descriptor.proto}. + */ + public MethodOptions getOptions() { return proto.getOptions(); } + + private final int index; + private MethodDescriptorProto proto; + private final String fullName; + private final FileDescriptor file; + private final ServiceDescriptor service; + + // Initialized during cross-linking. + private Descriptor inputType; + private Descriptor outputType; + + private MethodDescriptor(final MethodDescriptorProto proto, + final FileDescriptor file, + final ServiceDescriptor parent, + final int index) + throws DescriptorValidationException { + this.index = index; + this.proto = proto; + this.file = file; + service = parent; + + fullName = parent.getFullName() + '.' + proto.getName(); + + file.pool.addSymbol(this); + } + + private void crossLink() throws DescriptorValidationException { + final GenericDescriptor input = + file.pool.lookupSymbol(proto.getInputType(), this); + if (!(input instanceof Descriptor)) { + throw new DescriptorValidationException(this, + '\"' + proto.getInputType() + "\" is not a message type."); + } + inputType = (Descriptor)input; + + final GenericDescriptor output = + file.pool.lookupSymbol(proto.getOutputType(), this); + if (!(output instanceof Descriptor)) { + throw new DescriptorValidationException(this, + '\"' + proto.getOutputType() + "\" is not a message type."); + } + outputType = (Descriptor)output; + } + + /** See {@link FileDescriptor#setProto}. */ + private void setProto(final MethodDescriptorProto proto) { + this.proto = proto; + } + } + + // ================================================================= + + private static String computeFullName(final FileDescriptor file, + final Descriptor parent, + final String name) { + if (parent != null) { + return parent.getFullName() + '.' + name; + } else if (file.getPackage().length() > 0) { + return file.getPackage() + '.' + name; + } else { + return name; + } + } + + // ================================================================= + + /** + * All descriptors except {@code FileDescriptor} implement this to make + * {@code DescriptorPool}'s life easier. + */ + private interface GenericDescriptor { + Message toProto(); + String getName(); + String getFullName(); + FileDescriptor getFile(); + } + + /** + * Thrown when building descriptors fails because the source DescriptorProtos + * are not valid. + */ + public static class DescriptorValidationException extends Exception { + private static final long serialVersionUID = 5750205775490483148L; + + /** Gets the full name of the descriptor where the error occurred. */ + public String getProblemSymbolName() { return name; } + + /** + * Gets the the protocol message representation of the invalid descriptor. + */ + public Message getProblemProto() { return proto; } + + /** + * Gets a human-readable description of the error. + */ + public String getDescription() { return description; } + + private final String name; + private final Message proto; + private final String description; + + private DescriptorValidationException( + final GenericDescriptor problemDescriptor, + final String description) { + super(problemDescriptor.getFullName() + ": " + description); + + // Note that problemDescriptor may be partially uninitialized, so we + // don't want to expose it directly to the user. So, we only provide + // the name and the original proto. + name = problemDescriptor.getFullName(); + proto = problemDescriptor.toProto(); + this.description = description; + } + + private DescriptorValidationException( + final GenericDescriptor problemDescriptor, + final String description, + final Throwable cause) { + this(problemDescriptor, description); + initCause(cause); + } + + private DescriptorValidationException( + final FileDescriptor problemDescriptor, + final String description) { + super(problemDescriptor.getName() + ": " + description); + + // Note that problemDescriptor may be partially uninitialized, so we + // don't want to expose it directly to the user. So, we only provide + // the name and the original proto. + name = problemDescriptor.getName(); + proto = problemDescriptor.toProto(); + this.description = description; + } + } + + // ================================================================= + + /** + * A private helper class which contains lookup tables containing all the + * descriptors defined in a particular file. + */ + private static final class DescriptorPool { + DescriptorPool(final FileDescriptor[] dependencies) { + this.dependencies = new DescriptorPool[dependencies.length]; + + for (int i = 0; i < dependencies.length; i++) { + this.dependencies[i] = dependencies[i].pool; + } + + for (final FileDescriptor dependency : dependencies) { + try { + addPackage(dependency.getPackage(), dependency); + } catch (DescriptorValidationException e) { + // Can't happen, because addPackage() only fails when the name + // conflicts with a non-package, but we have not yet added any + // non-packages at this point. + assert false; + } + } + } + + private final DescriptorPool[] dependencies; + + private final Map descriptorsByName = + new HashMap(); + private final Map fieldsByNumber = + new HashMap(); + private final Map enumValuesByNumber + = new HashMap(); + + /** Find a generic descriptor by fully-qualified name. */ + GenericDescriptor findSymbol(final String fullName) { + GenericDescriptor result = descriptorsByName.get(fullName); + if (result != null) { + return result; + } + + for (final DescriptorPool dependency : dependencies) { + result = dependency.descriptorsByName.get(fullName); + if (result != null) { + return result; + } + } + + return null; + } + + /** + * Look up a descriptor by name, relative to some other descriptor. + * The name may be fully-qualified (with a leading '.'), + * partially-qualified, or unqualified. C++-like name lookup semantics + * are used to search for the matching descriptor. + */ + GenericDescriptor lookupSymbol(final String name, + final GenericDescriptor relativeTo) + throws DescriptorValidationException { + // TODO(kenton): This could be optimized in a number of ways. + + GenericDescriptor result; + if (name.startsWith(".")) { + // Fully-qualified name. + result = findSymbol(name.substring(1)); + } else { + // If "name" is a compound identifier, we want to search for the + // first component of it, then search within it for the rest. + final int firstPartLength = name.indexOf('.'); + final String firstPart; + if (firstPartLength == -1) { + firstPart = name; + } else { + firstPart = name.substring(0, firstPartLength); + } + + // We will search each parent scope of "relativeTo" looking for the + // symbol. + final StringBuilder scopeToTry = + new StringBuilder(relativeTo.getFullName()); + + while (true) { + // Chop off the last component of the scope. + final int dotpos = scopeToTry.lastIndexOf("."); + if (dotpos == -1) { + result = findSymbol(name); + break; + } else { + scopeToTry.setLength(dotpos + 1); + + // Append firstPart and try to find. + scopeToTry.append(firstPart); + result = findSymbol(scopeToTry.toString()); + + if (result != null) { + if (firstPartLength != -1) { + // We only found the first part of the symbol. Now look for + // the whole thing. If this fails, we *don't* want to keep + // searching parent scopes. + scopeToTry.setLength(dotpos + 1); + scopeToTry.append(name); + result = findSymbol(scopeToTry.toString()); + } + break; + } + + // Not found. Remove the name so we can try again. + scopeToTry.setLength(dotpos); + } + } + } + + if (result == null) { + throw new DescriptorValidationException(relativeTo, + '\"' + name + "\" is not defined."); + } else { + return result; + } + } + + /** + * Adds a symbol to the symbol table. If a symbol with the same name + * already exists, throws an error. + */ + void addSymbol(final GenericDescriptor descriptor) + throws DescriptorValidationException { + validateSymbolName(descriptor); + + final String fullName = descriptor.getFullName(); + final int dotpos = fullName.lastIndexOf('.'); + + final GenericDescriptor old = descriptorsByName.put(fullName, descriptor); + if (old != null) { + descriptorsByName.put(fullName, old); + + if (descriptor.getFile() == old.getFile()) { + if (dotpos == -1) { + throw new DescriptorValidationException(descriptor, + '\"' + fullName + "\" is already defined."); + } else { + throw new DescriptorValidationException(descriptor, + '\"' + fullName.substring(dotpos + 1) + + "\" is already defined in \"" + + fullName.substring(0, dotpos) + "\"."); + } + } else { + throw new DescriptorValidationException(descriptor, + '\"' + fullName + "\" is already defined in file \"" + + old.getFile().getName() + "\"."); + } + } + } + + /** + * Represents a package in the symbol table. We use PackageDescriptors + * just as placeholders so that someone cannot define, say, a message type + * that has the same name as an existing package. + */ + private static final class PackageDescriptor implements GenericDescriptor { + public Message toProto() { return file.toProto(); } + public String getName() { return name; } + public String getFullName() { return fullName; } + public FileDescriptor getFile() { return file; } + + PackageDescriptor(final String name, final String fullName, + final FileDescriptor file) { + this.file = file; + this.fullName = fullName; + this.name = name; + } + + private final String name; + private final String fullName; + private final FileDescriptor file; + } + + /** + * Adds a package to the symbol tables. If a package by the same name + * already exists, that is fine, but if some other kind of symbol exists + * under the same name, an exception is thrown. If the package has + * multiple components, this also adds the parent package(s). + */ + void addPackage(final String fullName, final FileDescriptor file) + throws DescriptorValidationException { + final int dotpos = fullName.lastIndexOf('.'); + final String name; + if (dotpos == -1) { + name = fullName; + } else { + addPackage(fullName.substring(0, dotpos), file); + name = fullName.substring(dotpos + 1); + } + + final GenericDescriptor old = + descriptorsByName.put(fullName, + new PackageDescriptor(name, fullName, file)); + if (old != null) { + descriptorsByName.put(fullName, old); + if (!(old instanceof PackageDescriptor)) { + throw new DescriptorValidationException(file, + '\"' + name + "\" is already defined (as something other than a " + + "package) in file \"" + old.getFile().getName() + "\"."); + } + } + } + + /** A (GenericDescriptor, int) pair, used as a map key. */ + private static final class DescriptorIntPair { + private final GenericDescriptor descriptor; + private final int number; + + DescriptorIntPair(final GenericDescriptor descriptor, final int number) { + this.descriptor = descriptor; + this.number = number; + } + + @Override + public int hashCode() { + return descriptor.hashCode() * ((1 << 16) - 1) + number; + } + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof DescriptorIntPair)) { + return false; + } + final DescriptorIntPair other = (DescriptorIntPair)obj; + return descriptor == other.descriptor && number == other.number; + } + } + + /** + * Adds a field to the fieldsByNumber table. Throws an exception if a + * field with hte same containing type and number already exists. + */ + void addFieldByNumber(final FieldDescriptor field) + throws DescriptorValidationException { + final DescriptorIntPair key = + new DescriptorIntPair(field.getContainingType(), field.getNumber()); + final FieldDescriptor old = fieldsByNumber.put(key, field); + if (old != null) { + fieldsByNumber.put(key, old); + throw new DescriptorValidationException(field, + "Field number " + field.getNumber() + + "has already been used in \"" + + field.getContainingType().getFullName() + + "\" by field \"" + old.getName() + "\"."); + } + } + + /** + * Adds an enum value to the enumValuesByNumber table. If an enum value + * with the same type and number already exists, does nothing. (This is + * allowed; the first value define with the number takes precedence.) + */ + void addEnumValueByNumber(final EnumValueDescriptor value) { + final DescriptorIntPair key = + new DescriptorIntPair(value.getType(), value.getNumber()); + final EnumValueDescriptor old = enumValuesByNumber.put(key, value); + if (old != null) { + enumValuesByNumber.put(key, old); + // Not an error: Multiple enum values may have the same number, but + // we only want the first one in the map. + } + } + + /** + * Verifies that the descriptor's name is valid (i.e. it contains only + * letters, digits, and underscores, and does not start with a digit). + */ + static void validateSymbolName(final GenericDescriptor descriptor) + throws DescriptorValidationException { + final String name = descriptor.getName(); + if (name.length() == 0) { + throw new DescriptorValidationException(descriptor, "Missing name."); + } else { + boolean valid = true; + for (int i = 0; i < name.length(); i++) { + final char c = name.charAt(i); + // Non-ASCII characters are not valid in protobuf identifiers, even + // if they are letters or digits. + if (c >= 128) { + valid = false; + } + // First character must be letter or _. Subsequent characters may + // be letters, numbers, or digits. + if (Character.isLetter(c) || c == '_' || + (Character.isDigit(c) && i > 0)) { + // Valid + } else { + valid = false; + } + } + if (!valid) { + throw new DescriptorValidationException(descriptor, + '\"' + name + "\" is not a valid identifier."); + } + } + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/DynamicMessage.java b/DataExtractionOSM/src/com/google/protobuf/DynamicMessage.java new file mode 100644 index 0000000000..c106b662ba --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/DynamicMessage.java @@ -0,0 +1,438 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; + +import java.io.InputStream; +import java.io.IOException; +import java.util.Map; + +/** + * An implementation of {@link Message} that can represent arbitrary types, + * given a {@link Descriptors.Descriptor}. + * + * @author kenton@google.com Kenton Varda + */ +public final class DynamicMessage extends AbstractMessage { + private final Descriptor type; + private final FieldSet fields; + private final UnknownFieldSet unknownFields; + private int memoizedSize = -1; + + /** + * Construct a {@code DynamicMessage} using the given {@code FieldSet}. + */ + private DynamicMessage(Descriptor type, FieldSet fields, + UnknownFieldSet unknownFields) { + this.type = type; + this.fields = fields; + this.unknownFields = unknownFields; + } + + /** + * Get a {@code DynamicMessage} representing the default instance of the + * given type. + */ + public static DynamicMessage getDefaultInstance(Descriptor type) { + return new DynamicMessage(type, FieldSet.emptySet(), + UnknownFieldSet.getDefaultInstance()); + } + + /** Parse a message of the given type from the given input stream. */ + public static DynamicMessage parseFrom(Descriptor type, + CodedInputStream input) + throws IOException { + return newBuilder(type).mergeFrom(input).buildParsed(); + } + + /** Parse a message of the given type from the given input stream. */ + public static DynamicMessage parseFrom( + Descriptor type, + CodedInputStream input, + ExtensionRegistry extensionRegistry) + throws IOException { + return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed(); + } + + /** Parse {@code data} as a message of the given type and return it. */ + public static DynamicMessage parseFrom(Descriptor type, ByteString data) + throws InvalidProtocolBufferException { + return newBuilder(type).mergeFrom(data).buildParsed(); + } + + /** Parse {@code data} as a message of the given type and return it. */ + public static DynamicMessage parseFrom(Descriptor type, ByteString data, + ExtensionRegistry extensionRegistry) + throws InvalidProtocolBufferException { + return newBuilder(type).mergeFrom(data, extensionRegistry).buildParsed(); + } + + /** Parse {@code data} as a message of the given type and return it. */ + public static DynamicMessage parseFrom(Descriptor type, byte[] data) + throws InvalidProtocolBufferException { + return newBuilder(type).mergeFrom(data).buildParsed(); + } + + /** Parse {@code data} as a message of the given type and return it. */ + public static DynamicMessage parseFrom(Descriptor type, byte[] data, + ExtensionRegistry extensionRegistry) + throws InvalidProtocolBufferException { + return newBuilder(type).mergeFrom(data, extensionRegistry).buildParsed(); + } + + /** Parse a message of the given type from {@code input} and return it. */ + public static DynamicMessage parseFrom(Descriptor type, InputStream input) + throws IOException { + return newBuilder(type).mergeFrom(input).buildParsed(); + } + + /** Parse a message of the given type from {@code input} and return it. */ + public static DynamicMessage parseFrom(Descriptor type, InputStream input, + ExtensionRegistry extensionRegistry) + throws IOException { + return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed(); + } + + /** Construct a {@link Message.Builder} for the given type. */ + public static Builder newBuilder(Descriptor type) { + return new Builder(type); + } + + /** + * Construct a {@link Message.Builder} for a message of the same type as + * {@code prototype}, and initialize it with {@code prototype}'s contents. + */ + public static Builder newBuilder(Message prototype) { + return new Builder(prototype.getDescriptorForType()).mergeFrom(prototype); + } + + // ----------------------------------------------------------------- + // Implementation of Message interface. + + public Descriptor getDescriptorForType() { + return type; + } + + public DynamicMessage getDefaultInstanceForType() { + return getDefaultInstance(type); + } + + public Map getAllFields() { + return fields.getAllFields(); + } + + public boolean hasField(FieldDescriptor field) { + verifyContainingType(field); + return fields.hasField(field); + } + + public Object getField(FieldDescriptor field) { + verifyContainingType(field); + Object result = fields.getField(field); + if (result == null) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + result = getDefaultInstance(field.getMessageType()); + } else { + result = field.getDefaultValue(); + } + } + return result; + } + + public int getRepeatedFieldCount(FieldDescriptor field) { + verifyContainingType(field); + return fields.getRepeatedFieldCount(field); + } + + public Object getRepeatedField(FieldDescriptor field, int index) { + verifyContainingType(field); + return fields.getRepeatedField(field, index); + } + + public UnknownFieldSet getUnknownFields() { + return unknownFields; + } + + private static boolean isInitialized(Descriptor type, + FieldSet fields) { + // Check that all required fields are present. + for (final FieldDescriptor field : type.getFields()) { + if (field.isRequired()) { + if (!fields.hasField(field)) { + return false; + } + } + } + + // Check that embedded messages are initialized. + return fields.isInitialized(); + } + + public boolean isInitialized() { + return isInitialized(type, fields); + } + + public void writeTo(CodedOutputStream output) throws IOException { + if (type.getOptions().getMessageSetWireFormat()) { + fields.writeMessageSetTo(output); + unknownFields.writeAsMessageSetTo(output); + } else { + fields.writeTo(output); + unknownFields.writeTo(output); + } + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + if (type.getOptions().getMessageSetWireFormat()) { + size = fields.getMessageSetSerializedSize(); + size += unknownFields.getSerializedSizeAsMessageSet(); + } else { + size = fields.getSerializedSize(); + size += unknownFields.getSerializedSize(); + } + + memoizedSize = size; + return size; + } + + public Builder newBuilderForType() { + return new Builder(type); + } + + public Builder toBuilder() { + return newBuilderForType().mergeFrom(this); + } + + /** Verifies that the field is a field of this message. */ + private void verifyContainingType(FieldDescriptor field) { + if (field.getContainingType() != type) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + + // ================================================================= + + /** + * Builder for {@link DynamicMessage}s. + */ + public static final class Builder extends AbstractMessage.Builder { + private final Descriptor type; + private FieldSet fields; + private UnknownFieldSet unknownFields; + + /** Construct a {@code Builder} for the given type. */ + private Builder(Descriptor type) { + this.type = type; + this.fields = FieldSet.newFieldSet(); + this.unknownFields = UnknownFieldSet.getDefaultInstance(); + } + + // --------------------------------------------------------------- + // Implementation of Message.Builder interface. + + public Builder clear() { + if (fields == null) { + throw new IllegalStateException("Cannot call clear() after build()."); + } + fields.clear(); + return this; + } + + public Builder mergeFrom(Message other) { + if (other instanceof DynamicMessage) { + // This should be somewhat faster than calling super.mergeFrom(). + DynamicMessage otherDynamicMessage = (DynamicMessage) other; + if (otherDynamicMessage.type != type) { + throw new IllegalArgumentException( + "mergeFrom(Message) can only merge messages of the same type."); + } + fields.mergeFrom(otherDynamicMessage.fields); + mergeUnknownFields(otherDynamicMessage.unknownFields); + return this; + } else { + return super.mergeFrom(other); + } + } + + public DynamicMessage build() { + // If fields == null, we'll throw an appropriate exception later. + if (fields != null && !isInitialized()) { + throw newUninitializedMessageException( + new DynamicMessage(type, fields, unknownFields)); + } + return buildPartial(); + } + + /** + * Helper for DynamicMessage.parseFrom() methods to call. Throws + * {@link InvalidProtocolBufferException} instead of + * {@link UninitializedMessageException}. + */ + private DynamicMessage buildParsed() throws InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + new DynamicMessage(type, fields, unknownFields)) + .asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public DynamicMessage buildPartial() { + if (fields == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + fields.makeImmutable(); + DynamicMessage result = + new DynamicMessage(type, fields, unknownFields); + fields = null; + unknownFields = null; + return result; + } + + public Builder clone() { + Builder result = new Builder(type); + result.fields.mergeFrom(fields); + return result; + } + + public boolean isInitialized() { + return DynamicMessage.isInitialized(type, fields); + } + + public Descriptor getDescriptorForType() { + return type; + } + + public DynamicMessage getDefaultInstanceForType() { + return getDefaultInstance(type); + } + + public Map getAllFields() { + return fields.getAllFields(); + } + + public Builder newBuilderForField(FieldDescriptor field) { + verifyContainingType(field); + + if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + throw new IllegalArgumentException( + "newBuilderForField is only valid for fields with message type."); + } + + return new Builder(field.getMessageType()); + } + + public boolean hasField(FieldDescriptor field) { + verifyContainingType(field); + return fields.hasField(field); + } + + public Object getField(FieldDescriptor field) { + verifyContainingType(field); + Object result = fields.getField(field); + if (result == null) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + result = getDefaultInstance(field.getMessageType()); + } else { + result = field.getDefaultValue(); + } + } + return result; + } + + public Builder setField(FieldDescriptor field, Object value) { + verifyContainingType(field); + fields.setField(field, value); + return this; + } + + public Builder clearField(FieldDescriptor field) { + verifyContainingType(field); + fields.clearField(field); + return this; + } + + public int getRepeatedFieldCount(FieldDescriptor field) { + verifyContainingType(field); + return fields.getRepeatedFieldCount(field); + } + + public Object getRepeatedField(FieldDescriptor field, int index) { + verifyContainingType(field); + return fields.getRepeatedField(field, index); + } + + public Builder setRepeatedField(FieldDescriptor field, + int index, Object value) { + verifyContainingType(field); + fields.setRepeatedField(field, index, value); + return this; + } + + public Builder addRepeatedField(FieldDescriptor field, Object value) { + verifyContainingType(field); + fields.addRepeatedField(field, value); + return this; + } + + public UnknownFieldSet getUnknownFields() { + return unknownFields; + } + + public Builder setUnknownFields(UnknownFieldSet unknownFields) { + this.unknownFields = unknownFields; + return this; + } + + public Builder mergeUnknownFields(UnknownFieldSet unknownFields) { + this.unknownFields = + UnknownFieldSet.newBuilder(this.unknownFields) + .mergeFrom(unknownFields) + .build(); + return this; + } + + /** Verifies that the field is a field of this message. */ + private void verifyContainingType(FieldDescriptor field) { + if (field.getContainingType() != type) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/ExtensionRegistry.java b/DataExtractionOSM/src/com/google/protobuf/ExtensionRegistry.java new file mode 100644 index 0000000000..d4f6ba9e79 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/ExtensionRegistry.java @@ -0,0 +1,266 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * A table of known extensions, searchable by name or field number. When + * parsing a protocol message that might have extensions, you must provide + * an {@code ExtensionRegistry} in which you have registered any extensions + * that you want to be able to parse. Otherwise, those extensions will just + * be treated like unknown fields. + * + *

For example, if you had the {@code .proto} file: + * + *

+ * option java_class = "MyProto";
+ *
+ * message Foo {
+ *   extensions 1000 to max;
+ * }
+ *
+ * extend Foo {
+ *   optional int32 bar;
+ * }
+ * 
+ * + * Then you might write code like: + * + *
+ * ExtensionRegistry registry = ExtensionRegistry.newInstance();
+ * registry.add(MyProto.bar);
+ * MyProto.Foo message = MyProto.Foo.parseFrom(input, registry);
+ * 
+ * + *

Background: + * + *

You might wonder why this is necessary. Two alternatives might come to + * mind. First, you might imagine a system where generated extensions are + * automatically registered when their containing classes are loaded. This + * is a popular technique, but is bad design; among other things, it creates a + * situation where behavior can change depending on what classes happen to be + * loaded. It also introduces a security vulnerability, because an + * unprivileged class could cause its code to be called unexpectedly from a + * privileged class by registering itself as an extension of the right type. + * + *

Another option you might consider is lazy parsing: do not parse an + * extension until it is first requested, at which point the caller must + * provide a type to use. This introduces a different set of problems. First, + * it would require a mutex lock any time an extension was accessed, which + * would be slow. Second, corrupt data would not be detected until first + * access, at which point it would be much harder to deal with it. Third, it + * could violate the expectation that message objects are immutable, since the + * type provided could be any arbitrary message class. An unprivileged user + * could take advantage of this to inject a mutable object into a message + * belonging to privileged code and create mischief. + * + * @author kenton@google.com Kenton Varda + */ +public final class ExtensionRegistry extends ExtensionRegistryLite { + /** Construct a new, empty instance. */ + public static ExtensionRegistry newInstance() { + return new ExtensionRegistry(); + } + + /** Get the unmodifiable singleton empty instance. */ + public static ExtensionRegistry getEmptyRegistry() { + return EMPTY; + } + + /** Returns an unmodifiable view of the registry. */ + @Override + public ExtensionRegistry getUnmodifiable() { + return new ExtensionRegistry(this); + } + + /** A (Descriptor, Message) pair, returned by lookup methods. */ + public static final class ExtensionInfo { + /** The extension's descriptor. */ + public final FieldDescriptor descriptor; + + /** + * A default instance of the extension's type, if it has a message type. + * Otherwise, {@code null}. + */ + public final Message defaultInstance; + + private ExtensionInfo(final FieldDescriptor descriptor) { + this.descriptor = descriptor; + defaultInstance = null; + } + private ExtensionInfo(final FieldDescriptor descriptor, + final Message defaultInstance) { + this.descriptor = descriptor; + this.defaultInstance = defaultInstance; + } + } + + /** + * Find an extension by fully-qualified field name, in the proto namespace. + * I.e. {@code result.descriptor.fullName()} will match {@code fullName} if + * a match is found. + * + * @return Information about the extension if found, or {@code null} + * otherwise. + */ + public ExtensionInfo findExtensionByName(final String fullName) { + return extensionsByName.get(fullName); + } + + /** + * Find an extension by containing type and field number. + * + * @return Information about the extension if found, or {@code null} + * otherwise. + */ + public ExtensionInfo findExtensionByNumber(final Descriptor containingType, + final int fieldNumber) { + return extensionsByNumber.get( + new DescriptorIntPair(containingType, fieldNumber)); + } + + /** Add an extension from a generated file to the registry. */ + public void add(final GeneratedMessage.GeneratedExtension extension) { + if (extension.getDescriptor().getJavaType() == + FieldDescriptor.JavaType.MESSAGE) { + if (extension.getMessageDefaultInstance() == null) { + throw new IllegalStateException( + "Registered message-type extension had null default instance: " + + extension.getDescriptor().getFullName()); + } + add(new ExtensionInfo(extension.getDescriptor(), + extension.getMessageDefaultInstance())); + } else { + add(new ExtensionInfo(extension.getDescriptor(), null)); + } + } + + /** Add a non-message-type extension to the registry by descriptor. */ + public void add(final FieldDescriptor type) { + if (type.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + throw new IllegalArgumentException( + "ExtensionRegistry.add() must be provided a default instance when " + + "adding an embedded message extension."); + } + add(new ExtensionInfo(type, null)); + } + + /** Add a message-type extension to the registry by descriptor. */ + public void add(final FieldDescriptor type, final Message defaultInstance) { + if (type.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + throw new IllegalArgumentException( + "ExtensionRegistry.add() provided a default instance for a " + + "non-message extension."); + } + add(new ExtensionInfo(type, defaultInstance)); + } + + // ================================================================= + // Private stuff. + + private ExtensionRegistry() { + this.extensionsByName = new HashMap(); + this.extensionsByNumber = new HashMap(); + } + + private ExtensionRegistry(ExtensionRegistry other) { + super(other); + this.extensionsByName = Collections.unmodifiableMap(other.extensionsByName); + this.extensionsByNumber = + Collections.unmodifiableMap(other.extensionsByNumber); + } + + private final Map extensionsByName; + private final Map extensionsByNumber; + + private ExtensionRegistry(boolean empty) { + super(ExtensionRegistryLite.getEmptyRegistry()); + this.extensionsByName = Collections.emptyMap(); + this.extensionsByNumber = + Collections.emptyMap(); + } + private static final ExtensionRegistry EMPTY = new ExtensionRegistry(true); + + private void add(final ExtensionInfo extension) { + if (!extension.descriptor.isExtension()) { + throw new IllegalArgumentException( + "ExtensionRegistry.add() was given a FieldDescriptor for a regular " + + "(non-extension) field."); + } + + extensionsByName.put(extension.descriptor.getFullName(), extension); + extensionsByNumber.put( + new DescriptorIntPair(extension.descriptor.getContainingType(), + extension.descriptor.getNumber()), + extension); + + final FieldDescriptor field = extension.descriptor; + if (field.getContainingType().getOptions().getMessageSetWireFormat() && + field.getType() == FieldDescriptor.Type.MESSAGE && + field.isOptional() && + field.getExtensionScope() == field.getMessageType()) { + // This is an extension of a MessageSet type defined within the extension + // type's own scope. For backwards-compatibility, allow it to be looked + // up by type name. + extensionsByName.put(field.getMessageType().getFullName(), extension); + } + } + + /** A (GenericDescriptor, int) pair, used as a map key. */ + private static final class DescriptorIntPair { + private final Descriptor descriptor; + private final int number; + + DescriptorIntPair(final Descriptor descriptor, final int number) { + this.descriptor = descriptor; + this.number = number; + } + + @Override + public int hashCode() { + return descriptor.hashCode() * ((1 << 16) - 1) + number; + } + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof DescriptorIntPair)) { + return false; + } + final DescriptorIntPair other = (DescriptorIntPair)obj; + return descriptor == other.descriptor && number == other.number; + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/ExtensionRegistryLite.java b/DataExtractionOSM/src/com/google/protobuf/ExtensionRegistryLite.java new file mode 100644 index 0000000000..d5288dd8ef --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/ExtensionRegistryLite.java @@ -0,0 +1,169 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Equivalent to {@link ExtensionRegistry} but supports only "lite" types. + *

+ * If all of your types are lite types, then you only need to use + * {@code ExtensionRegistryLite}. Similarly, if all your types are regular + * types, then you only need {@link ExtensionRegistry}. Typically it does not + * make sense to mix the two, since if you have any regular types in your + * program, you then require the full runtime and lose all the benefits of + * the lite runtime, so you might as well make all your types be regular types. + * However, in some cases (e.g. when depending on multiple third-patry libraries + * where one uses lite types and one uses regular), you may find yourself + * wanting to mix the two. In this case things get more complicated. + *

+ * There are three factors to consider: Whether the type being extended is + * lite, whether the embedded type (in the case of a message-typed extension) + * is lite, and whether the extension itself is lite. Since all three are + * declared in different files, they could all be different. Here are all + * the combinations and which type of registry to use: + *

+ *   Extended type     Inner type    Extension         Use registry
+ *   =======================================================================
+ *   lite              lite          lite              ExtensionRegistryLite
+ *   lite              regular       lite              ExtensionRegistry
+ *   regular           regular       regular           ExtensionRegistry
+ *   all other combinations                            not supported
+ * 
+ *

+ * Note that just as regular types are not allowed to contain lite-type fields, + * they are also not allowed to contain lite-type extensions. This is because + * regular types must be fully accessible via reflection, which in turn means + * that all the inner messages must also support reflection. On the other hand, + * since regular types implement the entire lite interface, there is no problem + * with embedding regular types inside lite types. + * + * @author kenton@google.com Kenton Varda + */ +public class ExtensionRegistryLite { + /** Construct a new, empty instance. */ + public static ExtensionRegistryLite newInstance() { + return new ExtensionRegistryLite(); + } + + /** Get the unmodifiable singleton empty instance. */ + public static ExtensionRegistryLite getEmptyRegistry() { + return EMPTY; + } + + /** Returns an unmodifiable view of the registry. */ + public ExtensionRegistryLite getUnmodifiable() { + return new ExtensionRegistryLite(this); + } + + /** + * Find an extension by containing type and field number. + * + * @return Information about the extension if found, or {@code null} + * otherwise. + */ + @SuppressWarnings("unchecked") + public + GeneratedMessageLite.GeneratedExtension + findLiteExtensionByNumber( + final ContainingType containingTypeDefaultInstance, + final int fieldNumber) { + return (GeneratedMessageLite.GeneratedExtension) + extensionsByNumber.get( + new ObjectIntPair(containingTypeDefaultInstance, fieldNumber)); + } + + /** Add an extension from a lite generated file to the registry. */ + public final void add( + final GeneratedMessageLite.GeneratedExtension extension) { + extensionsByNumber.put( + new ObjectIntPair(extension.getContainingTypeDefaultInstance(), + extension.getNumber()), + extension); + } + + // ================================================================= + // Private stuff. + + // Constructors are package-private so that ExtensionRegistry can subclass + // this. + + ExtensionRegistryLite() { + this.extensionsByNumber = + new HashMap>(); + } + + ExtensionRegistryLite(ExtensionRegistryLite other) { + if (other == EMPTY) { + this.extensionsByNumber = Collections.emptyMap(); + } else { + this.extensionsByNumber = + Collections.unmodifiableMap(other.extensionsByNumber); + } + } + + private final Map> + extensionsByNumber; + + private ExtensionRegistryLite(boolean empty) { + this.extensionsByNumber = Collections.emptyMap(); + } + private static final ExtensionRegistryLite EMPTY = + new ExtensionRegistryLite(true); + + /** A (Object, int) pair, used as a map key. */ + private static final class ObjectIntPair { + private final Object object; + private final int number; + + ObjectIntPair(final Object object, final int number) { + this.object = object; + this.number = number; + } + + @Override + public int hashCode() { + return System.identityHashCode(object) * ((1 << 16) - 1) + number; + } + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof ObjectIntPair)) { + return false; + } + final ObjectIntPair other = (ObjectIntPair)obj; + return object == other.object && number == other.number; + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/FieldSet.java b/DataExtractionOSM/src/com/google/protobuf/FieldSet.java new file mode 100644 index 0000000000..9217f4fb22 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/FieldSet.java @@ -0,0 +1,715 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.TreeMap; +import java.util.List; +import java.util.Map; +import java.io.IOException; + +/** + * A class which represents an arbitrary set of fields of some message type. + * This is used to implement {@link DynamicMessage}, and also to represent + * extensions in {@link GeneratedMessage}. This class is package-private, + * since outside users should probably be using {@link DynamicMessage}. + * + * @author kenton@google.com Kenton Varda + */ +final class FieldSet> { + /** + * Interface for a FieldDescriptor or lite extension descriptor. This + * prevents FieldSet from depending on {@link Descriptors.FieldDescriptor}. + */ + public interface FieldDescriptorLite> + extends Comparable { + int getNumber(); + WireFormat.FieldType getLiteType(); + WireFormat.JavaType getLiteJavaType(); + boolean isRepeated(); + boolean isPacked(); + Internal.EnumLiteMap getEnumType(); + + // If getLiteJavaType() == MESSAGE, this merges a message object of the + // type into a builder of the type. Returns {@code to}. + MessageLite.Builder internalMergeFrom( + MessageLite.Builder to, MessageLite from); + } + + private Map fields; + + /** Construct a new FieldSet. */ + private FieldSet() { + // Use a TreeMap because fields need to be in canonical order when + // serializing. + // TODO(kenton): Maybe use some sort of sparse array instead? It would + // even make sense to store the first 16 or so tags in a flat array + // to make DynamicMessage faster. + fields = new TreeMap(); + } + + /** + * Construct an empty FieldSet. This is only used to initialize + * DEFAULT_INSTANCE. + */ + private FieldSet(final boolean dummy) { + this.fields = Collections.emptyMap(); + } + + /** Construct a new FieldSet. */ + public static > + FieldSet newFieldSet() { + return new FieldSet(); + } + + /** Get an immutable empty FieldSet. */ + @SuppressWarnings("unchecked") + public static > + FieldSet emptySet() { + return DEFAULT_INSTANCE; + } + @SuppressWarnings("unchecked") + private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true); + + /** Make this FieldSet immutable from this point forward. */ + @SuppressWarnings("unchecked") + public void makeImmutable() { + for (final Map.Entry entry: + fields.entrySet()) { + if (entry.getKey().isRepeated()) { + final List value = (List)entry.getValue(); + fields.put(entry.getKey(), Collections.unmodifiableList(value)); + } + } + fields = Collections.unmodifiableMap(fields); + } + + // ================================================================= + + /** See {@link Message.Builder#clear()}. */ + public void clear() { + fields.clear(); + } + + /** + * Get a simple map containing all the fields. + */ + public Map getAllFields() { + return Collections.unmodifiableMap(fields); + } + + /** + * Get an iterator to the field map. This iterator should not be leaked + * out of the protobuf library as it is not protected from mutation. + */ + public Iterator> iterator() { + return fields.entrySet().iterator(); + } + + /** + * Useful for implementing + * {@link Message#hasField(Descriptors.FieldDescriptor)}. + */ + public boolean hasField(final FieldDescriptorType descriptor) { + if (descriptor.isRepeated()) { + throw new IllegalArgumentException( + "hasField() can only be called on non-repeated fields."); + } + + return fields.get(descriptor) != null; + } + + /** + * Useful for implementing + * {@link Message#getField(Descriptors.FieldDescriptor)}. This method + * returns {@code null} if the field is not set; in this case it is up + * to the caller to fetch the field's default value. + */ + public Object getField(final FieldDescriptorType descriptor) { + return fields.get(descriptor); + } + + /** + * Useful for implementing + * {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. + */ + @SuppressWarnings("unchecked") + public void setField(final FieldDescriptorType descriptor, + Object value) { + if (descriptor.isRepeated()) { + if (!(value instanceof List)) { + throw new IllegalArgumentException( + "Wrong object type used with protocol message reflection."); + } + + // Wrap the contents in a new list so that the caller cannot change + // the list's contents after setting it. + final List newList = new ArrayList(); + newList.addAll((List)value); + for (final Object element : newList) { + verifyType(descriptor.getLiteType(), element); + } + value = newList; + } else { + verifyType(descriptor.getLiteType(), value); + } + + fields.put(descriptor, value); + } + + /** + * Useful for implementing + * {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. + */ + public void clearField(final FieldDescriptorType descriptor) { + fields.remove(descriptor); + } + + /** + * Useful for implementing + * {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. + */ + public int getRepeatedFieldCount(final FieldDescriptorType descriptor) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object value = fields.get(descriptor); + if (value == null) { + return 0; + } else { + return ((List) value).size(); + } + } + + /** + * Useful for implementing + * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. + */ + @SuppressWarnings("unchecked") +public Object getRepeatedField(final FieldDescriptorType descriptor, + final int index) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object value = fields.get(descriptor); + + if (value == null) { + throw new IndexOutOfBoundsException(); + } else { + return ((List) value).get(index); + } + } + + /** + * Useful for implementing + * {@link Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}. + */ + @SuppressWarnings("unchecked") + public void setRepeatedField(final FieldDescriptorType descriptor, + final int index, + final Object value) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object list = fields.get(descriptor); + if (list == null) { + throw new IndexOutOfBoundsException(); + } + + verifyType(descriptor.getLiteType(), value); + ((List) list).set(index, value); + } + + /** + * Useful for implementing + * {@link Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. + */ + @SuppressWarnings("unchecked") + public void addRepeatedField(final FieldDescriptorType descriptor, + final Object value) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "addRepeatedField() can only be called on repeated fields."); + } + + verifyType(descriptor.getLiteType(), value); + + final Object existingValue = fields.get(descriptor); + List list; + if (existingValue == null) { + list = new ArrayList(); + fields.put(descriptor, list); + } else { + list = (List) existingValue; + } + + list.add(value); + } + + /** + * Verifies that the given object is of the correct type to be a valid + * value for the given field. (For repeated fields, this checks if the + * object is the right type to be one element of the field.) + * + * @throws IllegalArgumentException The value is not of the right type. + */ + private static void verifyType(final WireFormat.FieldType type, + final Object value) { + if (value == null) { + throw new NullPointerException(); + } + + boolean isValid = false; + switch (type.getJavaType()) { + case INT: isValid = value instanceof Integer ; break; + case LONG: isValid = value instanceof Long ; break; + case FLOAT: isValid = value instanceof Float ; break; + case DOUBLE: isValid = value instanceof Double ; break; + case BOOLEAN: isValid = value instanceof Boolean ; break; + case STRING: isValid = value instanceof String ; break; + case BYTE_STRING: isValid = value instanceof ByteString; break; + case ENUM: + // TODO(kenton): Caller must do type checking here, I guess. + isValid = value instanceof Internal.EnumLite; + break; + case MESSAGE: + // TODO(kenton): Caller must do type checking here, I guess. + isValid = value instanceof MessageLite; + break; + } + + if (!isValid) { + // TODO(kenton): When chaining calls to setField(), it can be hard to + // tell from the stack trace which exact call failed, since the whole + // chain is considered one line of code. It would be nice to print + // more information here, e.g. naming the field. We used to do that. + // But we can't now that FieldSet doesn't use descriptors. Maybe this + // isn't a big deal, though, since it would only really apply when using + // reflection and generally people don't chain reflection setters. + throw new IllegalArgumentException( + "Wrong object type used with protocol message reflection."); + } + } + + // ================================================================= + // Parsing and serialization + + /** + * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} + * itself does not have any way of knowing about required fields that + * aren't actually present in the set, it is up to the caller to check + * that all required fields are present. + */ + @SuppressWarnings("unchecked") + public boolean isInitialized() { + for (final Map.Entry entry: + fields.entrySet()) { + final FieldDescriptorType descriptor = entry.getKey(); + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { + if (descriptor.isRepeated()) { + for (final MessageLite element: + (List) entry.getValue()) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (!((MessageLite) entry.getValue()).isInitialized()) { + return false; + } + } + } + } + + return true; + } + + /** + * Given a field type, return the wire type. + * + * @returns One of the {@code WIRETYPE_} constants defined in + * {@link WireFormat}. + */ + static int getWireFormatForFieldType(final WireFormat.FieldType type, + boolean isPacked) { + if (isPacked) { + return WireFormat.WIRETYPE_LENGTH_DELIMITED; + } else { + return type.getWireType(); + } + } + + /** + * Like {@link #mergeFrom(Message)}, but merges from another {@link FieldSet}. + */ + @SuppressWarnings("unchecked") + public void mergeFrom(final FieldSet other) { + for (final Map.Entry entry: + other.fields.entrySet()) { + final FieldDescriptorType descriptor = entry.getKey(); + final Object otherValue = entry.getValue(); + + if (descriptor.isRepeated()) { + Object value = fields.get(descriptor); + if (value == null) { + // Our list is empty, but we still need to make a defensive copy of + // the other list since we don't know if the other FieldSet is still + // mutable. + fields.put(descriptor, new ArrayList((List) otherValue)); + } else { + // Concatenate the lists. + ((List) value).addAll((List) otherValue); + } + } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { + Object value = fields.get(descriptor); + if (value == null) { + fields.put(descriptor, otherValue); + } else { + // Merge the messages. + fields.put(descriptor, + descriptor.internalMergeFrom( + ((MessageLite) value).toBuilder(), (MessageLite) otherValue) + .build()); + } + + } else { + fields.put(descriptor, otherValue); + } + } + } + + // TODO(kenton): Move static parsing and serialization methods into some + // other class. Probably WireFormat. + + /** + * Read a field of any primitive type from a CodedInputStream. Enums, + * groups, and embedded messages are not handled by this method. + * + * @param input The stream from which to read. + * @param type Declared type of the field. + * @return An object representing the field's value, of the exact + * type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for + * this field. + */ + public static Object readPrimitiveField( + CodedInputStream input, + final WireFormat.FieldType type) throws IOException { + switch (type) { + case DOUBLE : return input.readDouble (); + case FLOAT : return input.readFloat (); + case INT64 : return input.readInt64 (); + case UINT64 : return input.readUInt64 (); + case INT32 : return input.readInt32 (); + case FIXED64 : return input.readFixed64 (); + case FIXED32 : return input.readFixed32 (); + case BOOL : return input.readBool (); + case STRING : return input.readString (); + case BYTES : return input.readBytes (); + case UINT32 : return input.readUInt32 (); + case SFIXED32: return input.readSFixed32(); + case SFIXED64: return input.readSFixed64(); + case SINT32 : return input.readSInt32 (); + case SINT64 : return input.readSInt64 (); + + case GROUP: + throw new IllegalArgumentException( + "readPrimitiveField() cannot handle nested groups."); + case MESSAGE: + throw new IllegalArgumentException( + "readPrimitiveField() cannot handle embedded messages."); + case ENUM: + // We don't handle enums because we don't know what to do if the + // value is not recognized. + throw new IllegalArgumentException( + "readPrimitiveField() cannot handle enums."); + } + + throw new RuntimeException( + "There is no way to get here, but the compiler thinks otherwise."); + } + + /** See {@link Message#writeTo(CodedOutputStream)}. */ + public void writeTo(final CodedOutputStream output) + throws IOException { + for (final Map.Entry entry: + fields.entrySet()) { + writeField(entry.getKey(), entry.getValue(), output); + } + } + + /** + * Like {@link #writeTo} but uses MessageSet wire format. + */ + public void writeMessageSetTo(final CodedOutputStream output) + throws IOException { + for (final Map.Entry entry: + fields.entrySet()) { + final FieldDescriptorType descriptor = entry.getKey(); + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && + !descriptor.isRepeated() && !descriptor.isPacked()) { + output.writeMessageSetExtension(entry.getKey().getNumber(), + (MessageLite) entry.getValue()); + } else { + writeField(descriptor, entry.getValue(), output); + } + } + } + + /** + * Write a single tag-value pair to the stream. + * + * @param output The output stream. + * @param type The field's type. + * @param number The field's number. + * @param value Object representing the field's value. Must be of the exact + * type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for + * this field. + */ + private static void writeElement(final CodedOutputStream output, + final WireFormat.FieldType type, + final int number, + final Object value) throws IOException { + // Special case for groups, which need a start and end tag; other fields + // can just use writeTag() and writeFieldNoTag(). + if (type == WireFormat.FieldType.GROUP) { + output.writeGroup(number, (MessageLite) value); + } else { + output.writeTag(number, getWireFormatForFieldType(type, false)); + writeElementNoTag(output, type, value); + } + } + + /** + * Write a field of arbitrary type, without its tag, to the stream. + * + * @param output The output stream. + * @param type The field's type. + * @param value Object representing the field's value. Must be of the exact + * type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for + * this field. + */ + private static void writeElementNoTag( + final CodedOutputStream output, + final WireFormat.FieldType type, + final Object value) throws IOException { + switch (type) { + case DOUBLE : output.writeDoubleNoTag ((Double ) value); break; + case FLOAT : output.writeFloatNoTag ((Float ) value); break; + case INT64 : output.writeInt64NoTag ((Long ) value); break; + case UINT64 : output.writeUInt64NoTag ((Long ) value); break; + case INT32 : output.writeInt32NoTag ((Integer ) value); break; + case FIXED64 : output.writeFixed64NoTag ((Long ) value); break; + case FIXED32 : output.writeFixed32NoTag ((Integer ) value); break; + case BOOL : output.writeBoolNoTag ((Boolean ) value); break; + case STRING : output.writeStringNoTag ((String ) value); break; + case GROUP : output.writeGroupNoTag ((MessageLite) value); break; + case MESSAGE : output.writeMessageNoTag ((MessageLite) value); break; + case BYTES : output.writeBytesNoTag ((ByteString ) value); break; + case UINT32 : output.writeUInt32NoTag ((Integer ) value); break; + case SFIXED32: output.writeSFixed32NoTag((Integer ) value); break; + case SFIXED64: output.writeSFixed64NoTag((Long ) value); break; + case SINT32 : output.writeSInt32NoTag ((Integer ) value); break; + case SINT64 : output.writeSInt64NoTag ((Long ) value); break; + + case ENUM: + output.writeEnumNoTag(((Internal.EnumLite) value).getNumber()); + break; + } + } + + /** Write a single field. */ + @SuppressWarnings("unchecked") +public static void writeField(final FieldDescriptorLite descriptor, + final Object value, + final CodedOutputStream output) + throws IOException { + WireFormat.FieldType type = descriptor.getLiteType(); + int number = descriptor.getNumber(); + if (descriptor.isRepeated()) { + final List valueList = (List)value; + if (descriptor.isPacked()) { + output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED); + // Compute the total data size so the length can be written. + int dataSize = 0; + for (final Object element : valueList) { + dataSize += computeElementSizeNoTag(type, element); + } + output.writeRawVarint32(dataSize); + // Write the data itself, without any tags. + for (final Object element : valueList) { + writeElementNoTag(output, type, element); + } + } else { + for (final Object element : valueList) { + writeElement(output, type, number, element); + } + } + } else { + writeElement(output, type, number, value); + } + } + + /** + * See {@link Message#getSerializedSize()}. It's up to the caller to cache + * the resulting size if desired. + */ + public int getSerializedSize() { + int size = 0; + for (final Map.Entry entry: + fields.entrySet()) { + size += computeFieldSize(entry.getKey(), entry.getValue()); + } + return size; + } + + /** + * Like {@link #getSerializedSize} but uses MessageSet wire format. + */ + public int getMessageSetSerializedSize() { + int size = 0; + for (final Map.Entry entry: + fields.entrySet()) { + final FieldDescriptorType descriptor = entry.getKey(); + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && + !descriptor.isRepeated() && !descriptor.isPacked()) { + size += CodedOutputStream.computeMessageSetExtensionSize( + entry.getKey().getNumber(), (MessageLite) entry.getValue()); + } else { + size += computeFieldSize(descriptor, entry.getValue()); + } + } + return size; + } + + /** + * Compute the number of bytes that would be needed to encode a + * single tag/value pair of arbitrary type. + * + * @param type The field's type. + * @param number The field's number. + * @param value Object representing the field's value. Must be of the exact + * type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for + * this field. + */ + private static int computeElementSize( + final WireFormat.FieldType type, + final int number, final Object value) { + int tagSize = CodedOutputStream.computeTagSize(number); + if (type == WireFormat.FieldType.GROUP) { + tagSize *= 2; + } + return tagSize + computeElementSizeNoTag(type, value); + } + + /** + * Compute the number of bytes that would be needed to encode a + * particular value of arbitrary type, excluding tag. + * + * @param type The field's type. + * @param value Object representing the field's value. Must be of the exact + * type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for + * this field. + */ + private static int computeElementSizeNoTag( + final WireFormat.FieldType type, final Object value) { + switch (type) { + // Note: Minor violation of 80-char limit rule here because this would + // actually be harder to read if we wrapped the lines. + case DOUBLE : return CodedOutputStream.computeDoubleSizeNoTag ((Double )value); + case FLOAT : return CodedOutputStream.computeFloatSizeNoTag ((Float )value); + case INT64 : return CodedOutputStream.computeInt64SizeNoTag ((Long )value); + case UINT64 : return CodedOutputStream.computeUInt64SizeNoTag ((Long )value); + case INT32 : return CodedOutputStream.computeInt32SizeNoTag ((Integer )value); + case FIXED64 : return CodedOutputStream.computeFixed64SizeNoTag ((Long )value); + case FIXED32 : return CodedOutputStream.computeFixed32SizeNoTag ((Integer )value); + case BOOL : return CodedOutputStream.computeBoolSizeNoTag ((Boolean )value); + case STRING : return CodedOutputStream.computeStringSizeNoTag ((String )value); + case GROUP : return CodedOutputStream.computeGroupSizeNoTag ((MessageLite)value); + case MESSAGE : return CodedOutputStream.computeMessageSizeNoTag ((MessageLite)value); + case BYTES : return CodedOutputStream.computeBytesSizeNoTag ((ByteString )value); + case UINT32 : return CodedOutputStream.computeUInt32SizeNoTag ((Integer )value); + case SFIXED32: return CodedOutputStream.computeSFixed32SizeNoTag((Integer )value); + case SFIXED64: return CodedOutputStream.computeSFixed64SizeNoTag((Long )value); + case SINT32 : return CodedOutputStream.computeSInt32SizeNoTag ((Integer )value); + case SINT64 : return CodedOutputStream.computeSInt64SizeNoTag ((Long )value); + + case ENUM: + return CodedOutputStream.computeEnumSizeNoTag( + ((Internal.EnumLite) value).getNumber()); + } + + throw new RuntimeException( + "There is no way to get here, but the compiler thinks otherwise."); + } + + /** + * Compute the number of bytes needed to encode a particular field. + */ + @SuppressWarnings("unchecked") +public static int computeFieldSize(final FieldDescriptorLite descriptor, + final Object value) { + WireFormat.FieldType type = descriptor.getLiteType(); + int number = descriptor.getNumber(); + if (descriptor.isRepeated()) { + if (descriptor.isPacked()) { + int dataSize = 0; + for (final Object element : (List)value) { + dataSize += computeElementSizeNoTag(type, element); + } + return dataSize + + CodedOutputStream.computeTagSize(number) + + CodedOutputStream.computeRawVarint32Size(dataSize); + } else { + int size = 0; + for (final Object element : (List)value) { + size += computeElementSize(type, number, element); + } + return size; + } + } else { + return computeElementSize(type, number, value); + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/GeneratedMessage.java b/DataExtractionOSM/src/com/google/protobuf/GeneratedMessage.java new file mode 100644 index 0000000000..74774cefde --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/GeneratedMessage.java @@ -0,0 +1,1324 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * All generated protocol message classes extend this class. This class + * implements most of the Message and Builder interfaces using Java reflection. + * Users can ignore this class and pretend that generated messages implement + * the Message interface directly. + * + * @author kenton@google.com Kenton Varda + */ +public abstract class GeneratedMessage extends AbstractMessage { + protected GeneratedMessage() {} + + private UnknownFieldSet unknownFields = UnknownFieldSet.getDefaultInstance(); + + /** + * Get the FieldAccessorTable for this type. We can't have the message + * class pass this in to the constructor because of bootstrapping trouble + * with DescriptorProtos. + */ + protected abstract FieldAccessorTable internalGetFieldAccessorTable(); + + public Descriptor getDescriptorForType() { + return internalGetFieldAccessorTable().descriptor; + } + + /** Internal helper which returns a mutable map. */ + @SuppressWarnings("unchecked") +private Map getAllFieldsMutable() { + final TreeMap result = + new TreeMap(); + final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; + for (final FieldDescriptor field : descriptor.getFields()) { + if (field.isRepeated()) { + final List value = (List) getField(field); + if (!value.isEmpty()) { + result.put(field, value); + } + } else { + if (hasField(field)) { + result.put(field, getField(field)); + } + } + } + return result; + } + + @Override + public boolean isInitialized() { + for (final FieldDescriptor field : getDescriptorForType().getFields()) { + // Check that all required fields are present. + if (field.isRequired()) { + if (!hasField(field)) { + return false; + } + } + // Check that embedded messages are initialized. + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + @SuppressWarnings("unchecked") final + List messageList = (List) getField(field); + for (final Message element : messageList) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (hasField(field) && !((Message) getField(field)).isInitialized()) { + return false; + } + } + } + } + + return true; + } + + public Map getAllFields() { + return Collections.unmodifiableMap(getAllFieldsMutable()); + } + + public boolean hasField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).has(this); + } + + public Object getField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).get(this); + } + + public int getRepeatedFieldCount(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field) + .getRepeatedCount(this); + } + + public Object getRepeatedField(final FieldDescriptor field, final int index) { + return internalGetFieldAccessorTable().getField(field) + .getRepeated(this, index); + } + + public final UnknownFieldSet getUnknownFields() { + return unknownFields; + } + + @SuppressWarnings("unchecked") + public abstract static class Builder + extends AbstractMessage.Builder { + protected Builder() {} + + // This is implemented here only to work around an apparent bug in the + // Java compiler and/or build system. See bug #1898463. The mere presence + // of this dummy clone() implementation makes it go away. + @Override + public BuilderType clone() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + /** + * Get the message being built. We don't just pass this to the + * constructor because it becomes null when build() is called. + */ + protected abstract GeneratedMessage internalGetResult(); + + /** + * Get the FieldAccessorTable for this type. We can't have the message + * class pass this in to the constructor because of bootstrapping trouble + * with DescriptorProtos. + */ + private FieldAccessorTable internalGetFieldAccessorTable() { + return internalGetResult().internalGetFieldAccessorTable(); + } + + public Descriptor getDescriptorForType() { + return internalGetFieldAccessorTable().descriptor; + } + + public Map getAllFields() { + return internalGetResult().getAllFields(); + } + + public Message.Builder newBuilderForField( + final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).newBuilder(); + } + + public boolean hasField(final FieldDescriptor field) { + return internalGetResult().hasField(field); + } + + public Object getField(final FieldDescriptor field) { + if (field.isRepeated()) { + // The underlying list object is still modifiable at this point. + // Make sure not to expose the modifiable list to the caller. + return Collections.unmodifiableList( + (List) internalGetResult().getField(field)); + } else { + return internalGetResult().getField(field); + } + } + + public BuilderType setField(final FieldDescriptor field, + final Object value) { + internalGetFieldAccessorTable().getField(field).set(this, value); + return (BuilderType) this; + } + + public BuilderType clearField(final FieldDescriptor field) { + internalGetFieldAccessorTable().getField(field).clear(this); + return (BuilderType) this; + } + + public int getRepeatedFieldCount(final FieldDescriptor field) { + return internalGetResult().getRepeatedFieldCount(field); + } + + public Object getRepeatedField(final FieldDescriptor field, + final int index) { + return internalGetResult().getRepeatedField(field, index); + } + + public BuilderType setRepeatedField(final FieldDescriptor field, + final int index, final Object value) { + internalGetFieldAccessorTable().getField(field) + .setRepeated(this, index, value); + return (BuilderType) this; + } + + public BuilderType addRepeatedField(final FieldDescriptor field, + final Object value) { + internalGetFieldAccessorTable().getField(field).addRepeated(this, value); + return (BuilderType) this; + } + + public final UnknownFieldSet getUnknownFields() { + return internalGetResult().unknownFields; + } + + public final BuilderType setUnknownFields( + final UnknownFieldSet unknownFields) { + internalGetResult().unknownFields = unknownFields; + return (BuilderType) this; + } + + @Override + public final BuilderType mergeUnknownFields( + final UnknownFieldSet unknownFields) { + final GeneratedMessage result = internalGetResult(); + result.unknownFields = + UnknownFieldSet.newBuilder(result.unknownFields) + .mergeFrom(unknownFields) + .build(); + return (BuilderType) this; + } + + public boolean isInitialized() { + return internalGetResult().isInitialized(); + } + + /** + * Called by subclasses to parse an unknown field. + * @return {@code true} unless the tag is an end-group tag. + */ + protected boolean parseUnknownField( + final CodedInputStream input, + final UnknownFieldSet.Builder unknownFields, + final ExtensionRegistryLite extensionRegistry, + final int tag) throws IOException { + return unknownFields.mergeFieldFrom(tag, input); + } + } + + // ================================================================= + // Extensions-related stuff + + /** + * Generated message classes for message types that contain extension ranges + * subclass this. + * + *

This class implements type-safe accessors for extensions. They + * implement all the same operations that you can do with normal fields -- + * e.g. "has", "get", and "getCount" -- but for extensions. The extensions + * are identified using instances of the class {@link GeneratedExtension}; + * the protocol compiler generates a static instance of this class for every + * extension in its input. Through the magic of generics, all is made + * type-safe. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then you might write code like: + * + *

+   * MyProto.Foo foo = getFoo();
+   * int i = foo.getExtension(MyProto.bar);
+   * 
+ * + *

See also {@link ExtendableBuilder}. + */ + public abstract static class ExtendableMessage< + MessageType extends ExtendableMessage> + extends GeneratedMessage { + protected ExtendableMessage() {} + private final FieldSet extensions = FieldSet.newFieldSet(); + + private void verifyExtensionContainingType( + final GeneratedExtension extension) { + if (extension.getDescriptor().getContainingType() != + getDescriptorForType()) { + // This can only happen if someone uses unchecked operations. + throw new IllegalArgumentException( + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + "\"."); + } + } + + /** Check if a singular extension is present. */ + public final boolean hasExtension( + final GeneratedExtension extension) { + verifyExtensionContainingType(extension); + return extensions.hasField(extension.getDescriptor()); + } + + /** Get the number of elements in a repeated extension. */ + public final int getExtensionCount( + final GeneratedExtension> extension) { + verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + return extensions.getRepeatedFieldCount(descriptor); + } + + /** Get the value of an extension. */ + @SuppressWarnings("unchecked") + public final Type getExtension( + final GeneratedExtension extension) { + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + final Object value = extensions.getField(descriptor); + if (value == null) { + if (descriptor.isRepeated()) { + return (Type) Collections.emptyList(); + } else if (descriptor.getJavaType() == + FieldDescriptor.JavaType.MESSAGE) { + return (Type) extension.getMessageDefaultInstance(); + } else { + return (Type) extension.fromReflectionType( + descriptor.getDefaultValue()); + } + } else { + return (Type) extension.fromReflectionType(value); + } + } + + /** Get one element of a repeated extension. */ + @SuppressWarnings("unchecked") + public final Type getExtension( + final GeneratedExtension> extension, + final int index) { + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + return (Type) extension.singularFromReflectionType( + extensions.getRepeatedField(descriptor, index)); + } + + /** Called by subclasses to check if all extensions are initialized. */ + protected boolean extensionsAreInitialized() { + return extensions.isInitialized(); + } + + @Override + public boolean isInitialized() { + return super.isInitialized() && extensionsAreInitialized(); + } + + /** + * Used by subclasses to serialize extensions. Extension ranges may be + * interleaved with field numbers, but we must write them in canonical + * (sorted by field number) order. ExtensionWriter helps us write + * individual ranges of extensions at once. + */ + protected class ExtensionWriter { + // Imagine how much simpler this code would be if Java iterators had + // a way to get the next element without advancing the iterator. + + private final Iterator> iter = + extensions.iterator(); + private Map.Entry next; + private final boolean messageSetWireFormat; + + private ExtensionWriter(final boolean messageSetWireFormat) { + if (iter.hasNext()) { + next = iter.next(); + } + this.messageSetWireFormat = messageSetWireFormat; + } + + public void writeUntil(final int end, final CodedOutputStream output) + throws IOException { + while (next != null && next.getKey().getNumber() < end) { + FieldDescriptor descriptor = next.getKey(); + if (messageSetWireFormat && descriptor.getLiteJavaType() == + WireFormat.JavaType.MESSAGE && + !descriptor.isRepeated()) { + output.writeMessageSetExtension(descriptor.getNumber(), + (Message) next.getValue()); + } else { + FieldSet.writeField(descriptor, next.getValue(), output); + } + if (iter.hasNext()) { + next = iter.next(); + } else { + next = null; + } + } + } + } + + protected ExtensionWriter newExtensionWriter() { + return new ExtensionWriter(false); + } + protected ExtensionWriter newMessageSetExtensionWriter() { + return new ExtensionWriter(true); + } + + /** Called by subclasses to compute the size of extensions. */ + protected int extensionsSerializedSize() { + return extensions.getSerializedSize(); + } + protected int extensionsSerializedSizeAsMessageSet() { + return extensions.getMessageSetSerializedSize(); + } + + // --------------------------------------------------------------- + // Reflection + + @Override + public Map getAllFields() { + final Map result = super.getAllFieldsMutable(); + result.putAll(extensions.getAllFields()); + return Collections.unmodifiableMap(result); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.hasField(field); + } else { + return super.hasField(field); + } + } + + @Override + public Object getField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + final Object value = extensions.getField(field); + if (value == null) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + // Lacking an ExtensionRegistry, we have no way to determine the + // extension's real type, so we return a DynamicMessage. + return DynamicMessage.getDefaultInstance(field.getMessageType()); + } else { + return field.getDefaultValue(); + } + } else { + return value; + } + } else { + return super.getField(field); + } + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedFieldCount(field); + } else { + return super.getRepeatedFieldCount(field); + } + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, + final int index) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedField(field, index); + } else { + return super.getRepeatedField(field, index); + } + } + + private void verifyContainingType(final FieldDescriptor field) { + if (field.getContainingType() != getDescriptorForType()) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + } + + /** + * Generated message builders for message types that contain extension ranges + * subclass this. + * + *

This class implements type-safe accessors for extensions. They + * implement all the same operations that you can do with normal fields -- + * e.g. "get", "set", and "add" -- but for extensions. The extensions are + * identified using instances of the class {@link GeneratedExtension}; the + * protocol compiler generates a static instance of this class for every + * extension in its input. Through the magic of generics, all is made + * type-safe. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then you might write code like: + * + *

+   * MyProto.Foo foo =
+   *   MyProto.Foo.newBuilder()
+   *     .setExtension(MyProto.bar, 123)
+   *     .build();
+   * 
+ * + *

See also {@link ExtendableMessage}. + */ + @SuppressWarnings("unchecked") + public abstract static class ExtendableBuilder< + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends Builder { + protected ExtendableBuilder() {} + + // This is implemented here only to work around an apparent bug in the + // Java compiler and/or build system. See bug #1898463. The mere presence + // of this dummy clone() implementation makes it go away. + @Override + public BuilderType clone() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + @Override + protected abstract ExtendableMessage internalGetResult(); + + /** Check if a singular extension is present. */ + public final boolean hasExtension( + final GeneratedExtension extension) { + return internalGetResult().hasExtension(extension); + } + + /** Get the number of elements in a repeated extension. */ + public final int getExtensionCount( + final GeneratedExtension> extension) { + return internalGetResult().getExtensionCount(extension); + } + + /** Get the value of an extension. */ + public final Type getExtension( + final GeneratedExtension extension) { + return internalGetResult().getExtension(extension); + } + + /** Get one element of a repeated extension. */ + public final Type getExtension( + final GeneratedExtension> extension, + final int index) { + return internalGetResult().getExtension(extension, index); + } + + /** Set the value of an extension. */ + public final BuilderType setExtension( + final GeneratedExtension extension, + final Type value) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + message.extensions.setField(descriptor, + extension.toReflectionType(value)); + return (BuilderType) this; + } + + /** Set the value of one element of a repeated extension. */ + public final BuilderType setExtension( + final GeneratedExtension> extension, + final int index, final Type value) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + message.extensions.setRepeatedField( + descriptor, index, + extension.singularToReflectionType(value)); + return (BuilderType) this; + } + + /** Append a value to a repeated extension. */ + public final BuilderType addExtension( + final GeneratedExtension> extension, + final Type value) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + message.extensions.addRepeatedField( + descriptor, extension.singularToReflectionType(value)); + return (BuilderType) this; + } + + /** Clear an extension. */ + public final BuilderType clearExtension( + final GeneratedExtension extension) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + message.extensions.clearField(extension.getDescriptor()); + return (BuilderType) this; + } + + /** + * Called by subclasses to parse an unknown field or an extension. + * @return {@code true} unless the tag is an end-group tag. + */ + @Override + protected boolean parseUnknownField( + final CodedInputStream input, + final UnknownFieldSet.Builder unknownFields, + final ExtensionRegistryLite extensionRegistry, + final int tag) throws IOException { + final ExtendableMessage message = internalGetResult(); + return AbstractMessage.Builder.mergeFieldFrom( + input, unknownFields, extensionRegistry, this, tag); + } + + // --------------------------------------------------------------- + // Reflection + + // We don't have to override the get*() methods here because they already + // just forward to the underlying message. + + @Override + public BuilderType setField(final FieldDescriptor field, + final Object value) { + if (field.isExtension()) { + final ExtendableMessage message = internalGetResult(); + message.verifyContainingType(field); + message.extensions.setField(field, value); + return (BuilderType) this; + } else { + return super.setField(field, value); + } + } + + @Override + public BuilderType clearField(final FieldDescriptor field) { + if (field.isExtension()) { + final ExtendableMessage message = internalGetResult(); + message.verifyContainingType(field); + message.extensions.clearField(field); + return (BuilderType) this; + } else { + return super.clearField(field); + } + } + + @Override + public BuilderType setRepeatedField(final FieldDescriptor field, + final int index, final Object value) { + if (field.isExtension()) { + final ExtendableMessage message = internalGetResult(); + message.verifyContainingType(field); + message.extensions.setRepeatedField(field, index, value); + return (BuilderType) this; + } else { + return super.setRepeatedField(field, index, value); + } + } + + @Override + public BuilderType addRepeatedField(final FieldDescriptor field, + final Object value) { + if (field.isExtension()) { + final ExtendableMessage message = internalGetResult(); + message.verifyContainingType(field); + message.extensions.addRepeatedField(field, value); + return (BuilderType) this; + } else { + return super.addRepeatedField(field, value); + } + } + + protected final void mergeExtensionFields(final ExtendableMessage other) { + internalGetResult().extensions.mergeFrom(other.extensions); + } + } + + // ----------------------------------------------------------------- + + /** For use by generated code only. */ + public static + GeneratedExtension + newGeneratedExtension() { + return new GeneratedExtension(); + } + + /** + * Type used to represent generated extensions. The protocol compiler + * generates a static singleton instance of this class for each extension. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then, {@code MyProto.Foo.bar} has type + * {@code GeneratedExtension}. + * + *

In general, users should ignore the details of this type, and simply use + * these static singletons as parameters to the extension accessors defined + * in {@link ExtendableMessage} and {@link ExtendableBuilder}. + */ + public static final class GeneratedExtension< + ContainingType extends Message, Type> { + // TODO(kenton): Find ways to avoid using Java reflection within this + // class. Also try to avoid suppressing unchecked warnings. + + // We can't always initialize a GeneratedExtension when we first construct + // it due to initialization order difficulties (namely, the descriptor may + // not have been constructed yet, since it is often constructed by the + // initializer of a separate module). So, we construct an uninitialized + // GeneratedExtension once, then call internalInit() on it later. Generated + // code will always call internalInit() on all extensions as part of the + // static initialization code, and internalInit() throws an exception if + // called more than once, so this method is useless to users. + private GeneratedExtension() {} + + /** For use by generated code only. */ + public void internalInit(final FieldDescriptor descriptor, + final Class type) { + if (this.descriptor != null) { + throw new IllegalStateException("Already initialized."); + } + + if (!descriptor.isExtension()) { + throw new IllegalArgumentException( + "GeneratedExtension given a regular (non-extension) field."); + } + + this.descriptor = descriptor; + this.type = type; + + switch (descriptor.getJavaType()) { + case MESSAGE: + enumValueOf = null; + enumGetValueDescriptor = null; + messageDefaultInstance = + (Message) invokeOrDie(getMethodOrDie(type, "getDefaultInstance"), + null); + if (messageDefaultInstance == null) { + throw new IllegalStateException( + type.getName() + ".getDefaultInstance() returned null."); + } + break; + case ENUM: + enumValueOf = getMethodOrDie(type, "valueOf", + EnumValueDescriptor.class); + enumGetValueDescriptor = getMethodOrDie(type, "getValueDescriptor"); + messageDefaultInstance = null; + break; + default: + enumValueOf = null; + enumGetValueDescriptor = null; + messageDefaultInstance = null; + break; + } + } + + private FieldDescriptor descriptor; + private Class type; + private Method enumValueOf; + private Method enumGetValueDescriptor; + private Message messageDefaultInstance; + + public FieldDescriptor getDescriptor() { return descriptor; } + + /** + * If the extension is an embedded message or group, returns the default + * instance of the message. + */ + @SuppressWarnings("unchecked") + public Message getMessageDefaultInstance() { + return messageDefaultInstance; + } + + /** + * Convert from the type used by the reflection accessors to the type used + * by native accessors. E.g., for enums, the reflection accessors use + * EnumValueDescriptors but the native accessors use the generated enum + * type. + */ + @SuppressWarnings("unchecked") + private Object fromReflectionType(final Object value) { + if (descriptor.isRepeated()) { + if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE || + descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { + // Must convert the whole list. + final List result = new ArrayList(); + for (final Object element : (List) value) { + result.add(singularFromReflectionType(element)); + } + return result; + } else { + return value; + } + } else { + return singularFromReflectionType(value); + } + } + + /** + * Like {@link #fromReflectionType(Object)}, but if the type is a repeated + * type, this converts a single element. + */ + private Object singularFromReflectionType(final Object value) { + switch (descriptor.getJavaType()) { + case MESSAGE: + if (type.isInstance(value)) { + return value; + } else { + // It seems the copy of the embedded message stored inside the + // extended message is not of the exact type the user was + // expecting. This can happen if a user defines a + // GeneratedExtension manually and gives it a different type. + // This should not happen in normal use. But, to be nice, we'll + // copy the message to whatever type the caller was expecting. + return messageDefaultInstance.newBuilderForType() + .mergeFrom((Message) value).build(); + } + case ENUM: + return invokeOrDie(enumValueOf, null, (EnumValueDescriptor) value); + default: + return value; + } + } + + /** + * Convert from the type used by the native accessors to the type used + * by reflection accessors. E.g., for enums, the reflection accessors use + * EnumValueDescriptors but the native accessors use the generated enum + * type. + */ + @SuppressWarnings("unchecked") + private Object toReflectionType(final Object value) { + if (descriptor.isRepeated()) { + if (descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { + // Must convert the whole list. + final List result = new ArrayList(); + for (final Object element : (List) value) { + result.add(singularToReflectionType(element)); + } + return result; + } else { + return value; + } + } else { + return singularToReflectionType(value); + } + } + + /** + * Like {@link #toReflectionType(Object)}, but if the type is a repeated + * type, this converts a single element. + */ + private Object singularToReflectionType(final Object value) { + switch (descriptor.getJavaType()) { + case ENUM: + return invokeOrDie(enumGetValueDescriptor, value); + default: + return value; + } + } + } + + // ================================================================= + + /** Calls Class.getMethod and throws a RuntimeException if it fails. */ + @SuppressWarnings("unchecked") + private static Method getMethodOrDie( + final Class clazz, final String name, final Class... params) { + try { + return clazz.getMethod(name, params); + } catch (NoSuchMethodException e) { + throw new RuntimeException( + "Generated message class \"" + clazz.getName() + + "\" missing method \"" + name + "\".", e); + } + } + + /** Calls invoke and throws a RuntimeException if it fails. */ + private static Object invokeOrDie( + final Method method, final Object object, final Object... params) { + try { + return method.invoke(object, params); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "Couldn't use Java reflection to implement protocol message " + + "reflection.", e); + } catch (InvocationTargetException e) { + final Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } else if (cause instanceof Error) { + throw (Error) cause; + } else { + throw new RuntimeException( + "Unexpected exception thrown by generated accessor method.", cause); + } + } + } + + /** + * Users should ignore this class. This class provides the implementation + * with access to the fields of a message object using Java reflection. + */ + public static final class FieldAccessorTable { + + /** + * Construct a FieldAccessorTable for a particular message class. Only + * one FieldAccessorTable should ever be constructed per class. + * + * @param descriptor The type's descriptor. + * @param camelCaseNames The camelcase names of all fields in the message. + * These are used to derive the accessor method names. + * @param messageClass The message type. + * @param builderClass The builder type. + */ + public FieldAccessorTable( + final Descriptor descriptor, + final String[] camelCaseNames, + final Class messageClass, + final Class builderClass) { + this.descriptor = descriptor; + fields = new FieldAccessor[descriptor.getFields().size()]; + + for (int i = 0; i < fields.length; i++) { + final FieldDescriptor field = descriptor.getFields().get(i); + if (field.isRepeated()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + fields[i] = new RepeatedMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + fields[i] = new RepeatedEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else { + fields[i] = new RepeatedFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } + } else { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + fields[i] = new SingularMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + fields[i] = new SingularEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else { + fields[i] = new SingularFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } + } + } + } + + private final Descriptor descriptor; + private final FieldAccessor[] fields; + + /** Get the FieldAccessor for a particular field. */ + private FieldAccessor getField(final FieldDescriptor field) { + if (field.getContainingType() != descriptor) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } else if (field.isExtension()) { + // If this type had extensions, it would subclass ExtendableMessage, + // which overrides the reflection interface to handle extensions. + throw new IllegalArgumentException( + "This type does not have extensions."); + } + return fields[field.getIndex()]; + } + + /** + * Abstract interface that provides access to a single field. This is + * implemented differently depending on the field type and cardinality. + */ + private interface FieldAccessor { + Object get(GeneratedMessage message); + void set(Builder builder, Object value); + Object getRepeated(GeneratedMessage message, int index); + void setRepeated(Builder builder, + int index, Object value); + void addRepeated(Builder builder, Object value); + boolean has(GeneratedMessage message); + int getRepeatedCount(GeneratedMessage message); + void clear(Builder builder); + Message.Builder newBuilder(); + } + + // --------------------------------------------------------------- + + private static class SingularFieldAccessor implements FieldAccessor { + SingularFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + getMethod = getMethodOrDie(messageClass, "get" + camelCaseName); + type = getMethod.getReturnType(); + setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type); + hasMethod = + getMethodOrDie(messageClass, "has" + camelCaseName); + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + } + + // Note: We use Java reflection to call public methods rather than + // access private fields directly as this avoids runtime security + // checks. + protected final Class type; + protected final Method getMethod; + protected final Method setMethod; + protected final Method hasMethod; + protected final Method clearMethod; + + public Object get(final GeneratedMessage message) { + return invokeOrDie(getMethod, message); + } + public void set(final Builder builder, final Object value) { + invokeOrDie(setMethod, builder, value); + } + public Object getRepeated(final GeneratedMessage message, + final int index) { + throw new UnsupportedOperationException( + "getRepeatedField() called on a singular field."); + } + public void setRepeated(final Builder builder, + final int index, final Object value) { + throw new UnsupportedOperationException( + "setRepeatedField() called on a singular field."); + } + public void addRepeated(final Builder builder, final Object value) { + throw new UnsupportedOperationException( + "addRepeatedField() called on a singular field."); + } + public boolean has(final GeneratedMessage message) { + return (Boolean) invokeOrDie(hasMethod, message); + } + public int getRepeatedCount(final GeneratedMessage message) { + throw new UnsupportedOperationException( + "getRepeatedFieldSize() called on a singular field."); + } + public void clear(final Builder builder) { + invokeOrDie(clearMethod, builder); + } + public Message.Builder newBuilder() { + throw new UnsupportedOperationException( + "newBuilderForField() called on a non-Message type."); + } + } + + private static class RepeatedFieldAccessor implements FieldAccessor { + RepeatedFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + getMethod = getMethodOrDie(messageClass, + "get" + camelCaseName + "List"); + + getRepeatedMethod = + getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE); + type = getRepeatedMethod.getReturnType(); + setRepeatedMethod = + getMethodOrDie(builderClass, "set" + camelCaseName, + Integer.TYPE, type); + addRepeatedMethod = + getMethodOrDie(builderClass, "add" + camelCaseName, type); + getCountMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Count"); + + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + } + + protected final Class type; + protected final Method getMethod; + protected final Method getRepeatedMethod; + protected final Method setRepeatedMethod; + protected final Method addRepeatedMethod; + protected final Method getCountMethod; + protected final Method clearMethod; + + public Object get(final GeneratedMessage message) { + return invokeOrDie(getMethod, message); + } + public void set(final Builder builder, final Object value) { + // Add all the elements individually. This serves two purposes: + // 1) Verifies that each element has the correct type. + // 2) Insures that the caller cannot modify the list later on and + // have the modifications be reflected in the message. + clear(builder); + for (final Object element : (List) value) { + addRepeated(builder, element); + } + } + public Object getRepeated(final GeneratedMessage message, + final int index) { + return invokeOrDie(getRepeatedMethod, message, index); + } + public void setRepeated(final Builder builder, + final int index, final Object value) { + invokeOrDie(setRepeatedMethod, builder, index, value); + } + public void addRepeated(final Builder builder, final Object value) { + invokeOrDie(addRepeatedMethod, builder, value); + } + public boolean has(final GeneratedMessage message) { + throw new UnsupportedOperationException( + "hasField() called on a singular field."); + } + public int getRepeatedCount(final GeneratedMessage message) { + return (Integer) invokeOrDie(getCountMethod, message); + } + public void clear(final Builder builder) { + invokeOrDie(clearMethod, builder); + } + public Message.Builder newBuilder() { + throw new UnsupportedOperationException( + "newBuilderForField() called on a non-Message type."); + } + } + + // --------------------------------------------------------------- + + private static final class SingularEnumFieldAccessor + extends SingularFieldAccessor { + SingularEnumFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + valueOfMethod = getMethodOrDie(type, "valueOf", + EnumValueDescriptor.class); + getValueDescriptorMethod = + getMethodOrDie(type, "getValueDescriptor"); + } + + private Method valueOfMethod; + private Method getValueDescriptorMethod; + + @Override + public Object get(final GeneratedMessage message) { + return invokeOrDie(getValueDescriptorMethod, super.get(message)); + } + @Override + public void set(final Builder builder, final Object value) { + super.set(builder, invokeOrDie(valueOfMethod, null, value)); + } + } + + private static final class RepeatedEnumFieldAccessor + extends RepeatedFieldAccessor { + RepeatedEnumFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + valueOfMethod = getMethodOrDie(type, "valueOf", + EnumValueDescriptor.class); + getValueDescriptorMethod = + getMethodOrDie(type, "getValueDescriptor"); + } + + private final Method valueOfMethod; + private final Method getValueDescriptorMethod; + + @Override + @SuppressWarnings("unchecked") + public Object get(final GeneratedMessage message) { + final List newList = new ArrayList(); + for (final Object element : (List) super.get(message)) { + newList.add(invokeOrDie(getValueDescriptorMethod, element)); + } + return Collections.unmodifiableList(newList); + } + @Override + public Object getRepeated(final GeneratedMessage message, + final int index) { + return invokeOrDie(getValueDescriptorMethod, + super.getRepeated(message, index)); + } + @Override + public void setRepeated(final Builder builder, + final int index, final Object value) { + super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null, + value)); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value)); + } + } + + // --------------------------------------------------------------- + + private static final class SingularMessageFieldAccessor + extends SingularFieldAccessor { + SingularMessageFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + newBuilderMethod = getMethodOrDie(type, "newBuilder"); + } + + private final Method newBuilderMethod; + + private Object coerceType(final Object value) { + if (type.isInstance(value)) { + return value; + } else { + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) + .mergeFrom((Message) value).build(); + } + } + + @Override + public void set(final Builder builder, final Object value) { + super.set(builder, coerceType(value)); + } + @Override + public Message.Builder newBuilder() { + return (Message.Builder) invokeOrDie(newBuilderMethod, null); + } + } + + private static final class RepeatedMessageFieldAccessor + extends RepeatedFieldAccessor { + RepeatedMessageFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + newBuilderMethod = getMethodOrDie(type, "newBuilder"); + } + + private final Method newBuilderMethod; + + private Object coerceType(final Object value) { + if (type.isInstance(value)) { + return value; + } else { + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) + .mergeFrom((Message) value).build(); + } + } + + @Override + public void setRepeated(final Builder builder, + final int index, final Object value) { + super.setRepeated(builder, index, coerceType(value)); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + super.addRepeated(builder, coerceType(value)); + } + @Override + public Message.Builder newBuilder() { + return (Message.Builder) invokeOrDie(newBuilderMethod, null); + } + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/GeneratedMessageLite.java b/DataExtractionOSM/src/com/google/protobuf/GeneratedMessageLite.java new file mode 100644 index 0000000000..6b29d0e910 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/GeneratedMessageLite.java @@ -0,0 +1,567 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.IOException; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * Lite version of {@link GeneratedMessage}. + * + * @author kenton@google.com Kenton Varda + */ +public abstract class GeneratedMessageLite extends AbstractMessageLite { + protected GeneratedMessageLite() {} + + @SuppressWarnings("unchecked") + public abstract static class Builder + extends AbstractMessageLite.Builder { + protected Builder() {} + + // This is implemented here only to work around an apparent bug in the + // Java compiler and/or build system. See bug #1898463. The mere presence + // of this dummy clone() implementation makes it go away. + @Override + public BuilderType clone() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + /** All subclasses implement this. */ + public abstract BuilderType mergeFrom(MessageType message); + + // Defined here for return type covariance. + public abstract MessageType getDefaultInstanceForType(); + + /** + * Get the message being built. We don't just pass this to the + * constructor because it becomes null when build() is called. + */ + protected abstract MessageType internalGetResult(); + + /** + * Called by subclasses to parse an unknown field. + * @return {@code true} unless the tag is an end-group tag. + */ + protected boolean parseUnknownField( + final CodedInputStream input, + final ExtensionRegistryLite extensionRegistry, + final int tag) throws IOException { + return input.skipField(tag); + } + } + + // ================================================================= + // Extensions-related stuff + + /** + * Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. + */ + public abstract static class ExtendableMessage< + MessageType extends ExtendableMessage> + extends GeneratedMessageLite { + protected ExtendableMessage() {} + private final FieldSet extensions = + FieldSet.newFieldSet(); + + private void verifyExtensionContainingType( + final GeneratedExtension extension) { + if (extension.getContainingTypeDefaultInstance() != + getDefaultInstanceForType()) { + // This can only happen if someone uses unchecked operations. + throw new IllegalArgumentException( + "This extension is for a different message type. Please make " + + "sure that you are not suppressing any generics type warnings."); + } + } + + /** Check if a singular extension is present. */ + public final boolean hasExtension( + final GeneratedExtension extension) { + verifyExtensionContainingType(extension); + return extensions.hasField(extension.descriptor); + } + + /** Get the number of elements in a repeated extension. */ + public final int getExtensionCount( + final GeneratedExtension> extension) { + verifyExtensionContainingType(extension); + return extensions.getRepeatedFieldCount(extension.descriptor); + } + + /** Get the value of an extension. */ + @SuppressWarnings("unchecked") + public final Type getExtension( + final GeneratedExtension extension) { + verifyExtensionContainingType(extension); + final Object value = extensions.getField(extension.descriptor); + if (value == null) { + return extension.defaultValue; + } else { + return (Type) value; + } + } + + /** Get one element of a repeated extension. */ + @SuppressWarnings("unchecked") + public final Type getExtension( + final GeneratedExtension> extension, + final int index) { + verifyExtensionContainingType(extension); + return (Type) extensions.getRepeatedField(extension.descriptor, index); + } + + /** Called by subclasses to check if all extensions are initialized. */ + protected boolean extensionsAreInitialized() { + return extensions.isInitialized(); + } + + /** + * Used by subclasses to serialize extensions. Extension ranges may be + * interleaved with field numbers, but we must write them in canonical + * (sorted by field number) order. ExtensionWriter helps us write + * individual ranges of extensions at once. + */ + protected class ExtensionWriter { + // Imagine how much simpler this code would be if Java iterators had + // a way to get the next element without advancing the iterator. + + private final Iterator> iter = + extensions.iterator(); + private Map.Entry next; + private final boolean messageSetWireFormat; + + private ExtensionWriter(boolean messageSetWireFormat) { + if (iter.hasNext()) { + next = iter.next(); + } + this.messageSetWireFormat = messageSetWireFormat; + } + + public void writeUntil(final int end, final CodedOutputStream output) + throws IOException { + while (next != null && next.getKey().getNumber() < end) { + ExtensionDescriptor extension = next.getKey(); + if (messageSetWireFormat && extension.getLiteJavaType() == + WireFormat.JavaType.MESSAGE && + !extension.isRepeated()) { + output.writeMessageSetExtension(extension.getNumber(), + (MessageLite) next.getValue()); + } else { + FieldSet.writeField(extension, next.getValue(), output); + } + if (iter.hasNext()) { + next = iter.next(); + } else { + next = null; + } + } + } + } + + protected ExtensionWriter newExtensionWriter() { + return new ExtensionWriter(false); + } + protected ExtensionWriter newMessageSetExtensionWriter() { + return new ExtensionWriter(true); + } + + /** Called by subclasses to compute the size of extensions. */ + protected int extensionsSerializedSize() { + return extensions.getSerializedSize(); + } + protected int extensionsSerializedSizeAsMessageSet() { + return extensions.getMessageSetSerializedSize(); + } + } + + /** + * Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}. + */ + @SuppressWarnings("unchecked") + public abstract static class ExtendableBuilder< + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends Builder { + protected ExtendableBuilder() {} + + // This is implemented here only to work around an apparent bug in the + // Java compiler and/or build system. See bug #1898463. The mere presence + // of this dummy clone() implementation makes it go away. + @Override + public BuilderType clone() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + @Override + protected abstract MessageType internalGetResult(); + + /** Check if a singular extension is present. */ + public final boolean hasExtension( + final GeneratedExtension extension) { + return internalGetResult().hasExtension(extension); + } + + /** Get the number of elements in a repeated extension. */ + public final int getExtensionCount( + final GeneratedExtension> extension) { + return internalGetResult().getExtensionCount(extension); + } + + /** Get the value of an extension. */ + public final Type getExtension( + final GeneratedExtension extension) { + return internalGetResult().getExtension(extension); + } + + /** Get one element of a repeated extension. */ + public final Type getExtension( + final GeneratedExtension> extension, + final int index) { + return internalGetResult().getExtension(extension, index); + } + + /** Set the value of an extension. */ + public final BuilderType setExtension( + final GeneratedExtension extension, + final Type value) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + message.extensions.setField(extension.descriptor, value); + return (BuilderType) this; + } + + /** Set the value of one element of a repeated extension. */ + public final BuilderType setExtension( + final GeneratedExtension> extension, + final int index, final Type value) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + message.extensions.setRepeatedField(extension.descriptor, index, value); + return (BuilderType) this; + } + + /** Append a value to a repeated extension. */ + public final BuilderType addExtension( + final GeneratedExtension> extension, + final Type value) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + message.extensions.addRepeatedField(extension.descriptor, value); + return (BuilderType) this; + } + + /** Clear an extension. */ + public final BuilderType clearExtension( + final GeneratedExtension extension) { + final ExtendableMessage message = internalGetResult(); + message.verifyExtensionContainingType(extension); + message.extensions.clearField(extension.descriptor); + return (BuilderType) this; + } + + /** + * Called by subclasses to parse an unknown field or an extension. + * @return {@code true} unless the tag is an end-group tag. + */ + @Override + protected boolean parseUnknownField( + final CodedInputStream input, + final ExtensionRegistryLite extensionRegistry, + final int tag) throws IOException { + final FieldSet extensions = + ((ExtendableMessage) internalGetResult()).extensions; + + final int wireType = WireFormat.getTagWireType(tag); + final int fieldNumber = WireFormat.getTagFieldNumber(tag); + + final GeneratedExtension extension = + extensionRegistry.findLiteExtensionByNumber( + getDefaultInstanceForType(), fieldNumber); + + boolean unknown = false; + boolean packed = false; + if (extension == null) { + unknown = true; // Unknown field. + } else if (wireType == FieldSet.getWireFormatForFieldType( + extension.descriptor.getLiteType(), + false /* isPacked */)) { + packed = false; // Normal, unpacked value. + } else if (extension.descriptor.isRepeated && + extension.descriptor.type.isPackable() && + wireType == FieldSet.getWireFormatForFieldType( + extension.descriptor.getLiteType(), + true /* isPacked */)) { + packed = true; // Packed value. + } else { + unknown = true; // Wrong wire type. + } + + if (unknown) { // Unknown field or wrong wire type. Skip. + return input.skipField(tag); + } + + if (packed) { + final int length = input.readRawVarint32(); + final int limit = input.pushLimit(length); + if (extension.descriptor.getLiteType() == WireFormat.FieldType.ENUM) { + while (input.getBytesUntilLimit() > 0) { + final int rawValue = input.readEnum(); + final Object value = + extension.descriptor.getEnumType().findValueByNumber(rawValue); + if (value == null) { + // If the number isn't recognized as a valid value for this + // enum, drop it (don't even add it to unknownFields). + return true; + } + extensions.addRepeatedField(extension.descriptor, value); + } + } else { + while (input.getBytesUntilLimit() > 0) { + final Object value = + FieldSet.readPrimitiveField(input, + extension.descriptor.getLiteType()); + extensions.addRepeatedField(extension.descriptor, value); + } + } + input.popLimit(limit); + } else { + final Object value; + switch (extension.descriptor.getLiteJavaType()) { + case MESSAGE: { + MessageLite.Builder subBuilder = null; + if (!extension.descriptor.isRepeated()) { + MessageLite existingValue = + (MessageLite) extensions.getField(extension.descriptor); + if (existingValue != null) { + subBuilder = existingValue.toBuilder(); + } + } + if (subBuilder == null) { + subBuilder = extension.messageDefaultInstance.newBuilderForType(); + } + if (extension.descriptor.getLiteType() == + WireFormat.FieldType.GROUP) { + input.readGroup(extension.getNumber(), + subBuilder, extensionRegistry); + } else { + input.readMessage(subBuilder, extensionRegistry); + } + value = subBuilder.build(); + break; + } + case ENUM: + final int rawValue = input.readEnum(); + value = extension.descriptor.getEnumType() + .findValueByNumber(rawValue); + // If the number isn't recognized as a valid value for this enum, + // drop it. + if (value == null) { + return true; + } + break; + default: + value = FieldSet.readPrimitiveField(input, + extension.descriptor.getLiteType()); + break; + } + + if (extension.descriptor.isRepeated()) { + extensions.addRepeatedField(extension.descriptor, value); + } else { + extensions.setField(extension.descriptor, value); + } + } + + return true; + } + + protected final void mergeExtensionFields(final MessageType other) { + ((ExtendableMessage) internalGetResult()).extensions.mergeFrom( + ((ExtendableMessage) other).extensions); + } + } + + // ----------------------------------------------------------------- + + /** For use by generated code only. */ + public static + GeneratedExtension + newGeneratedExtension() { + return new GeneratedExtension(); + } + + private static final class ExtensionDescriptor + implements FieldSet.FieldDescriptorLite< + ExtensionDescriptor> { + private ExtensionDescriptor( + final Internal.EnumLiteMap enumTypeMap, + final int number, + final WireFormat.FieldType type, + final boolean isRepeated, + final boolean isPacked) { + this.enumTypeMap = enumTypeMap; + this.number = number; + this.type = type; + this.isRepeated = isRepeated; + this.isPacked = isPacked; + } + + private final Internal.EnumLiteMap enumTypeMap; + private final int number; + private final WireFormat.FieldType type; + private final boolean isRepeated; + private final boolean isPacked; + + public int getNumber() { + return number; + } + + public WireFormat.FieldType getLiteType() { + return type; + } + + public WireFormat.JavaType getLiteJavaType() { + return type.getJavaType(); + } + + public boolean isRepeated() { + return isRepeated; + } + + public boolean isPacked() { + return isPacked; + } + + public Internal.EnumLiteMap getEnumType() { + return enumTypeMap; + } + + @SuppressWarnings("unchecked") + public MessageLite.Builder internalMergeFrom( + MessageLite.Builder to, MessageLite from) { + return ((Builder) to).mergeFrom((GeneratedMessageLite) from); + } + + public int compareTo(ExtensionDescriptor other) { + return number - other.number; + } + } + + /** + * Lite equivalent to {@link GeneratedMessage.GeneratedExtension}. + * + * Users should ignore the contents of this class and only use objects of + * this type as parameters to extension accessors and ExtensionRegistry.add(). + */ + public static final class GeneratedExtension< + ContainingType extends MessageLite, Type> { + // We can't always initialize a GeneratedExtension when we first construct + // it due to initialization order difficulties (namely, the default + // instances may not have been constructed yet). So, we construct an + // uninitialized GeneratedExtension once, then call internalInit() on it + // later. Generated code will always call internalInit() on all extensions + // as part of the static initialization code, and internalInit() throws an + // exception if called more than once, so this method is useless to users. + private GeneratedExtension() {} + + private void internalInit( + final ContainingType containingTypeDefaultInstance, + final Type defaultValue, + final MessageLite messageDefaultInstance, + final ExtensionDescriptor descriptor) { + this.containingTypeDefaultInstance = containingTypeDefaultInstance; + this.defaultValue = defaultValue; + this.messageDefaultInstance = messageDefaultInstance; + this.descriptor = descriptor; + } + + /** For use by generated code only. */ + public void internalInitSingular( + final ContainingType containingTypeDefaultInstance, + final Type defaultValue, + final MessageLite messageDefaultInstance, + final Internal.EnumLiteMap enumTypeMap, + final int number, + final WireFormat.FieldType type) { + internalInit( + containingTypeDefaultInstance, defaultValue, messageDefaultInstance, + new ExtensionDescriptor(enumTypeMap, number, type, + false /* isRepeated */, false /* isPacked */)); + } + + /** For use by generated code only. */ + @SuppressWarnings("unchecked") + public void internalInitRepeated( + final ContainingType containingTypeDefaultInstance, + final MessageLite messageDefaultInstance, + final Internal.EnumLiteMap enumTypeMap, + final int number, + final WireFormat.FieldType type, + final boolean isPacked) { + internalInit( + containingTypeDefaultInstance, (Type) Collections.emptyList(), + messageDefaultInstance, + new ExtensionDescriptor( + enumTypeMap, number, type, true /* isRepeated */, isPacked)); + } + + private ContainingType containingTypeDefaultInstance; + private Type defaultValue; + private MessageLite messageDefaultInstance; + private ExtensionDescriptor descriptor; + + /** + * Default instance of the type being extended, used to identify that type. + */ + public ContainingType getContainingTypeDefaultInstance() { + return containingTypeDefaultInstance; + } + + /** Get the field number. */ + public int getNumber() { + return descriptor.getNumber(); + } + + /** + * If the extension is an embedded message, this is the default instance of + * that type. + */ + public MessageLite getMessageDefaultInstance() { + return messageDefaultInstance; + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/Internal.java b/DataExtractionOSM/src/com/google/protobuf/Internal.java new file mode 100644 index 0000000000..965465e14b --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/Internal.java @@ -0,0 +1,121 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.UnsupportedEncodingException; + +/** + * The classes contained within are used internally by the Protocol Buffer + * library and generated message implementations. They are public only because + * those generated messages do not reside in the {@code protobuf} package. + * Others should not use this class directly. + * + * @author kenton@google.com (Kenton Varda) + */ +public class Internal { + /** + * Helper called by generated code to construct default values for string + * fields. + *

+ * The protocol compiler does not actually contain a UTF-8 decoder -- it + * just pushes UTF-8-encoded text around without touching it. The one place + * where this presents a problem is when generating Java string literals. + * Unicode characters in the string literal would normally need to be encoded + * using a Unicode escape sequence, which would require decoding them. + * To get around this, protoc instead embeds the UTF-8 bytes into the + * generated code and leaves it to the runtime library to decode them. + *

+ * It gets worse, though. If protoc just generated a byte array, like: + * new byte[] {0x12, 0x34, 0x56, 0x78} + * Java actually generates *code* which allocates an array and then fills + * in each value. This is much less efficient than just embedding the bytes + * directly into the bytecode. To get around this, we need another + * work-around. String literals are embedded directly, so protoc actually + * generates a string literal corresponding to the bytes. The easiest way + * to do this is to use the ISO-8859-1 character set, which corresponds to + * the first 256 characters of the Unicode range. Protoc can then use + * good old CEscape to generate the string. + *

+ * So we have a string literal which represents a set of bytes which + * represents another string. This function -- stringDefaultValue -- + * converts from the generated string to the string we actually want. The + * generated code calls this automatically. + */ + public static String stringDefaultValue(String bytes) { + try { + return new String(bytes.getBytes("ISO-8859-1"), "UTF-8"); + } catch (UnsupportedEncodingException e) { + // This should never happen since all JVMs are required to implement + // both of the above character sets. + throw new IllegalStateException( + "Java VM does not support a standard character set.", e); + } + } + + /** + * Helper called by generated code to construct default values for bytes + * fields. + *

+ * This is a lot like {@link #stringDefaultValue}, but for bytes fields. + * In this case we only need the second of the two hacks -- allowing us to + * embed raw bytes as a string literal with ISO-8859-1 encoding. + */ + public static ByteString bytesDefaultValue(String bytes) { + try { + return ByteString.copyFrom(bytes.getBytes("ISO-8859-1")); + } catch (UnsupportedEncodingException e) { + // This should never happen since all JVMs are required to implement + // ISO-8859-1. + throw new IllegalStateException( + "Java VM does not support a standard character set.", e); + } + } + + /** + * Interface for an enum value or value descriptor, to be used in FieldSet. + * The lite library stores enum values directly in FieldSets but the full + * library stores EnumValueDescriptors in order to better support reflection. + */ + public interface EnumLite { + int getNumber(); + } + + /** + * Interface for an object which maps integers to {@link EnumLite}s. + * {@link Descriptors.EnumDescriptor} implements this interface by mapping + * numbers to {@link Descriptors.EnumValueDescriptor}s. Additionally, + * every generated enum type has a static method internalGetValueMap() which + * returns an implementation of this type that maps numbers to enum values. + */ + public interface EnumLiteMap { + T findValueByNumber(int number); + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/InvalidProtocolBufferException.java b/DataExtractionOSM/src/com/google/protobuf/InvalidProtocolBufferException.java new file mode 100644 index 0000000000..90f7ffbc28 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/InvalidProtocolBufferException.java @@ -0,0 +1,93 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.IOException; + +/** + * Thrown when a protocol message being parsed is invalid in some way, + * e.g. it contains a malformed varint or a negative byte length. + * + * @author kenton@google.com Kenton Varda + */ +public class InvalidProtocolBufferException extends IOException { + private static final long serialVersionUID = -1616151763072450476L; + + public InvalidProtocolBufferException(final String description) { + super(description); + } + + static InvalidProtocolBufferException truncatedMessage() { + return new InvalidProtocolBufferException( + "While parsing a protocol message, the input ended unexpectedly " + + "in the middle of a field. This could mean either than the " + + "input has been truncated or that an embedded message " + + "misreported its own length."); + } + + static InvalidProtocolBufferException negativeSize() { + return new InvalidProtocolBufferException( + "CodedInputStream encountered an embedded string or message " + + "which claimed to have negative size."); + } + + static InvalidProtocolBufferException malformedVarint() { + return new InvalidProtocolBufferException( + "CodedInputStream encountered a malformed varint."); + } + + static InvalidProtocolBufferException invalidTag() { + return new InvalidProtocolBufferException( + "Protocol message contained an invalid tag (zero)."); + } + + static InvalidProtocolBufferException invalidEndTag() { + return new InvalidProtocolBufferException( + "Protocol message end-group tag did not match expected tag."); + } + + static InvalidProtocolBufferException invalidWireType() { + return new InvalidProtocolBufferException( + "Protocol message tag had invalid wire type."); + } + + static InvalidProtocolBufferException recursionLimitExceeded() { + return new InvalidProtocolBufferException( + "Protocol message had too many levels of nesting. May be malicious. " + + "Use CodedInputStream.setRecursionLimit() to increase the depth limit."); + } + + static InvalidProtocolBufferException sizeLimitExceeded() { + return new InvalidProtocolBufferException( + "Protocol message was too large. May be malicious. " + + "Use CodedInputStream.setSizeLimit() to increase the size limit."); + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/Message.java b/DataExtractionOSM/src/com/google/protobuf/Message.java new file mode 100644 index 0000000000..8c29e212cf --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/Message.java @@ -0,0 +1,305 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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. + +// TODO(kenton): Use generics? E.g. Builder, then +// mergeFrom*() could return BuilderType for better type-safety. + +package com.google.protobuf; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + +/** + * Abstract interface implemented by Protocol Message objects. + *

+ * See also {@link MessageLite}, which defines most of the methods that typical + * users care about. {@link Message} adds to it methods that are not available + * in the "lite" runtime. The biggest added features are introspection and + * reflection -- i.e., getting descriptors for the message type and accessing + * the field values dynamically. + * + * @author kenton@google.com Kenton Varda + */ +public interface Message extends MessageLite { + /** + * Get the message's type's descriptor. This differs from the + * {@code getDescriptor()} method of generated message classes in that + * this method is an abstract method of the {@code Message} interface + * whereas {@code getDescriptor()} is a static method of a specific class. + * They return the same thing. + */ + Descriptors.Descriptor getDescriptorForType(); + + // (From MessageLite, re-declared here only for return type covariance.) + Message getDefaultInstanceForType(); + + /** + * Returns a collection of all the fields in this message which are set + * and their corresponding values. A singular ("required" or "optional") + * field is set iff hasField() returns true for that field. A "repeated" + * field is set iff getRepeatedFieldSize() is greater than zero. The + * values are exactly what would be returned by calling + * {@link #getField(Descriptors.FieldDescriptor)} for each field. The map + * is guaranteed to be a sorted map, so iterating over it will return fields + * in order by field number. + */ + Map getAllFields(); + + /** + * Returns true if the given field is set. This is exactly equivalent to + * calling the generated "has" accessor method corresponding to the field. + * @throws IllegalArgumentException The field is a repeated field, or + * {@code field.getContainingType() != getDescriptorForType()}. + */ + boolean hasField(Descriptors.FieldDescriptor field); + + /** + * Obtains the value of the given field, or the default value if it is + * not set. For primitive fields, the boxed primitive value is returned. + * For enum fields, the EnumValueDescriptor for the value is returend. For + * embedded message fields, the sub-message is returned. For repeated + * fields, a java.util.List is returned. + */ + Object getField(Descriptors.FieldDescriptor field); + + /** + * Gets the number of elements of a repeated field. This is exactly + * equivalent to calling the generated "Count" accessor method corresponding + * to the field. + * @throws IllegalArgumentException The field is not a repeated field, or + * {@code field.getContainingType() != getDescriptorForType()}. + */ + int getRepeatedFieldCount(Descriptors.FieldDescriptor field); + + /** + * Gets an element of a repeated field. For primitive fields, the boxed + * primitive value is returned. For enum fields, the EnumValueDescriptor + * for the value is returend. For embedded message fields, the sub-message + * is returned. + * @throws IllegalArgumentException The field is not a repeated field, or + * {@code field.getContainingType() != getDescriptorForType()}. + */ + Object getRepeatedField(Descriptors.FieldDescriptor field, int index); + + /** Get the {@link UnknownFieldSet} for this message. */ + UnknownFieldSet getUnknownFields(); + + // ----------------------------------------------------------------- + // Comparison and hashing + + /** + * Compares the specified object with this message for equality. Returns + * true if the given object is a message of the same type (as + * defined by {@code getDescriptorForType()}) and has identical values for + * all of its fields. + * + * @param other object to be compared for equality with this message + * @return true if the specified object is equal to this message + */ + @Override + boolean equals(Object other); + + /** + * Returns the hash code value for this message. The hash code of a message + * is defined to be getDescriptor().hashCode() ^ map.hashCode(), + * where map is a map of field numbers to field values. + * + * @return the hash code value for this message + * @see Map#hashCode() + */ + @Override + int hashCode(); + + // ----------------------------------------------------------------- + // Convenience methods. + + /** + * Converts the message to a string in protocol buffer text format. This is + * just a trivial wrapper around {@link TextFormat#printToString(Message)}. + */ + @Override + String toString(); + + // ================================================================= + // Builders + + // (From MessageLite, re-declared here only for return type covariance.) + Builder newBuilderForType(); + Builder toBuilder(); + + /** + * Abstract interface implemented by Protocol Message builders. + */ + interface Builder extends MessageLite.Builder { + // (From MessageLite.Builder, re-declared here only for return type + // covariance.) + Builder clear(); + + /** + * Merge {@code other} into the message being built. {@code other} must + * have the exact same type as {@code this} (i.e. + * {@code getDescriptorForType() == other.getDescriptorForType()}). + * + * Merging occurs as follows. For each field:
+ * * For singular primitive fields, if the field is set in {@code other}, + * then {@code other}'s value overwrites the value in this message.
+ * * For singular message fields, if the field is set in {@code other}, + * it is merged into the corresponding sub-message of this message + * using the same merging rules.
+ * * For repeated fields, the elements in {@code other} are concatenated + * with the elements in this message. + * + * This is equivalent to the {@code Message::MergeFrom} method in C++. + */ + Builder mergeFrom(Message other); + + // (From MessageLite.Builder, re-declared here only for return type + // covariance.) + Message build(); + Message buildPartial(); + Builder clone(); + Builder mergeFrom(CodedInputStream input) throws IOException; + Builder mergeFrom(CodedInputStream input, + ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Get the message's type's descriptor. + * See {@link Message#getDescriptorForType()}. + */ + Descriptors.Descriptor getDescriptorForType(); + + // (From MessageLite.Builder, re-declared here only for return type + // covariance.) + Message getDefaultInstanceForType(); + + /** + * Like {@link Message#getAllFields()}. The returned map may or may not + * reflect future changes to the builder. Either way, the returned map is + * itself unmodifiable. + */ + Map getAllFields(); + + /** + * Create a Builder for messages of the appropriate type for the given + * field. Messages built with this can then be passed to setField(), + * setRepeatedField(), or addRepeatedField(). + */ + Builder newBuilderForField(Descriptors.FieldDescriptor field); + + /** Like {@link Message#hasField(Descriptors.FieldDescriptor)} */ + boolean hasField(Descriptors.FieldDescriptor field); + + /** Like {@link Message#getField(Descriptors.FieldDescriptor)} */ + Object getField(Descriptors.FieldDescriptor field); + + /** + * Sets a field to the given value. The value must be of the correct type + * for this field, i.e. the same type that + * {@link Message#getField(Descriptors.FieldDescriptor)} would return. + */ + Builder setField(Descriptors.FieldDescriptor field, Object value); + + /** + * Clears the field. This is exactly equivalent to calling the generated + * "clear" accessor method corresponding to the field. + */ + Builder clearField(Descriptors.FieldDescriptor field); + + /** + * Like {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)} + */ + int getRepeatedFieldCount(Descriptors.FieldDescriptor field); + + /** + * Like {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)} + */ + Object getRepeatedField(Descriptors.FieldDescriptor field, int index); + + /** + * Sets an element of a repeated field to the given value. The value must + * be of the correct type for this field, i.e. the same type that + * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)} would + * return. + * @throws IllegalArgumentException The field is not a repeated field, or + * {@code field.getContainingType() != getDescriptorForType()}. + */ + Builder setRepeatedField(Descriptors.FieldDescriptor field, + int index, Object value); + + /** + * Like {@code setRepeatedField}, but appends the value as a new element. + * @throws IllegalArgumentException The field is not a repeated field, or + * {@code field.getContainingType() != getDescriptorForType()}. + */ + Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value); + + /** Get the {@link UnknownFieldSet} for this message. */ + UnknownFieldSet getUnknownFields(); + + /** Set the {@link UnknownFieldSet} for this message. */ + Builder setUnknownFields(UnknownFieldSet unknownFields); + + /** + * Merge some unknown fields into the {@link UnknownFieldSet} for this + * message. + */ + Builder mergeUnknownFields(UnknownFieldSet unknownFields); + + // --------------------------------------------------------------- + // Convenience methods. + + // (From MessageLite.Builder, re-declared here only for return type + // covariance.) + Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException; + Builder mergeFrom(ByteString data, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException; + Builder mergeFrom(byte[] data, int off, int len) + throws InvalidProtocolBufferException; + Builder mergeFrom(byte[] data, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + Builder mergeFrom(byte[] data, int off, int len, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + Builder mergeFrom(InputStream input) throws IOException; + Builder mergeFrom(InputStream input, + ExtensionRegistryLite extensionRegistry) + throws IOException; + boolean mergeDelimitedFrom(InputStream input) + throws IOException; + boolean mergeDelimitedFrom(InputStream input, + ExtensionRegistryLite extensionRegistry) + throws IOException; + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/MessageLite.java b/DataExtractionOSM/src/com/google/protobuf/MessageLite.java new file mode 100644 index 0000000000..cf7f39e2f5 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/MessageLite.java @@ -0,0 +1,335 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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. + +// TODO(kenton): Use generics? E.g. Builder, then +// mergeFrom*() could return BuilderType for better type-safety. + +package com.google.protobuf; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Abstract interface implemented by Protocol Message objects. + * + *

This interface is implemented by all protocol message objects. Non-lite + * messages additionally implement the Message interface, which is a subclass + * of MessageLite. Use MessageLite instead when you only need the subset of + * features which it supports -- namely, nothing that uses descriptors or + * reflection. You can instruct the protocol compiler to generate classes + * which implement only MessageLite, not the full Message interface, by adding + * the follow line to the .proto file: + *

+ *   option optimize_for = LITE_RUNTIME;
+ * 
+ * + *

This is particularly useful on resource-constrained systems where the + * full protocol buffers runtime library is too big. + * + *

Note that on non-constrained systems (e.g. servers) when you need to link + * in lots of protocol definitions, a better way to reduce total code footprint + * is to use {@code optimize_for = CODE_SIZE}. This will make the generated + * code smaller while still supporting all the same features (at the expense of + * speed). {@code optimize_for = LITE_RUNTIME} is best when you only have a + * small number of message types linked into your binary, in which case the + * size of the protocol buffers runtime itself is the biggest problem. + * + * @author kenton@google.com Kenton Varda + */ +public interface MessageLite { + /** + * Get an instance of the type with all fields set to their default values. + * This may or may not be a singleton. This differs from the + * {@code getDefaultInstance()} method of generated message classes in that + * this method is an abstract method of the {@code MessageLite} interface + * whereas {@code getDefaultInstance()} is a static method of a specific + * class. They return the same thing. + */ + MessageLite getDefaultInstanceForType(); + + /** + * Returns true if all required fields in the message and all embedded + * messages are set, false otherwise. + */ + boolean isInitialized(); + + /** + * Serializes the message and writes it to {@code output}. This does not + * flush or close the stream. + */ + void writeTo(CodedOutputStream output) throws IOException; + + /** + * Get the number of bytes required to encode this message. The result + * is only computed on the first call and memoized after that. + */ + int getSerializedSize(); + + // ----------------------------------------------------------------- + // Convenience methods. + + /** + * Serializes the message to a {@code ByteString} and returns it. This is + * just a trivial wrapper around + * {@link #writeTo(CodedOutputStream)}. + */ + ByteString toByteString(); + + /** + * Serializes the message to a {@code byte} array and returns it. This is + * just a trivial wrapper around + * {@link #writeTo(CodedOutputStream)}. + */ + byte[] toByteArray(); + + /** + * Serializes the message and writes it to {@code output}. This is just a + * trivial wrapper around {@link #writeTo(CodedOutputStream)}. This does + * not flush or close the stream. + *

+ * NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write + * any more data to the stream after the message, you must somehow ensure + * that the parser on the receiving end does not interpret this as being + * part of the protocol message. This can be done e.g. by writing the size + * of the message before the data, then making sure to limit the input to + * that size on the receiving end (e.g. by wrapping the InputStream in one + * which limits the input). Alternatively, just use + * {@link #writeDelimitedTo(OutputStream)}. + */ + void writeTo(OutputStream output) throws IOException; + + /** + * Like {@link #writeTo(OutputStream)}, but writes the size of the message + * as a varint before writing the data. This allows more data to be written + * to the stream after the message without the need to delimit the message + * data yourself. Use {@link Builder#mergeDelimitedFrom(InputStream)} (or + * the static method {@code YourMessageType.parseDelimitedFrom(InputStream)}) + * to parse messages written by this method. + */ + void writeDelimitedTo(OutputStream output) throws IOException; + + // ================================================================= + // Builders + + /** + * Constructs a new builder for a message of the same type as this message. + */ + Builder newBuilderForType(); + + /** + * Constructs a builder initialized with the current message. Use this to + * derive a new message from the current one. + */ + Builder toBuilder(); + + /** + * Abstract interface implemented by Protocol Message builders. + */ + interface Builder extends Cloneable { + /** Resets all fields to their default values. */ + Builder clear(); + + /** + * Construct the final message. Once this is called, the Builder is no + * longer valid, and calling any other method will result in undefined + * behavior and may throw a NullPointerException. If you need to continue + * working with the builder after calling {@code build()}, {@code clone()} + * it first. + * @throws UninitializedMessageException The message is missing one or more + * required fields (i.e. {@link #isInitialized()} returns false). + * Use {@link #buildPartial()} to bypass this check. + */ + MessageLite build(); + + /** + * Like {@link #build()}, but does not throw an exception if the message + * is missing required fields. Instead, a partial message is returned. + * Once this is called, the Builder is no longer valid, and calling any + * will result in undefined behavior and may throw a NullPointerException. + * + * If you need to continue working with the builder after calling + * {@code buildPartial()}, {@code clone()} it first. + */ + MessageLite buildPartial(); + + /** + * Clones the Builder. + * @see Object#clone() + */ + Builder clone(); + + /** + * Returns true if all required fields in the message and all embedded + * messages are set, false otherwise. + */ + boolean isInitialized(); + + /** + * Parses a message of this type from the input and merges it with this + * message, as if using {@link Builder#mergeFrom(MessageLite)}. + * + *

Warning: This does not verify that all required fields are present in + * the input message. If you call {@link #build()} without setting all + * required fields, it will throw an {@link UninitializedMessageException}, + * which is a {@code RuntimeException} and thus might not be caught. There + * are a few good ways to deal with this: + *

    + *
  • Call {@link #isInitialized()} to verify that all required fields + * are set before building. + *
  • Parse the message separately using one of the static + * {@code parseFrom} methods, then use {@link #mergeFrom(MessageLite)} + * to merge it with this one. {@code parseFrom} will throw an + * {@link InvalidProtocolBufferException} (an {@code IOException}) + * if some required fields are missing. + *
  • Use {@code buildPartial()} to build, which ignores missing + * required fields. + *
+ * + *

Note: The caller should call + * {@link CodedInputStream#checkLastTagWas(int)} after calling this to + * verify that the last tag seen was the appropriate end-group tag, + * or zero for EOF. + */ + Builder mergeFrom(CodedInputStream input) throws IOException; + + /** + * Like {@link Builder#mergeFrom(CodedInputStream)}, but also + * parses extensions. The extensions that you want to be able to parse + * must be registered in {@code extensionRegistry}. Extensions not in + * the registry will be treated as unknown fields. + */ + Builder mergeFrom(CodedInputStream input, + ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Get the message's type's default instance. + * See {@link MessageLite#getDefaultInstanceForType()}. + */ + MessageLite getDefaultInstanceForType(); + + // --------------------------------------------------------------- + // Convenience methods. + + /** + * Parse {@code data} as a message of this type and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. + */ + Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException; + + /** + * Parse {@code data} as a message of this type and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}. + */ + Builder mergeFrom(ByteString data, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Parse {@code data} as a message of this type and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. + */ + Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException; + + /** + * Parse {@code data} as a message of this type and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. + */ + Builder mergeFrom(byte[] data, int off, int len) + throws InvalidProtocolBufferException; + + /** + * Parse {@code data} as a message of this type and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}. + */ + Builder mergeFrom(byte[] data, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Parse {@code data} as a message of this type and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}. + */ + Builder mergeFrom(byte[] data, int off, int len, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Parse a message of this type from {@code input} and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. Note that this method always + * reads the entire input (unless it throws an exception). If you + * want it to stop earlier, you will need to wrap your input in some + * wrapper stream that limits reading. Or, use + * {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message + * and {@link #mergeDelimitedFrom(InputStream)} to read it. + *

+ * Despite usually reading the entire input, this does not close the stream. + */ + Builder mergeFrom(InputStream input) throws IOException; + + /** + * Parse a message of this type from {@code input} and merge it with the + * message being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}. + */ + Builder mergeFrom(InputStream input, + ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Like {@link #mergeFrom(InputStream)}, but does not read until EOF. + * Instead, the size of the message (encoded as a varint) is read first, + * then the message data. Use + * {@link MessageLite#writeDelimitedTo(OutputStream)} to write messages in + * this format. + * + * @returns True if successful, or false if the stream is at EOF when the + * method starts. Any other error (including reaching EOF during + * parsing) will cause an exception to be thrown. + */ + boolean mergeDelimitedFrom(InputStream input) + throws IOException; + + /** + * Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions. + */ + boolean mergeDelimitedFrom(InputStream input, + ExtensionRegistryLite extensionRegistry) + throws IOException; + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/ProtocolMessageEnum.java b/DataExtractionOSM/src/com/google/protobuf/ProtocolMessageEnum.java new file mode 100644 index 0000000000..112400f42b --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/ProtocolMessageEnum.java @@ -0,0 +1,58 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.EnumDescriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; + +/** + * Interface of useful methods added to all enums generated by the protocol + * compiler. + */ +public interface ProtocolMessageEnum extends Internal.EnumLite { + + /** + * Return the value's numeric value as defined in the .proto file. + */ + int getNumber(); + + /** + * Return the value's descriptor, which contains information such as + * value name, number, and type. + */ + EnumValueDescriptor getValueDescriptor(); + + /** + * Return the enum type's descriptor, which contains information + * about each defined value, etc. + */ + EnumDescriptor getDescriptorForType(); +} diff --git a/DataExtractionOSM/src/com/google/protobuf/RpcCallback.java b/DataExtractionOSM/src/com/google/protobuf/RpcCallback.java new file mode 100644 index 0000000000..1fd35ed332 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/RpcCallback.java @@ -0,0 +1,47 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + * Interface for an RPC callback, normally called when an RPC completes. + * {@code ParameterType} is normally the method's response message type. + * + *

Starting with version 2.3.0, RPC implementations should not try to build + * on this, but should instead provide code generator plugins which generate + * code specific to the particular RPC implementation. This way the generated + * code can be more appropriate for the implementation in use and can avoid + * unnecessary layers of indirection. + * + * @author kenton@google.com Kenton Varda + */ +public interface RpcCallback { + void run(ParameterType parameter); +} diff --git a/DataExtractionOSM/src/com/google/protobuf/RpcChannel.java b/DataExtractionOSM/src/com/google/protobuf/RpcChannel.java new file mode 100644 index 0000000000..c6ec54fc91 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/RpcChannel.java @@ -0,0 +1,71 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + *

Abstract interface for an RPC channel. An {@code RpcChannel} represents a + * communication line to a {@link Service} which can be used to call that + * {@link Service}'s methods. The {@link Service} may be running on another + * machine. Normally, you should not call an {@code RpcChannel} directly, but + * instead construct a stub {@link Service} wrapping it. Example: + * + *

+ *   RpcChannel channel = rpcImpl.newChannel("remotehost.example.com:1234");
+ *   RpcController controller = rpcImpl.newController();
+ *   MyService service = MyService.newStub(channel);
+ *   service.myMethod(controller, request, callback);
+ * 
+ * + *

Starting with version 2.3.0, RPC implementations should not try to build + * on this, but should instead provide code generator plugins which generate + * code specific to the particular RPC implementation. This way the generated + * code can be more appropriate for the implementation in use and can avoid + * unnecessary layers of indirection. + * + * @author kenton@google.com Kenton Varda + */ +public interface RpcChannel { + /** + * Call the given method of the remote service. This method is similar to + * {@code Service.callMethod()} with one important difference: the caller + * decides the types of the {@code Message} objects, not the callee. The + * request may be of any type as long as + * {@code request.getDescriptor() == method.getInputType()}. + * The response passed to the callback will be of the same type as + * {@code responsePrototype} (which must have + * {@code getDescriptor() == method.getOutputType()}). + */ + void callMethod(Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + Message responsePrototype, + RpcCallback done); +} diff --git a/DataExtractionOSM/src/com/google/protobuf/RpcController.java b/DataExtractionOSM/src/com/google/protobuf/RpcController.java new file mode 100644 index 0000000000..aaa5446da8 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/RpcController.java @@ -0,0 +1,118 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + *

An {@code RpcController} mediates a single method call. The primary + * purpose of the controller is to provide a way to manipulate settings + * specific to the RPC implementation and to find out about RPC-level errors. + * + *

Starting with version 2.3.0, RPC implementations should not try to build + * on this, but should instead provide code generator plugins which generate + * code specific to the particular RPC implementation. This way the generated + * code can be more appropriate for the implementation in use and can avoid + * unnecessary layers of indirection. + * + *

The methods provided by the {@code RpcController} interface are intended + * to be a "least common denominator" set of features which we expect all + * implementations to support. Specific implementations may provide more + * advanced features (e.g. deadline propagation). + * + * @author kenton@google.com Kenton Varda + */ +public interface RpcController { + // ----------------------------------------------------------------- + // These calls may be made from the client side only. Their results + // are undefined on the server side (may throw RuntimeExceptions). + + /** + * Resets the RpcController to its initial state so that it may be reused in + * a new call. This can be called from the client side only. It must not + * be called while an RPC is in progress. + */ + void reset(); + + /** + * After a call has finished, returns true if the call failed. The possible + * reasons for failure depend on the RPC implementation. {@code failed()} + * most only be called on the client side, and must not be called before a + * call has finished. + */ + boolean failed(); + + /** + * If {@code failed()} is {@code true}, returns a human-readable description + * of the error. + */ + String errorText(); + + /** + * Advises the RPC system that the caller desires that the RPC call be + * canceled. The RPC system may cancel it immediately, may wait awhile and + * then cancel it, or may not even cancel the call at all. If the call is + * canceled, the "done" callback will still be called and the RpcController + * will indicate that the call failed at that time. + */ + void startCancel(); + + // ----------------------------------------------------------------- + // These calls may be made from the server side only. Their results + // are undefined on the client side (may throw RuntimeExceptions). + + /** + * Causes {@code failed()} to return true on the client side. {@code reason} + * will be incorporated into the message returned by {@code errorText()}. + * If you find you need to return machine-readable information about + * failures, you should incorporate it into your response protocol buffer + * and should NOT call {@code setFailed()}. + */ + void setFailed(String reason); + + /** + * If {@code true}, indicates that the client canceled the RPC, so the server + * may as well give up on replying to it. This method must be called on the + * server side only. The server should still call the final "done" callback. + */ + boolean isCanceled(); + + /** + * Asks that the given callback be called when the RPC is canceled. The + * parameter passed to the callback will always be {@code null}. The + * callback will always be called exactly once. If the RPC completes without + * being canceled, the callback will be called after completion. If the RPC + * has already been canceled when NotifyOnCancel() is called, the callback + * will be called immediately. + * + *

{@code notifyOnCancel()} must be called no more than once per request. + * It must be called on the server side only. + */ + void notifyOnCancel(RpcCallback callback); +} diff --git a/DataExtractionOSM/src/com/google/protobuf/RpcUtil.java b/DataExtractionOSM/src/com/google/protobuf/RpcUtil.java new file mode 100644 index 0000000000..b1b959a8a0 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/RpcUtil.java @@ -0,0 +1,135 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + * Grab-bag of utility functions useful when dealing with RPCs. + * + * @author kenton@google.com Kenton Varda + */ +public final class RpcUtil { + private RpcUtil() {} + + /** + * Take an {@code RpcCallback} and convert it to an + * {@code RpcCallback} accepting a specific message type. This is always + * type-safe (parameter type contravariance). + */ + @SuppressWarnings("unchecked") + public static RpcCallback + specializeCallback(final RpcCallback originalCallback) { + return (RpcCallback)originalCallback; + // The above cast works, but only due to technical details of the Java + // implementation. A more theoretically correct -- but less efficient -- + // implementation would be as follows: + // return new RpcCallback() { + // public void run(Type parameter) { + // originalCallback.run(parameter); + // } + // }; + } + + /** + * Take an {@code RpcCallback} accepting a specific message type and convert + * it to an {@code RpcCallback}. The generalized callback will + * accept any message object which has the same descriptor, and will convert + * it to the correct class before calling the original callback. However, + * if the generalized callback is given a message with a different descriptor, + * an exception will be thrown. + */ + public static + RpcCallback generalizeCallback( + final RpcCallback originalCallback, + final Class originalClass, + final Type defaultInstance) { + return new RpcCallback() { + public void run(final Message parameter) { + Type typedParameter; + try { + typedParameter = originalClass.cast(parameter); + } catch (ClassCastException ignored) { + typedParameter = copyAsType(defaultInstance, parameter); + } + originalCallback.run(typedParameter); + } + }; + } + + /** + * Creates a new message of type "Type" which is a copy of "source". "source" + * must have the same descriptor but may be a different class (e.g. + * DynamicMessage). + */ + @SuppressWarnings("unchecked") + private static Type copyAsType( + final Type typeDefaultInstance, final Message source) { + return (Type)typeDefaultInstance.newBuilderForType() + .mergeFrom(source) + .build(); + } + + /** + * Creates a callback which can only be called once. This may be useful for + * security, when passing a callback to untrusted code: most callbacks do + * not expect to be called more than once, so doing so may expose bugs if it + * is not prevented. + */ + public static + RpcCallback newOneTimeCallback( + final RpcCallback originalCallback) { + return new RpcCallback() { + private boolean alreadyCalled = false; + + public void run(final ParameterType parameter) { + synchronized(this) { + if (alreadyCalled) { + throw new AlreadyCalledException(); + } + alreadyCalled = true; + } + + originalCallback.run(parameter); + } + }; + } + + /** + * Exception thrown when a one-time callback is called more than once. + */ + public static final class AlreadyCalledException extends RuntimeException { + private static final long serialVersionUID = 5469741279507848266L; + + public AlreadyCalledException() { + super("This RpcCallback was already called and cannot be called " + + "multiple times."); + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/Service.java b/DataExtractionOSM/src/com/google/protobuf/Service.java new file mode 100644 index 0000000000..541585f41f --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/Service.java @@ -0,0 +1,117 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + * Abstract base interface for protocol-buffer-based RPC services. Services + * themselves are abstract classes (implemented either by servers or as + * stubs), but they subclass this base interface. The methods of this + * interface can be used to call the methods of the service without knowing + * its exact type at compile time (analogous to the Message interface). + * + *

Starting with version 2.3.0, RPC implementations should not try to build + * on this, but should instead provide code generator plugins which generate + * code specific to the particular RPC implementation. This way the generated + * code can be more appropriate for the implementation in use and can avoid + * unnecessary layers of indirection. + * + * @author kenton@google.com Kenton Varda + */ +public interface Service { + /** + * Get the {@code ServiceDescriptor} describing this service and its methods. + */ + Descriptors.ServiceDescriptor getDescriptorForType(); + + /** + *

Call a method of the service specified by MethodDescriptor. This is + * normally implemented as a simple {@code switch()} that calls the standard + * definitions of the service's methods. + * + *

Preconditions: + *

    + *
  • {@code method.getService() == getDescriptorForType()} + *
  • {@code request} is of the exact same class as the object returned by + * {@code getRequestPrototype(method)}. + *
  • {@code controller} is of the correct type for the RPC implementation + * being used by this Service. For stubs, the "correct type" depends + * on the RpcChannel which the stub is using. Server-side Service + * implementations are expected to accept whatever type of + * {@code RpcController} the server-side RPC implementation uses. + *
+ * + *

Postconditions: + *

    + *
  • {@code done} will be called when the method is complete. This may be + * before {@code callMethod()} returns or it may be at some point in + * the future. + *
  • The parameter to {@code done} is the response. It must be of the + * exact same type as would be returned by + * {@code getResponsePrototype(method)}. + *
  • If the RPC failed, the parameter to {@code done} will be + * {@code null}. Further details about the failure can be found by + * querying {@code controller}. + *
+ */ + void callMethod(Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + RpcCallback done); + + /** + *

{@code callMethod()} requires that the request passed in is of a + * particular subclass of {@code Message}. {@code getRequestPrototype()} + * gets the default instances of this type for a given method. You can then + * call {@code Message.newBuilderForType()} on this instance to + * construct a builder to build an object which you can then pass to + * {@code callMethod()}. + * + *

Example: + *

+   *   MethodDescriptor method =
+   *     service.getDescriptorForType().findMethodByName("Foo");
+   *   Message request =
+   *     stub.getRequestPrototype(method).newBuilderForType()
+   *         .mergeFrom(input).build();
+   *   service.callMethod(method, request, callback);
+   * 
+ */ + Message getRequestPrototype(Descriptors.MethodDescriptor method); + + /** + * Like {@code getRequestPrototype()}, but gets a prototype of the response + * message. {@code getResponsePrototype()} is generally not needed because + * the {@code Service} implementation constructs the response message itself, + * but it may be useful in some cases to know ahead of time what type of + * object will be returned. + */ + Message getResponsePrototype(Descriptors.MethodDescriptor method); +} diff --git a/DataExtractionOSM/src/com/google/protobuf/ServiceException.java b/DataExtractionOSM/src/com/google/protobuf/ServiceException.java new file mode 100644 index 0000000000..c043a77582 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/ServiceException.java @@ -0,0 +1,44 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + * Thrown by blocking RPC methods when a failure occurs. + * + * @author cpovirk@google.com (Chris Povirk) + */ +public final class ServiceException extends Exception { + private static final long serialVersionUID = -1219262335729891920L; + + public ServiceException(final String message) { + super(message); + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/TextFormat.java b/DataExtractionOSM/src/com/google/protobuf/TextFormat.java new file mode 100644 index 0000000000..bbbdd37547 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/TextFormat.java @@ -0,0 +1,1341 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.EnumDescriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; + +import java.io.IOException; +import java.nio.CharBuffer; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Provide ascii text parsing and formatting support for proto2 instances. + * The implementation largely follows google/protobuf/text_format.cc. + * + * @author wenboz@google.com Wenbo Zhu + * @author kenton@google.com Kenton Varda + */ +public final class TextFormat { + private TextFormat() { + } + + /** + * Outputs a textual representation of the Protocol Message supplied into + * the parameter output. (This representation is the new version of the + * classic "ProtocolPrinter" output from the original Protocol Buffer system) + */ + public static void print(final Message message, final Appendable output) + throws IOException { + final TextGenerator generator = new TextGenerator(output); + print(message, generator); + } + + /** Outputs a textual representation of {@code fields} to {@code output}. */ + public static void print(final UnknownFieldSet fields, + final Appendable output) + throws IOException { + final TextGenerator generator = new TextGenerator(output); + printUnknownFields(fields, generator); + } + + /** + * Like {@code print()}, but writes directly to a {@code String} and + * returns it. + */ + public static String printToString(final Message message) { + try { + final StringBuilder text = new StringBuilder(); + print(message, text); + return text.toString(); + } catch (IOException e) { + throw new RuntimeException( + "Writing to a StringBuilder threw an IOException (should never " + + "happen).", e); + } + } + + /** + * Like {@code print()}, but writes directly to a {@code String} and + * returns it. + */ + public static String printToString(final UnknownFieldSet fields) { + try { + final StringBuilder text = new StringBuilder(); + print(fields, text); + return text.toString(); + } catch (IOException e) { + throw new RuntimeException( + "Writing to a StringBuilder threw an IOException (should never " + + "happen).", e); + } + } + + private static void print(final Message message, + final TextGenerator generator) + throws IOException { + for (final Map.Entry field : + message.getAllFields().entrySet()) { + printField(field.getKey(), field.getValue(), generator); + } + printUnknownFields(message.getUnknownFields(), generator); + } + + public static void printField(final FieldDescriptor field, + final Object value, + final Appendable output) + throws IOException { + final TextGenerator generator = new TextGenerator(output); + printField(field, value, generator); + } + + public static String printFieldToString(final FieldDescriptor field, + final Object value) { + try { + final StringBuilder text = new StringBuilder(); + printField(field, value, text); + return text.toString(); + } catch (IOException e) { + throw new RuntimeException( + "Writing to a StringBuilder threw an IOException (should never " + + "happen).", e); + } + } + + @SuppressWarnings("unchecked") +private static void printField(final FieldDescriptor field, + final Object value, + final TextGenerator generator) + throws IOException { + if (field.isRepeated()) { + // Repeated field. Print each element. + for (final Object element : (List) value) { + printSingleField(field, element, generator); + } + } else { + printSingleField(field, value, generator); + } + } + + private static void printSingleField(final FieldDescriptor field, + final Object value, + final TextGenerator generator) + throws IOException { + if (field.isExtension()) { + generator.print("["); + // We special-case MessageSet elements for compatibility with proto1. + if (field.getContainingType().getOptions().getMessageSetWireFormat() + && (field.getType() == FieldDescriptor.Type.MESSAGE) + && (field.isOptional()) + // object equality + && (field.getExtensionScope() == field.getMessageType())) { + generator.print(field.getMessageType().getFullName()); + } else { + generator.print(field.getFullName()); + } + generator.print("]"); + } else { + if (field.getType() == FieldDescriptor.Type.GROUP) { + // Groups must be serialized with their original capitalization. + generator.print(field.getMessageType().getName()); + } else { + generator.print(field.getName()); + } + } + + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + generator.print(" {\n"); + generator.indent(); + } else { + generator.print(": "); + } + + printFieldValue(field, value, generator); + + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + generator.outdent(); + generator.print("}"); + } + generator.print("\n"); + } + + private static void printFieldValue(final FieldDescriptor field, + final Object value, + final TextGenerator generator) + throws IOException { + switch (field.getType()) { + case INT32: + case INT64: + case SINT32: + case SINT64: + case SFIXED32: + case SFIXED64: + case FLOAT: + case DOUBLE: + case BOOL: + // Good old toString() does what we want for these types. + generator.print(value.toString()); + break; + + case UINT32: + case FIXED32: + generator.print(unsignedToString((Integer) value)); + break; + + case UINT64: + case FIXED64: + generator.print(unsignedToString((Long) value)); + break; + + case STRING: + generator.print("\""); + generator.print(escapeText((String) value)); + generator.print("\""); + break; + + case BYTES: + generator.print("\""); + generator.print(escapeBytes((ByteString) value)); + generator.print("\""); + break; + + case ENUM: + generator.print(((EnumValueDescriptor) value).getName()); + break; + + case MESSAGE: + case GROUP: + print((Message) value, generator); + break; + } + } + + private static void printUnknownFields(final UnknownFieldSet unknownFields, + final TextGenerator generator) + throws IOException { + for (final Map.Entry entry : + unknownFields.asMap().entrySet()) { + @SuppressWarnings("unused") + final String prefix = entry.getKey().toString() + ": "; + final UnknownFieldSet.Field field = entry.getValue(); + + for (final long value : field.getVarintList()) { + generator.print(entry.getKey().toString()); + generator.print(": "); + generator.print(unsignedToString(value)); + generator.print("\n"); + } + for (final int value : field.getFixed32List()) { + generator.print(entry.getKey().toString()); + generator.print(": "); + generator.print(String.format((Locale) null, "0x%08x", value)); + generator.print("\n"); + } + for (final long value : field.getFixed64List()) { + generator.print(entry.getKey().toString()); + generator.print(": "); + generator.print(String.format((Locale) null, "0x%016x", value)); + generator.print("\n"); + } + for (final ByteString value : field.getLengthDelimitedList()) { + generator.print(entry.getKey().toString()); + generator.print(": \""); + generator.print(escapeBytes(value)); + generator.print("\"\n"); + } + for (final UnknownFieldSet value : field.getGroupList()) { + generator.print(entry.getKey().toString()); + generator.print(" {\n"); + generator.indent(); + printUnknownFields(value, generator); + generator.outdent(); + generator.print("}\n"); + } + } + } + + /** Convert an unsigned 32-bit integer to a string. */ + private static String unsignedToString(final int value) { + if (value >= 0) { + return Integer.toString(value); + } else { + return Long.toString(((long) value) & 0x00000000FFFFFFFFL); + } + } + + /** Convert an unsigned 64-bit integer to a string. */ + private static String unsignedToString(final long value) { + if (value >= 0) { + return Long.toString(value); + } else { + // Pull off the most-significant bit so that BigInteger doesn't think + // the number is negative, then set it again using setBit(). + return BigInteger.valueOf(value & 0x7FFFFFFFFFFFFFFFL) + .setBit(63).toString(); + } + } + + /** + * An inner class for writing text to the output stream. + */ + private static final class TextGenerator { + private Appendable output; + private boolean atStartOfLine = true; + private final StringBuilder indent = new StringBuilder(); + + private TextGenerator(final Appendable output) { + this.output = output; + } + + /** + * Indent text by two spaces. After calling Indent(), two spaces will be + * inserted at the beginning of each line of text. Indent() may be called + * multiple times to produce deeper indents. + */ + public void indent() { + indent.append(" "); + } + + /** + * Reduces the current indent level by two spaces, or crashes if the indent + * level is zero. + */ + public void outdent() { + final int length = indent.length(); + if (length == 0) { + throw new IllegalArgumentException( + " Outdent() without matching Indent()."); + } + indent.delete(length - 2, length); + } + + /** + * Print text to the output stream. + */ + public void print(final CharSequence text) throws IOException { + final int size = text.length(); + int pos = 0; + + for (int i = 0; i < size; i++) { + if (text.charAt(i) == '\n') { + write(text.subSequence(pos, size), i - pos + 1); + pos = i + 1; + atStartOfLine = true; + } + } + write(text.subSequence(pos, size), size - pos); + } + + private void write(final CharSequence data, final int size) + throws IOException { + if (size == 0) { + return; + } + if (atStartOfLine) { + atStartOfLine = false; + output.append(indent); + } + output.append(data); + } + } + + // ================================================================= + // Parsing + + /** + * Represents a stream of tokens parsed from a {@code String}. + * + *

The Java standard library provides many classes that you might think + * would be useful for implementing this, but aren't. For example: + * + *

    + *
  • {@code java.io.StreamTokenizer}: This almost does what we want -- or, + * at least, something that would get us close to what we want -- except + * for one fatal flaw: It automatically un-escapes strings using Java + * escape sequences, which do not include all the escape sequences we + * need to support (e.g. '\x'). + *
  • {@code java.util.Scanner}: This seems like a great way at least to + * parse regular expressions out of a stream (so we wouldn't have to load + * the entire input into a single string before parsing). Sadly, + * {@code Scanner} requires that tokens be delimited with some delimiter. + * Thus, although the text "foo:" should parse to two tokens ("foo" and + * ":"), {@code Scanner} would recognize it only as a single token. + * Furthermore, {@code Scanner} provides no way to inspect the contents + * of delimiters, making it impossible to keep track of line and column + * numbers. + *
+ * + *

Luckily, Java's regular expression support does manage to be useful to + * us. (Barely: We need {@code Matcher.usePattern()}, which is new in + * Java 1.5.) So, we can use that, at least. Unfortunately, this implies + * that we need to have the entire input in one contiguous string. + */ + private static final class Tokenizer { + private final CharSequence text; + private final Matcher matcher; + private String currentToken; + + // The character index within this.text at which the current token begins. + private int pos = 0; + + // The line and column numbers of the current token. + private int line = 0; + private int column = 0; + + // The line and column numbers of the previous token (allows throwing + // errors *after* consuming). + private int previousLine = 0; + private int previousColumn = 0; + + // We use possesive quantifiers (*+ and ++) because otherwise the Java + // regex matcher has stack overflows on large inputs. + private static final Pattern WHITESPACE = + Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE); + private static final Pattern TOKEN = Pattern.compile( + "[a-zA-Z_][0-9a-zA-Z_+-]*+|" + // an identifier + "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" + // a number + "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" + // a double-quoted string + "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string + Pattern.MULTILINE); + + private static final Pattern DOUBLE_INFINITY = Pattern.compile( + "-?inf(inity)?", + Pattern.CASE_INSENSITIVE); + private static final Pattern FLOAT_INFINITY = Pattern.compile( + "-?inf(inity)?f?", + Pattern.CASE_INSENSITIVE); + private static final Pattern FLOAT_NAN = Pattern.compile( + "nanf?", + Pattern.CASE_INSENSITIVE); + + /** Construct a tokenizer that parses tokens from the given text. */ + private Tokenizer(final CharSequence text) { + this.text = text; + this.matcher = WHITESPACE.matcher(text); + skipWhitespace(); + nextToken(); + } + + /** Are we at the end of the input? */ + public boolean atEnd() { + return currentToken.length() == 0; + } + + /** Advance to the next token. */ + public void nextToken() { + previousLine = line; + previousColumn = column; + + // Advance the line counter to the current position. + while (pos < matcher.regionStart()) { + if (text.charAt(pos) == '\n') { + ++line; + column = 0; + } else { + ++column; + } + ++pos; + } + + // Match the next token. + if (matcher.regionStart() == matcher.regionEnd()) { + // EOF + currentToken = ""; + } else { + matcher.usePattern(TOKEN); + if (matcher.lookingAt()) { + currentToken = matcher.group(); + matcher.region(matcher.end(), matcher.regionEnd()); + } else { + // Take one character. + currentToken = String.valueOf(text.charAt(pos)); + matcher.region(pos + 1, matcher.regionEnd()); + } + + skipWhitespace(); + } + } + + /** + * Skip over any whitespace so that the matcher region starts at the next + * token. + */ + private void skipWhitespace() { + matcher.usePattern(WHITESPACE); + if (matcher.lookingAt()) { + matcher.region(matcher.end(), matcher.regionEnd()); + } + } + + /** + * If the next token exactly matches {@code token}, consume it and return + * {@code true}. Otherwise, return {@code false} without doing anything. + */ + public boolean tryConsume(final String token) { + if (currentToken.equals(token)) { + nextToken(); + return true; + } else { + return false; + } + } + + /** + * If the next token exactly matches {@code token}, consume it. Otherwise, + * throw a {@link ParseException}. + */ + public void consume(final String token) throws ParseException { + if (!tryConsume(token)) { + throw parseException("Expected \"" + token + "\"."); + } + } + + /** + * Returns {@code true} if the next token is an integer, but does + * not consume it. + */ + public boolean lookingAtInteger() { + if (currentToken.length() == 0) { + return false; + } + + final char c = currentToken.charAt(0); + return ('0' <= c && c <= '9') || + c == '-' || c == '+'; + } + + /** + * If the next token is an identifier, consume it and return its value. + * Otherwise, throw a {@link ParseException}. + */ + public String consumeIdentifier() throws ParseException { + for (int i = 0; i < currentToken.length(); i++) { + final char c = currentToken.charAt(i); + if (('a' <= c && c <= 'z') || + ('A' <= c && c <= 'Z') || + ('0' <= c && c <= '9') || + (c == '_') || (c == '.')) { + // OK + } else { + throw parseException("Expected identifier."); + } + } + + final String result = currentToken; + nextToken(); + return result; + } + + /** + * If the next token is a 32-bit signed integer, consume it and return its + * value. Otherwise, throw a {@link ParseException}. + */ + public int consumeInt32() throws ParseException { + try { + final int result = parseInt32(currentToken); + nextToken(); + return result; + } catch (NumberFormatException e) { + throw integerParseException(e); + } + } + + /** + * If the next token is a 32-bit unsigned integer, consume it and return its + * value. Otherwise, throw a {@link ParseException}. + */ + public int consumeUInt32() throws ParseException { + try { + final int result = parseUInt32(currentToken); + nextToken(); + return result; + } catch (NumberFormatException e) { + throw integerParseException(e); + } + } + + /** + * If the next token is a 64-bit signed integer, consume it and return its + * value. Otherwise, throw a {@link ParseException}. + */ + public long consumeInt64() throws ParseException { + try { + final long result = parseInt64(currentToken); + nextToken(); + return result; + } catch (NumberFormatException e) { + throw integerParseException(e); + } + } + + /** + * If the next token is a 64-bit unsigned integer, consume it and return its + * value. Otherwise, throw a {@link ParseException}. + */ + public long consumeUInt64() throws ParseException { + try { + final long result = parseUInt64(currentToken); + nextToken(); + return result; + } catch (NumberFormatException e) { + throw integerParseException(e); + } + } + + /** + * If the next token is a double, consume it and return its value. + * Otherwise, throw a {@link ParseException}. + */ + public double consumeDouble() throws ParseException { + // We need to parse infinity and nan separately because + // Double.parseDouble() does not accept "inf", "infinity", or "nan". + if (DOUBLE_INFINITY.matcher(currentToken).matches()) { + final boolean negative = currentToken.startsWith("-"); + nextToken(); + return negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; + } + if (currentToken.equalsIgnoreCase("nan")) { + nextToken(); + return Double.NaN; + } + try { + final double result = Double.parseDouble(currentToken); + nextToken(); + return result; + } catch (NumberFormatException e) { + throw floatParseException(e); + } + } + + /** + * If the next token is a float, consume it and return its value. + * Otherwise, throw a {@link ParseException}. + */ + public float consumeFloat() throws ParseException { + // We need to parse infinity and nan separately because + // Float.parseFloat() does not accept "inf", "infinity", or "nan". + if (FLOAT_INFINITY.matcher(currentToken).matches()) { + final boolean negative = currentToken.startsWith("-"); + nextToken(); + return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; + } + if (FLOAT_NAN.matcher(currentToken).matches()) { + nextToken(); + return Float.NaN; + } + try { + final float result = Float.parseFloat(currentToken); + nextToken(); + return result; + } catch (NumberFormatException e) { + throw floatParseException(e); + } + } + + /** + * If the next token is a boolean, consume it and return its value. + * Otherwise, throw a {@link ParseException}. + */ + public boolean consumeBoolean() throws ParseException { + if (currentToken.equals("true")) { + nextToken(); + return true; + } else if (currentToken.equals("false")) { + nextToken(); + return false; + } else { + throw parseException("Expected \"true\" or \"false\"."); + } + } + + /** + * If the next token is a string, consume it and return its (unescaped) + * value. Otherwise, throw a {@link ParseException}. + */ + public String consumeString() throws ParseException { + return consumeByteString().toStringUtf8(); + } + + /** + * If the next token is a string, consume it, unescape it as a + * {@link ByteString}, and return it. Otherwise, throw a + * {@link ParseException}. + */ + public ByteString consumeByteString() throws ParseException { + List list = new ArrayList(); + consumeByteString(list); + while (currentToken.startsWith("'") || currentToken.startsWith("\"")) { + consumeByteString(list); + } + return ByteString.copyFrom(list); + } + + /** + * Like {@link #consumeByteString()} but adds each token of the string to + * the given list. String literals (whether bytes or text) may come in + * multiple adjacent tokens which are automatically concatenated, like in + * C or Python. + */ + private void consumeByteString(List list) throws ParseException { + final char quote = currentToken.length() > 0 ? currentToken.charAt(0) + : '\0'; + if (quote != '\"' && quote != '\'') { + throw parseException("Expected string."); + } + + if (currentToken.length() < 2 || + currentToken.charAt(currentToken.length() - 1) != quote) { + throw parseException("String missing ending quote."); + } + + try { + final String escaped = + currentToken.substring(1, currentToken.length() - 1); + final ByteString result = unescapeBytes(escaped); + nextToken(); + list.add(result); + } catch (InvalidEscapeSequenceException e) { + throw parseException(e.getMessage()); + } + } + + /** + * Returns a {@link ParseException} with the current line and column + * numbers in the description, suitable for throwing. + */ + public ParseException parseException(final String description) { + // Note: People generally prefer one-based line and column numbers. + return new ParseException( + (line + 1) + ":" + (column + 1) + ": " + description); + } + + /** + * Returns a {@link ParseException} with the line and column numbers of + * the previous token in the description, suitable for throwing. + */ + public ParseException parseExceptionPreviousToken( + final String description) { + // Note: People generally prefer one-based line and column numbers. + return new ParseException( + (previousLine + 1) + ":" + (previousColumn + 1) + ": " + description); + } + + /** + * Constructs an appropriate {@link ParseException} for the given + * {@code NumberFormatException} when trying to parse an integer. + */ + private ParseException integerParseException( + final NumberFormatException e) { + return parseException("Couldn't parse integer: " + e.getMessage()); + } + + /** + * Constructs an appropriate {@link ParseException} for the given + * {@code NumberFormatException} when trying to parse a float or double. + */ + private ParseException floatParseException(final NumberFormatException e) { + return parseException("Couldn't parse number: " + e.getMessage()); + } + } + + /** Thrown when parsing an invalid text format message. */ + public static class ParseException extends IOException { + private static final long serialVersionUID = 3196188060225107702L; + + public ParseException(final String message) { + super(message); + } + } + + /** + * Parse a text-format message from {@code input} and merge the contents + * into {@code builder}. + */ + public static void merge(final Readable input, + final Message.Builder builder) + throws IOException { + merge(input, ExtensionRegistry.getEmptyRegistry(), builder); + } + + /** + * Parse a text-format message from {@code input} and merge the contents + * into {@code builder}. + */ + public static void merge(final CharSequence input, + final Message.Builder builder) + throws ParseException { + merge(input, ExtensionRegistry.getEmptyRegistry(), builder); + } + + /** + * Parse a text-format message from {@code input} and merge the contents + * into {@code builder}. Extensions will be recognized if they are + * registered in {@code extensionRegistry}. + */ + public static void merge(final Readable input, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws IOException { + // Read the entire input to a String then parse that. + + // If StreamTokenizer were not quite so crippled, or if there were a kind + // of Reader that could read in chunks that match some particular regex, + // or if we wanted to write a custom Reader to tokenize our stream, then + // we would not have to read to one big String. Alas, none of these is + // the case. Oh well. + + merge(toStringBuilder(input), extensionRegistry, builder); + } + + private static final int BUFFER_SIZE = 4096; + + // TODO(chrisn): See if working around java.io.Reader#read(CharBuffer) + // overhead is worthwhile + private static StringBuilder toStringBuilder(final Readable input) + throws IOException { + final StringBuilder text = new StringBuilder(); + final CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE); + while (true) { + final int n = input.read(buffer); + if (n == -1) { + break; + } + buffer.flip(); + text.append(buffer, 0, n); + } + return text; + } + + /** + * Parse a text-format message from {@code input} and merge the contents + * into {@code builder}. Extensions will be recognized if they are + * registered in {@code extensionRegistry}. + */ + public static void merge(final CharSequence input, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws ParseException { + final Tokenizer tokenizer = new Tokenizer(input); + + while (!tokenizer.atEnd()) { + mergeField(tokenizer, extensionRegistry, builder); + } + } + + /** + * Parse a single field from {@code tokenizer} and merge it into + * {@code builder}. + */ + private static void mergeField(final Tokenizer tokenizer, + final ExtensionRegistry extensionRegistry, + final Message.Builder builder) + throws ParseException { + FieldDescriptor field; + final Descriptor type = builder.getDescriptorForType(); + ExtensionRegistry.ExtensionInfo extension = null; + + if (tokenizer.tryConsume("[")) { + // An extension. + final StringBuilder name = + new StringBuilder(tokenizer.consumeIdentifier()); + while (tokenizer.tryConsume(".")) { + name.append('.'); + name.append(tokenizer.consumeIdentifier()); + } + + extension = extensionRegistry.findExtensionByName(name.toString()); + + if (extension == null) { + throw tokenizer.parseExceptionPreviousToken( + "Extension \"" + name + "\" not found in the ExtensionRegistry."); + } else if (extension.descriptor.getContainingType() != type) { + throw tokenizer.parseExceptionPreviousToken( + "Extension \"" + name + "\" does not extend message type \"" + + type.getFullName() + "\"."); + } + + tokenizer.consume("]"); + + field = extension.descriptor; + } else { + final String name = tokenizer.consumeIdentifier(); + field = type.findFieldByName(name); + + // Group names are expected to be capitalized as they appear in the + // .proto file, which actually matches their type names, not their field + // names. + if (field == null) { + // Explicitly specify US locale so that this code does not break when + // executing in Turkey. + final String lowerName = name.toLowerCase(Locale.US); + field = type.findFieldByName(lowerName); + // If the case-insensitive match worked but the field is NOT a group, + if (field != null && field.getType() != FieldDescriptor.Type.GROUP) { + field = null; + } + } + // Again, special-case group names as described above. + if (field != null && field.getType() == FieldDescriptor.Type.GROUP && + !field.getMessageType().getName().equals(name)) { + field = null; + } + + if (field == null) { + throw tokenizer.parseExceptionPreviousToken( + "Message type \"" + type.getFullName() + + "\" has no field named \"" + name + "\"."); + } + } + + Object value = null; + + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + tokenizer.tryConsume(":"); // optional + + final String endToken; + if (tokenizer.tryConsume("<")) { + endToken = ">"; + } else { + tokenizer.consume("{"); + endToken = "}"; + } + + final Message.Builder subBuilder; + if (extension == null) { + subBuilder = builder.newBuilderForField(field); + } else { + subBuilder = extension.defaultInstance.newBuilderForType(); + } + + while (!tokenizer.tryConsume(endToken)) { + if (tokenizer.atEnd()) { + throw tokenizer.parseException( + "Expected \"" + endToken + "\"."); + } + mergeField(tokenizer, extensionRegistry, subBuilder); + } + + value = subBuilder.build(); + + } else { + tokenizer.consume(":"); + + switch (field.getType()) { + case INT32: + case SINT32: + case SFIXED32: + value = tokenizer.consumeInt32(); + break; + + case INT64: + case SINT64: + case SFIXED64: + value = tokenizer.consumeInt64(); + break; + + case UINT32: + case FIXED32: + value = tokenizer.consumeUInt32(); + break; + + case UINT64: + case FIXED64: + value = tokenizer.consumeUInt64(); + break; + + case FLOAT: + value = tokenizer.consumeFloat(); + break; + + case DOUBLE: + value = tokenizer.consumeDouble(); + break; + + case BOOL: + value = tokenizer.consumeBoolean(); + break; + + case STRING: + value = tokenizer.consumeString(); + break; + + case BYTES: + value = tokenizer.consumeByteString(); + break; + + case ENUM: + final EnumDescriptor enumType = field.getEnumType(); + + if (tokenizer.lookingAtInteger()) { + final int number = tokenizer.consumeInt32(); + value = enumType.findValueByNumber(number); + if (value == null) { + throw tokenizer.parseExceptionPreviousToken( + "Enum type \"" + enumType.getFullName() + + "\" has no value with number " + number + '.'); + } + } else { + final String id = tokenizer.consumeIdentifier(); + value = enumType.findValueByName(id); + if (value == null) { + throw tokenizer.parseExceptionPreviousToken( + "Enum type \"" + enumType.getFullName() + + "\" has no value named \"" + id + "\"."); + } + } + + break; + + case MESSAGE: + case GROUP: + throw new RuntimeException("Can't get here."); + } + } + + if (field.isRepeated()) { + builder.addRepeatedField(field, value); + } else { + builder.setField(field, value); + } + } + + // ================================================================= + // Utility functions + // + // Some of these methods are package-private because Descriptors.java uses + // them. + + /** + * Escapes bytes in the format used in protocol buffer text format, which + * is the same as the format used for C string literals. All bytes + * that are not printable 7-bit ASCII characters are escaped, as well as + * backslash, single-quote, and double-quote characters. Characters for + * which no defined short-hand escape sequence is defined will be escaped + * using 3-digit octal sequences. + */ + static String escapeBytes(final ByteString input) { + final StringBuilder builder = new StringBuilder(input.size()); + for (int i = 0; i < input.size(); i++) { + final byte b = input.byteAt(i); + switch (b) { + // Java does not recognize \a or \v, apparently. + case 0x07: builder.append("\\a" ); break; + case '\b': builder.append("\\b" ); break; + case '\f': builder.append("\\f" ); break; + case '\n': builder.append("\\n" ); break; + case '\r': builder.append("\\r" ); break; + case '\t': builder.append("\\t" ); break; + case 0x0b: builder.append("\\v" ); break; + case '\\': builder.append("\\\\"); break; + case '\'': builder.append("\\\'"); break; + case '"' : builder.append("\\\""); break; + default: + if (b >= 0x20) { + builder.append((char) b); + } else { + builder.append('\\'); + builder.append((char) ('0' + ((b >>> 6) & 3))); + builder.append((char) ('0' + ((b >>> 3) & 7))); + builder.append((char) ('0' + (b & 7))); + } + break; + } + } + return builder.toString(); + } + + /** + * Un-escape a byte sequence as escaped using + * {@link #escapeBytes(ByteString)}. Two-digit hex escapes (starting with + * "\x") are also recognized. + */ + static ByteString unescapeBytes(final CharSequence input) + throws InvalidEscapeSequenceException { + final byte[] result = new byte[input.length()]; + int pos = 0; + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + if (c == '\\') { + if (i + 1 < input.length()) { + ++i; + c = input.charAt(i); + if (isOctal(c)) { + // Octal escape. + int code = digitValue(c); + if (i + 1 < input.length() && isOctal(input.charAt(i + 1))) { + ++i; + code = code * 8 + digitValue(input.charAt(i)); + } + if (i + 1 < input.length() && isOctal(input.charAt(i + 1))) { + ++i; + code = code * 8 + digitValue(input.charAt(i)); + } + result[pos++] = (byte)code; + } else { + switch (c) { + case 'a' : result[pos++] = 0x07; break; + case 'b' : result[pos++] = '\b'; break; + case 'f' : result[pos++] = '\f'; break; + case 'n' : result[pos++] = '\n'; break; + case 'r' : result[pos++] = '\r'; break; + case 't' : result[pos++] = '\t'; break; + case 'v' : result[pos++] = 0x0b; break; + case '\\': result[pos++] = '\\'; break; + case '\'': result[pos++] = '\''; break; + case '"' : result[pos++] = '\"'; break; + + case 'x': + // hex escape + int code = 0; + if (i + 1 < input.length() && isHex(input.charAt(i + 1))) { + ++i; + code = digitValue(input.charAt(i)); + } else { + throw new InvalidEscapeSequenceException( + "Invalid escape sequence: '\\x' with no digits"); + } + if (i + 1 < input.length() && isHex(input.charAt(i + 1))) { + ++i; + code = code * 16 + digitValue(input.charAt(i)); + } + result[pos++] = (byte)code; + break; + + default: + throw new InvalidEscapeSequenceException( + "Invalid escape sequence: '\\" + c + '\''); + } + } + } else { + throw new InvalidEscapeSequenceException( + "Invalid escape sequence: '\\' at end of string."); + } + } else { + result[pos++] = (byte)c; + } + } + + return ByteString.copyFrom(result, 0, pos); + } + + /** + * Thrown by {@link TextFormat#unescapeBytes} and + * {@link TextFormat#unescapeText} when an invalid escape sequence is seen. + */ + static class InvalidEscapeSequenceException extends IOException { + private static final long serialVersionUID = -8164033650142593304L; + + InvalidEscapeSequenceException(final String description) { + super(description); + } + } + + /** + * Like {@link #escapeBytes(ByteString)}, but escapes a text string. + * Non-ASCII characters are first encoded as UTF-8, then each byte is escaped + * individually as a 3-digit octal escape. Yes, it's weird. + */ + static String escapeText(final String input) { + return escapeBytes(ByteString.copyFromUtf8(input)); + } + + /** + * Un-escape a text string as escaped using {@link #escapeText(String)}. + * Two-digit hex escapes (starting with "\x") are also recognized. + */ + static String unescapeText(final String input) + throws InvalidEscapeSequenceException { + return unescapeBytes(input).toStringUtf8(); + } + + /** Is this an octal digit? */ + private static boolean isOctal(final char c) { + return '0' <= c && c <= '7'; + } + + /** Is this a hex digit? */ + private static boolean isHex(final char c) { + return ('0' <= c && c <= '9') || + ('a' <= c && c <= 'f') || + ('A' <= c && c <= 'F'); + } + + /** + * Interpret a character as a digit (in any base up to 36) and return the + * numeric value. This is like {@code Character.digit()} but we don't accept + * non-ASCII digits. + */ + private static int digitValue(final char c) { + if ('0' <= c && c <= '9') { + return c - '0'; + } else if ('a' <= c && c <= 'z') { + return c - 'a' + 10; + } else { + return c - 'A' + 10; + } + } + + /** + * Parse a 32-bit signed integer from the text. Unlike the Java standard + * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" + * and "0" to signify hexidecimal and octal numbers, respectively. + */ + static int parseInt32(final String text) throws NumberFormatException { + return (int) parseInteger(text, true, false); + } + + /** + * Parse a 32-bit unsigned integer from the text. Unlike the Java standard + * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" + * and "0" to signify hexidecimal and octal numbers, respectively. The + * result is coerced to a (signed) {@code int} when returned since Java has + * no unsigned integer type. + */ + static int parseUInt32(final String text) throws NumberFormatException { + return (int) parseInteger(text, false, false); + } + + /** + * Parse a 64-bit signed integer from the text. Unlike the Java standard + * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" + * and "0" to signify hexidecimal and octal numbers, respectively. + */ + static long parseInt64(final String text) throws NumberFormatException { + return parseInteger(text, true, true); + } + + /** + * Parse a 64-bit unsigned integer from the text. Unlike the Java standard + * {@code Integer.parseInt()}, this function recognizes the prefixes "0x" + * and "0" to signify hexidecimal and octal numbers, respectively. The + * result is coerced to a (signed) {@code long} when returned since Java has + * no unsigned long type. + */ + static long parseUInt64(final String text) throws NumberFormatException { + return parseInteger(text, false, true); + } + + private static long parseInteger(final String text, + final boolean isSigned, + final boolean isLong) + throws NumberFormatException { + int pos = 0; + + boolean negative = false; + if (text.startsWith("-", pos)) { + if (!isSigned) { + throw new NumberFormatException("Number must be positive: " + text); + } + ++pos; + negative = true; + } + + int radix = 10; + if (text.startsWith("0x", pos)) { + pos += 2; + radix = 16; + } else if (text.startsWith("0", pos)) { + radix = 8; + } + + final String numberText = text.substring(pos); + + long result = 0; + if (numberText.length() < 16) { + // Can safely assume no overflow. + result = Long.parseLong(numberText, radix); + if (negative) { + result = -result; + } + + // Check bounds. + // No need to check for 64-bit numbers since they'd have to be 16 chars + // or longer to overflow. + if (!isLong) { + if (isSigned) { + if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) { + throw new NumberFormatException( + "Number out of range for 32-bit signed integer: " + text); + } + } else { + if (result >= (1L << 32) || result < 0) { + throw new NumberFormatException( + "Number out of range for 32-bit unsigned integer: " + text); + } + } + } + } else { + BigInteger bigValue = new BigInteger(numberText, radix); + if (negative) { + bigValue = bigValue.negate(); + } + + // Check bounds. + if (!isLong) { + if (isSigned) { + if (bigValue.bitLength() > 31) { + throw new NumberFormatException( + "Number out of range for 32-bit signed integer: " + text); + } + } else { + if (bigValue.bitLength() > 32) { + throw new NumberFormatException( + "Number out of range for 32-bit unsigned integer: " + text); + } + } + } else { + if (isSigned) { + if (bigValue.bitLength() > 63) { + throw new NumberFormatException( + "Number out of range for 64-bit signed integer: " + text); + } + } else { + if (bigValue.bitLength() > 64) { + throw new NumberFormatException( + "Number out of range for 64-bit unsigned integer: " + text); + } + } + } + + result = bigValue.longValue(); + } + + return result; + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/UninitializedMessageException.java b/DataExtractionOSM/src/com/google/protobuf/UninitializedMessageException.java new file mode 100644 index 0000000000..8743c1200a --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/UninitializedMessageException.java @@ -0,0 +1,99 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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.util.Collections; +import java.util.List; + +/** + * Thrown when attempting to build a protocol message that is missing required + * fields. This is a {@code RuntimeException} because it normally represents + * a programming error: it happens when some code which constructs a message + * fails to set all the fields. {@code parseFrom()} methods do not + * throw this; they throw an {@link InvalidProtocolBufferException} if + * required fields are missing, because it is not a programming error to + * receive an incomplete message. In other words, + * {@code UninitializedMessageException} should never be thrown by correct + * code, but {@code InvalidProtocolBufferException} might be. + * + * @author kenton@google.com Kenton Varda + */ +public class UninitializedMessageException extends RuntimeException { + private static final long serialVersionUID = -7466929953374883507L; + + public UninitializedMessageException(final MessageLite message) { + super("Message was missing required fields. (Lite runtime could not " + + "determine which fields were missing)."); + missingFields = null; + } + + public UninitializedMessageException(final List missingFields) { + super(buildDescription(missingFields)); + this.missingFields = missingFields; + } + + private final List missingFields; + + /** + * Get a list of human-readable names of required fields missing from this + * message. Each name is a full path to a field, e.g. "foo.bar[5].baz". + * Returns null if the lite runtime was used, since it lacks the ability to + * find missing fields. + */ + public List getMissingFields() { + return Collections.unmodifiableList(missingFields); + } + + /** + * Converts this exception to an {@link InvalidProtocolBufferException}. + * When a parsed message is missing required fields, this should be thrown + * instead of {@code UninitializedMessageException}. + */ + public InvalidProtocolBufferException asInvalidProtocolBufferException() { + return new InvalidProtocolBufferException(getMessage()); + } + + /** Construct the description string for this exception. */ + private static String buildDescription(final List missingFields) { + final StringBuilder description = + new StringBuilder("Message missing required fields: "); + boolean first = true; + for (final String field : missingFields) { + if (first) { + first = false; + } else { + description.append(", "); + } + description.append(field); + } + return description.toString(); + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/UnknownFieldSet.java b/DataExtractionOSM/src/com/google/protobuf/UnknownFieldSet.java new file mode 100644 index 0000000000..26a15d0087 --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/UnknownFieldSet.java @@ -0,0 +1,953 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * {@code UnknownFieldSet} is used to keep track of fields which were seen when + * parsing a protocol message but whose field numbers or types are unrecognized. + * This most frequently occurs when new fields are added to a message type + * and then messages containing those feilds are read by old software that was + * compiled before the new types were added. + * + *

Every {@link Message} contains an {@code UnknownFieldSet} (and every + * {@link Message.Builder} contains an {@link Builder}). + * + *

Most users will never need to use this class. + * + * @author kenton@google.com Kenton Varda + */ +public final class UnknownFieldSet implements MessageLite { + private UnknownFieldSet() {} + + /** Create a new {@link Builder}. */ + public static Builder newBuilder() { + return Builder.create(); + } + + /** + * Create a new {@link Builder} and initialize it to be a copy + * of {@code copyFrom}. + */ + public static Builder newBuilder(final UnknownFieldSet copyFrom) { + return newBuilder().mergeFrom(copyFrom); + } + + /** Get an empty {@code UnknownFieldSet}. */ + public static UnknownFieldSet getDefaultInstance() { + return defaultInstance; + } + public UnknownFieldSet getDefaultInstanceForType() { + return defaultInstance; + } + private static final UnknownFieldSet defaultInstance = + new UnknownFieldSet(Collections.emptyMap()); + + /** + * Construct an {@code UnknownFieldSet} around the given map. The map is + * expected to be immutable. + */ + private UnknownFieldSet(final Map fields) { + this.fields = fields; + } + private Map fields; + + @Override + public boolean equals(final Object other) { + if (this == other) { + return true; + } + return (other instanceof UnknownFieldSet) && + fields.equals(((UnknownFieldSet) other).fields); + } + + @Override + public int hashCode() { + return fields.hashCode(); + } + + /** Get a map of fields in the set by number. */ + public Map asMap() { + return fields; + } + + /** Check if the given field number is present in the set. */ + public boolean hasField(final int number) { + return fields.containsKey(number); + } + + /** + * Get a field by number. Returns an empty field if not present. Never + * returns {@code null}. + */ + public Field getField(final int number) { + final Field result = fields.get(number); + return (result == null) ? Field.getDefaultInstance() : result; + } + + /** Serializes the set and writes it to {@code output}. */ + public void writeTo(final CodedOutputStream output) throws IOException { + for (final Map.Entry entry : fields.entrySet()) { + entry.getValue().writeTo(entry.getKey(), output); + } + } + + /** + * Converts the set to a string in protocol buffer text format. This is + * just a trivial wrapper around + * {@link TextFormat#printToString(UnknownFieldSet)}. + */ + @Override + public String toString() { + return TextFormat.printToString(this); + } + + /** + * Serializes the message to a {@code ByteString} and returns it. This is + * just a trivial wrapper around {@link #writeTo(CodedOutputStream)}. + */ + public ByteString toByteString() { + try { + final ByteString.CodedBuilder out = + ByteString.newCodedBuilder(getSerializedSize()); + writeTo(out.getCodedOutput()); + return out.build(); + } catch (final IOException e) { + throw new RuntimeException( + "Serializing to a ByteString threw an IOException (should " + + "never happen).", e); + } + } + + /** + * Serializes the message to a {@code byte} array and returns it. This is + * just a trivial wrapper around {@link #writeTo(CodedOutputStream)}. + */ + public byte[] toByteArray() { + try { + final byte[] result = new byte[getSerializedSize()]; + final CodedOutputStream output = CodedOutputStream.newInstance(result); + writeTo(output); + output.checkNoSpaceLeft(); + return result; + } catch (final IOException e) { + throw new RuntimeException( + "Serializing to a byte array threw an IOException " + + "(should never happen).", e); + } + } + + /** + * Serializes the message and writes it to {@code output}. This is just a + * trivial wrapper around {@link #writeTo(CodedOutputStream)}. + */ + public void writeTo(final OutputStream output) throws IOException { + final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output); + writeTo(codedOutput); + codedOutput.flush(); + } + + public void writeDelimitedTo(OutputStream output) throws IOException { + final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output); + codedOutput.writeRawVarint32(getSerializedSize()); + writeTo(codedOutput); + codedOutput.flush(); + } + + /** Get the number of bytes required to encode this set. */ + public int getSerializedSize() { + int result = 0; + for (final Map.Entry entry : fields.entrySet()) { + result += entry.getValue().getSerializedSize(entry.getKey()); + } + return result; + } + + /** + * Serializes the set and writes it to {@code output} using + * {@code MessageSet} wire format. + */ + public void writeAsMessageSetTo(final CodedOutputStream output) + throws IOException { + for (final Map.Entry entry : fields.entrySet()) { + entry.getValue().writeAsMessageSetExtensionTo( + entry.getKey(), output); + } + } + + /** + * Get the number of bytes required to encode this set using + * {@code MessageSet} wire format. + */ + public int getSerializedSizeAsMessageSet() { + int result = 0; + for (final Map.Entry entry : fields.entrySet()) { + result += entry.getValue().getSerializedSizeAsMessageSetExtension( + entry.getKey()); + } + return result; + } + + public boolean isInitialized() { + // UnknownFieldSets do not have required fields, so they are always + // initialized. + return true; + } + + /** Parse an {@code UnknownFieldSet} from the given input stream. */ + public static UnknownFieldSet parseFrom(final CodedInputStream input) + throws IOException { + return newBuilder().mergeFrom(input).build(); + } + + /** Parse {@code data} as an {@code UnknownFieldSet} and return it. */ + public static UnknownFieldSet parseFrom(final ByteString data) + throws InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).build(); + } + + /** Parse {@code data} as an {@code UnknownFieldSet} and return it. */ + public static UnknownFieldSet parseFrom(final byte[] data) + throws InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).build(); + } + + /** Parse an {@code UnknownFieldSet} from {@code input} and return it. */ + public static UnknownFieldSet parseFrom(final InputStream input) + throws IOException { + return newBuilder().mergeFrom(input).build(); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public Builder toBuilder() { + return newBuilder().mergeFrom(this); + } + + /** + * Builder for {@link UnknownFieldSet}s. + * + *

Note that this class maintains {@link Field.Builder}s for all fields + * in the set. Thus, adding one element to an existing {@link Field} does not + * require making a copy. This is important for efficient parsing of + * unknown repeated fields. However, it implies that {@link Field}s cannot + * be constructed independently, nor can two {@link UnknownFieldSet}s share + * the same {@code Field} object. + * + *

Use {@link UnknownFieldSet#newBuilder()} to construct a {@code Builder}. + */ + public static final class Builder implements MessageLite.Builder { + // This constructor should never be called directly (except from 'create'). + private Builder() {} + + private Map fields; + + // Optimization: We keep around a builder for the last field that was + // modified so that we can efficiently add to it multiple times in a + // row (important when parsing an unknown repeated field). + private int lastFieldNumber; + private Field.Builder lastField; + + private static Builder create() { + Builder builder = new Builder(); + builder.reinitialize(); + return builder; + } + + /** + * Get a field builder for the given field number which includes any + * values that already exist. + */ + private Field.Builder getFieldBuilder(final int number) { + if (lastField != null) { + if (number == lastFieldNumber) { + return lastField; + } + // Note: addField() will reset lastField and lastFieldNumber. + addField(lastFieldNumber, lastField.build()); + } + if (number == 0) { + return null; + } else { + final Field existing = fields.get(number); + lastFieldNumber = number; + lastField = Field.newBuilder(); + if (existing != null) { + lastField.mergeFrom(existing); + } + return lastField; + } + } + + /** + * Build the {@link UnknownFieldSet} and return it. + * + *

Once {@code build()} has been called, the {@code Builder} will no + * longer be usable. Calling any method after {@code build()} will result + * in undefined behavior and can cause a {@code NullPointerException} to be + * thrown. + */ + public UnknownFieldSet build() { + getFieldBuilder(0); // Force lastField to be built. + final UnknownFieldSet result; + if (fields.isEmpty()) { + result = getDefaultInstance(); + } else { + result = new UnknownFieldSet(Collections.unmodifiableMap(fields)); + } + fields = null; + return result; + } + + public UnknownFieldSet buildPartial() { + // No required fields, so this is the same as build(). + return build(); + } + + @Override + public Builder clone() { + getFieldBuilder(0); // Force lastField to be built. + return UnknownFieldSet.newBuilder().mergeFrom( + new UnknownFieldSet(fields)); + } + + public UnknownFieldSet getDefaultInstanceForType() { + return UnknownFieldSet.getDefaultInstance(); + } + + private void reinitialize() { + fields = Collections.emptyMap(); + lastFieldNumber = 0; + lastField = null; + } + + /** Reset the builder to an empty set. */ + public Builder clear() { + reinitialize(); + return this; + } + + /** + * Merge the fields from {@code other} into this set. If a field number + * exists in both sets, {@code other}'s values for that field will be + * appended to the values in this set. + */ + public Builder mergeFrom(final UnknownFieldSet other) { + if (other != getDefaultInstance()) { + for (final Map.Entry entry : other.fields.entrySet()) { + mergeField(entry.getKey(), entry.getValue()); + } + } + return this; + } + + /** + * Add a field to the {@code UnknownFieldSet}. If a field with the same + * number already exists, the two are merged. + */ + public Builder mergeField(final int number, final Field field) { + if (number == 0) { + throw new IllegalArgumentException("Zero is not a valid field number."); + } + if (hasField(number)) { + getFieldBuilder(number).mergeFrom(field); + } else { + // Optimization: We could call getFieldBuilder(number).mergeFrom(field) + // in this case, but that would create a copy of the Field object. + // We'd rather reuse the one passed to us, so call addField() instead. + addField(number, field); + } + return this; + } + + /** + * Convenience method for merging a new field containing a single varint + * value. This is used in particular when an unknown enum value is + * encountered. + */ + public Builder mergeVarintField(final int number, final int value) { + if (number == 0) { + throw new IllegalArgumentException("Zero is not a valid field number."); + } + getFieldBuilder(number).addVarint(value); + return this; + } + + /** Check if the given field number is present in the set. */ + public boolean hasField(final int number) { + if (number == 0) { + throw new IllegalArgumentException("Zero is not a valid field number."); + } + return number == lastFieldNumber || fields.containsKey(number); + } + + /** + * Add a field to the {@code UnknownFieldSet}. If a field with the same + * number already exists, it is removed. + */ + public Builder addField(final int number, final Field field) { + if (number == 0) { + throw new IllegalArgumentException("Zero is not a valid field number."); + } + if (lastField != null && lastFieldNumber == number) { + // Discard this. + lastField = null; + lastFieldNumber = 0; + } + if (fields.isEmpty()) { + fields = new TreeMap(); + } + fields.put(number, field); + return this; + } + + /** + * Get all present {@code Field}s as an immutable {@code Map}. If more + * fields are added, the changes may or may not be reflected in this map. + */ + public Map asMap() { + getFieldBuilder(0); // Force lastField to be built. + return Collections.unmodifiableMap(fields); + } + + /** + * Parse an entire message from {@code input} and merge its fields into + * this set. + */ + public Builder mergeFrom(final CodedInputStream input) throws IOException { + while (true) { + final int tag = input.readTag(); + if (tag == 0 || !mergeFieldFrom(tag, input)) { + break; + } + } + return this; + } + + /** + * Parse a single field from {@code input} and merge it into this set. + * @param tag The field's tag number, which was already parsed. + * @return {@code false} if the tag is an engroup tag. + */ + public boolean mergeFieldFrom(final int tag, final CodedInputStream input) + throws IOException { + final int number = WireFormat.getTagFieldNumber(tag); + switch (WireFormat.getTagWireType(tag)) { + case WireFormat.WIRETYPE_VARINT: + getFieldBuilder(number).addVarint(input.readInt64()); + return true; + case WireFormat.WIRETYPE_FIXED64: + getFieldBuilder(number).addFixed64(input.readFixed64()); + return true; + case WireFormat.WIRETYPE_LENGTH_DELIMITED: + getFieldBuilder(number).addLengthDelimited(input.readBytes()); + return true; + case WireFormat.WIRETYPE_START_GROUP: + final Builder subBuilder = newBuilder(); + input.readGroup(number, subBuilder, + ExtensionRegistry.getEmptyRegistry()); + getFieldBuilder(number).addGroup(subBuilder.build()); + return true; + case WireFormat.WIRETYPE_END_GROUP: + return false; + case WireFormat.WIRETYPE_FIXED32: + getFieldBuilder(number).addFixed32(input.readFixed32()); + return true; + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + /** + * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the + * set being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. + */ + public Builder mergeFrom(final ByteString data) + throws InvalidProtocolBufferException { + try { + final CodedInputStream input = data.newCodedInput(); + mergeFrom(input); + input.checkLastTagWas(0); + return this; + } catch (final InvalidProtocolBufferException e) { + throw e; + } catch (final IOException e) { + throw new RuntimeException( + "Reading from a ByteString threw an IOException (should " + + "never happen).", e); + } + } + + /** + * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the + * set being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. + */ + public Builder mergeFrom(final byte[] data) + throws InvalidProtocolBufferException { + try { + final CodedInputStream input = CodedInputStream.newInstance(data); + mergeFrom(input); + input.checkLastTagWas(0); + return this; + } catch (final InvalidProtocolBufferException e) { + throw e; + } catch (final IOException e) { + throw new RuntimeException( + "Reading from a byte array threw an IOException (should " + + "never happen).", e); + } + } + + /** + * Parse an {@code UnknownFieldSet} from {@code input} and merge it with the + * set being built. This is just a small wrapper around + * {@link #mergeFrom(CodedInputStream)}. + */ + public Builder mergeFrom(final InputStream input) throws IOException { + final CodedInputStream codedInput = CodedInputStream.newInstance(input); + mergeFrom(codedInput); + codedInput.checkLastTagWas(0); + return this; + } + + public boolean mergeDelimitedFrom(InputStream input) + 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); + return true; + } + + public boolean mergeDelimitedFrom( + InputStream input, + ExtensionRegistryLite extensionRegistry) throws IOException { + // UnknownFieldSet has no extensions. + return mergeDelimitedFrom(input); + } + + public Builder mergeFrom( + CodedInputStream input, + ExtensionRegistryLite extensionRegistry) throws IOException { + // UnknownFieldSet has no extensions. + return mergeFrom(input); + } + + public Builder mergeFrom( + ByteString data, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + // UnknownFieldSet has no extensions. + return mergeFrom(data); + } + + public Builder mergeFrom(byte[] data, int off, int len) + throws InvalidProtocolBufferException { + try { + final CodedInputStream input = + CodedInputStream.newInstance(data, off, len); + mergeFrom(input); + input.checkLastTagWas(0); + return this; + } catch (InvalidProtocolBufferException e) { + throw e; + } catch (IOException e) { + throw new RuntimeException( + "Reading from a byte array threw an IOException (should " + + "never happen).", e); + } + } + + public Builder mergeFrom( + byte[] data, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + // UnknownFieldSet has no extensions. + return mergeFrom(data); + } + + public Builder mergeFrom( + byte[] data, int off, int len, + ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + // UnknownFieldSet has no extensions. + return mergeFrom(data, off, len); + } + + public Builder mergeFrom( + InputStream input, + ExtensionRegistryLite extensionRegistry) throws IOException { + // UnknownFieldSet has no extensions. + return mergeFrom(input); + } + + public boolean isInitialized() { + // UnknownFieldSets do not have required fields, so they are always + // initialized. + return true; + } + } + + /** + * Represents a single field in an {@code UnknownFieldSet}. + * + *

A {@code Field} consists of five lists of values. The lists correspond + * to the five "wire types" used in the protocol buffer binary format. + * The wire type of each field can be determined from the encoded form alone, + * without knowing the field's declared type. So, we are able to parse + * unknown values at least this far and separate them. Normally, only one + * of the five lists will contain any values, since it is impossible to + * define a valid message type that declares two different types for the + * same field number. However, the code is designed to allow for the case + * where the same unknown field number is encountered using multiple different + * wire types. + * + *

{@code Field} is an immutable class. To construct one, you must use a + * {@link Builder}. + * + * @see UnknownFieldSet + */ + public static final class Field { + private Field() {} + + /** Construct a new {@link Builder}. */ + public static Builder newBuilder() { + return Builder.create(); + } + + /** + * Construct a new {@link Builder} and initialize it to a copy of + * {@code copyFrom}. + */ + public static Builder newBuilder(final Field copyFrom) { + return newBuilder().mergeFrom(copyFrom); + } + + /** Get an empty {@code Field}. */ + public static Field getDefaultInstance() { + return fieldDefaultInstance; + } + private static final Field fieldDefaultInstance = newBuilder().build(); + + /** Get the list of varint values for this field. */ + public List getVarintList() { return varint; } + + /** Get the list of fixed32 values for this field. */ + public List getFixed32List() { return fixed32; } + + /** Get the list of fixed64 values for this field. */ + public List getFixed64List() { return fixed64; } + + /** Get the list of length-delimited values for this field. */ + public List getLengthDelimitedList() { return lengthDelimited; } + + /** + * Get the list of embedded group values for this field. These are + * represented using {@link UnknownFieldSet}s rather than {@link Message}s + * since the group's type is presumably unknown. + */ + public List getGroupList() { return group; } + + @Override + public boolean equals(final Object other) { + if (this == other) { + return true; + } + if (!(other instanceof Field)) { + return false; + } + return Arrays.equals(getIdentityArray(), + ((Field) other).getIdentityArray()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(getIdentityArray()); + } + + /** + * Returns the array of objects to be used to uniquely identify this + * {@link Field} instance. + */ + private Object[] getIdentityArray() { + return new Object[] { + varint, + fixed32, + fixed64, + lengthDelimited, + group}; + } + + /** + * Serializes the field, including field number, and writes it to + * {@code output}. + */ + public void writeTo(final int fieldNumber, final CodedOutputStream output) + throws IOException { + for (final long value : varint) { + output.writeUInt64(fieldNumber, value); + } + for (final int value : fixed32) { + output.writeFixed32(fieldNumber, value); + } + for (final long value : fixed64) { + output.writeFixed64(fieldNumber, value); + } + for (final ByteString value : lengthDelimited) { + output.writeBytes(fieldNumber, value); + } + for (final UnknownFieldSet value : group) { + output.writeGroup(fieldNumber, value); + } + } + + /** + * Get the number of bytes required to encode this field, including field + * number. + */ + public int getSerializedSize(final int fieldNumber) { + int result = 0; + for (final long value : varint) { + result += CodedOutputStream.computeUInt64Size(fieldNumber, value); + } + for (final int value : fixed32) { + result += CodedOutputStream.computeFixed32Size(fieldNumber, value); + } + for (final long value : fixed64) { + result += CodedOutputStream.computeFixed64Size(fieldNumber, value); + } + for (final ByteString value : lengthDelimited) { + result += CodedOutputStream.computeBytesSize(fieldNumber, value); + } + for (final UnknownFieldSet value : group) { + result += CodedOutputStream.computeGroupSize(fieldNumber, value); + } + return result; + } + + /** + * Serializes the field, including field number, and writes it to + * {@code output}, using {@code MessageSet} wire format. + */ + public void writeAsMessageSetExtensionTo( + final int fieldNumber, + final CodedOutputStream output) + throws IOException { + for (final ByteString value : lengthDelimited) { + output.writeRawMessageSetExtension(fieldNumber, value); + } + } + + /** + * Get the number of bytes required to encode this field, including field + * number, using {@code MessageSet} wire format. + */ + public int getSerializedSizeAsMessageSetExtension(final int fieldNumber) { + int result = 0; + for (final ByteString value : lengthDelimited) { + result += CodedOutputStream.computeRawMessageSetExtensionSize( + fieldNumber, value); + } + return result; + } + + private List varint; + private List fixed32; + private List fixed64; + private List lengthDelimited; + private List group; + + /** + * Used to build a {@link Field} within an {@link UnknownFieldSet}. + * + *

Use {@link Field#newBuilder()} to construct a {@code Builder}. + */ + public static final class Builder { + // This constructor should never be called directly (except from 'create'). + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new Field(); + return builder; + } + + private Field result; + + /** + * Build the field. After {@code build()} has been called, the + * {@code Builder} is no longer usable. Calling any other method will + * result in undefined behavior and can cause a + * {@code NullPointerException} to be thrown. + */ + public Field build() { + if (result.varint == null) { + result.varint = Collections.emptyList(); + } else { + result.varint = Collections.unmodifiableList(result.varint); + } + if (result.fixed32 == null) { + result.fixed32 = Collections.emptyList(); + } else { + result.fixed32 = Collections.unmodifiableList(result.fixed32); + } + if (result.fixed64 == null) { + result.fixed64 = Collections.emptyList(); + } else { + result.fixed64 = Collections.unmodifiableList(result.fixed64); + } + if (result.lengthDelimited == null) { + result.lengthDelimited = Collections.emptyList(); + } else { + result.lengthDelimited = + Collections.unmodifiableList(result.lengthDelimited); + } + if (result.group == null) { + result.group = Collections.emptyList(); + } else { + result.group = Collections.unmodifiableList(result.group); + } + + final Field returnMe = result; + result = null; + return returnMe; + } + + /** Discard the field's contents. */ + public Builder clear() { + result = new Field(); + return this; + } + + /** + * Merge the values in {@code other} into this field. For each list + * of values, {@code other}'s values are append to the ones in this + * field. + */ + public Builder mergeFrom(final Field other) { + if (!other.varint.isEmpty()) { + if (result.varint == null) { + result.varint = new ArrayList(); + } + result.varint.addAll(other.varint); + } + if (!other.fixed32.isEmpty()) { + if (result.fixed32 == null) { + result.fixed32 = new ArrayList(); + } + result.fixed32.addAll(other.fixed32); + } + if (!other.fixed64.isEmpty()) { + if (result.fixed64 == null) { + result.fixed64 = new ArrayList(); + } + result.fixed64.addAll(other.fixed64); + } + if (!other.lengthDelimited.isEmpty()) { + if (result.lengthDelimited == null) { + result.lengthDelimited = new ArrayList(); + } + result.lengthDelimited.addAll(other.lengthDelimited); + } + if (!other.group.isEmpty()) { + if (result.group == null) { + result.group = new ArrayList(); + } + result.group.addAll(other.group); + } + return this; + } + + /** Add a varint value. */ + public Builder addVarint(final long value) { + if (result.varint == null) { + result.varint = new ArrayList(); + } + result.varint.add(value); + return this; + } + + /** Add a fixed32 value. */ + public Builder addFixed32(final int value) { + if (result.fixed32 == null) { + result.fixed32 = new ArrayList(); + } + result.fixed32.add(value); + return this; + } + + /** Add a fixed64 value. */ + public Builder addFixed64(final long value) { + if (result.fixed64 == null) { + result.fixed64 = new ArrayList(); + } + result.fixed64.add(value); + return this; + } + + /** Add a length-delimited value. */ + public Builder addLengthDelimited(final ByteString value) { + if (result.lengthDelimited == null) { + result.lengthDelimited = new ArrayList(); + } + result.lengthDelimited.add(value); + return this; + } + + /** Add an embedded group. */ + public Builder addGroup(final UnknownFieldSet value) { + if (result.group == null) { + result.group = new ArrayList(); + } + result.group.add(value); + return this; + } + } + } +} diff --git a/DataExtractionOSM/src/com/google/protobuf/WireFormat.java b/DataExtractionOSM/src/com/google/protobuf/WireFormat.java new file mode 100644 index 0000000000..c46f7b0a6c --- /dev/null +++ b/DataExtractionOSM/src/com/google/protobuf/WireFormat.java @@ -0,0 +1,163 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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; + +/** + * This class is used internally by the Protocol Buffer library and generated + * message implementations. It is public only because those generated messages + * do not reside in the {@code protobuf} package. Others should not use this + * class directly. + * + * This class contains constants and helper functions useful for dealing with + * the Protocol Buffer wire format. + * + * @author kenton@google.com Kenton Varda + */ +public final class WireFormat { + // Do not allow instantiation. + private WireFormat() {} + + static final int WIRETYPE_VARINT = 0; + static final int WIRETYPE_FIXED64 = 1; + static final int WIRETYPE_LENGTH_DELIMITED = 2; + static final int WIRETYPE_START_GROUP = 3; + static final int WIRETYPE_END_GROUP = 4; + static final int WIRETYPE_FIXED32 = 5; + + static final int TAG_TYPE_BITS = 3; + static final int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1; + + /** Given a tag value, determines the wire type (the lower 3 bits). */ + static int getTagWireType(final int tag) { + return tag & TAG_TYPE_MASK; + } + + /** Given a tag value, determines the field number (the upper 29 bits). */ + public static int getTagFieldNumber(final int tag) { + return tag >>> TAG_TYPE_BITS; + } + + /** Makes a tag value given a field number and wire type. */ + static int makeTag(final int fieldNumber, final int wireType) { + return (fieldNumber << TAG_TYPE_BITS) | wireType; + } + + /** + * Lite equivalent to {@link Descriptors.FieldDescriptor.JavaType}. This is + * only here to support the lite runtime and should not be used by users. + */ + public enum JavaType { + INT(0), + LONG(0L), + FLOAT(0F), + DOUBLE(0D), + BOOLEAN(false), + STRING(""), + BYTE_STRING(ByteString.EMPTY), + ENUM(null), + MESSAGE(null); + + JavaType(final Object defaultDefault) { + this.defaultDefault = defaultDefault; + } + + /** + * The default default value for fields of this type, if it's a primitive + * type. + */ + Object getDefaultDefault() { + return defaultDefault; + } + + private final Object defaultDefault; + } + + /** + * Lite equivalent to {@link Descriptors.FieldDescriptor.Type}. This is + * only here to support the lite runtime and should not be used by users. + */ + public enum FieldType { + DOUBLE (JavaType.DOUBLE , WIRETYPE_FIXED64 ), + FLOAT (JavaType.FLOAT , WIRETYPE_FIXED32 ), + INT64 (JavaType.LONG , WIRETYPE_VARINT ), + UINT64 (JavaType.LONG , WIRETYPE_VARINT ), + INT32 (JavaType.INT , WIRETYPE_VARINT ), + FIXED64 (JavaType.LONG , WIRETYPE_FIXED64 ), + FIXED32 (JavaType.INT , WIRETYPE_FIXED32 ), + BOOL (JavaType.BOOLEAN , WIRETYPE_VARINT ), + STRING (JavaType.STRING , WIRETYPE_LENGTH_DELIMITED) { + public boolean isPackable() { return false; } + }, + GROUP (JavaType.MESSAGE , WIRETYPE_START_GROUP ) { + public boolean isPackable() { return false; } + }, + MESSAGE (JavaType.MESSAGE , WIRETYPE_LENGTH_DELIMITED) { + public boolean isPackable() { return false; } + }, + BYTES (JavaType.BYTE_STRING, WIRETYPE_LENGTH_DELIMITED) { + public boolean isPackable() { return false; } + }, + UINT32 (JavaType.INT , WIRETYPE_VARINT ), + ENUM (JavaType.ENUM , WIRETYPE_VARINT ), + SFIXED32(JavaType.INT , WIRETYPE_FIXED32 ), + SFIXED64(JavaType.LONG , WIRETYPE_FIXED64 ), + SINT32 (JavaType.INT , WIRETYPE_VARINT ), + SINT64 (JavaType.LONG , WIRETYPE_VARINT ); + + FieldType(final JavaType javaType, final int wireType) { + this.javaType = javaType; + this.wireType = wireType; + } + + private final JavaType javaType; + private final int wireType; + + public JavaType getJavaType() { return javaType; } + public int getWireType() { return wireType; } + + public boolean isPackable() { return true; } + } + + // Field numbers for feilds in MessageSet wire format. + static final int MESSAGE_SET_ITEM = 1; + static final int MESSAGE_SET_TYPE_ID = 2; + static final int MESSAGE_SET_MESSAGE = 3; + + // Tag numbers. + static final int MESSAGE_SET_ITEM_TAG = + makeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP); + static final int MESSAGE_SET_ITEM_END_TAG = + makeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP); + static final int MESSAGE_SET_TYPE_ID_TAG = + makeTag(MESSAGE_SET_TYPE_ID, WIRETYPE_VARINT); + static final int MESSAGE_SET_MESSAGE_TAG = + makeTag(MESSAGE_SET_MESSAGE, WIRETYPE_LENGTH_DELIMITED); +} diff --git a/DataExtractionOSM/src/crosby/binary/BinaryParser.java b/DataExtractionOSM/src/crosby/binary/BinaryParser.java new file mode 100644 index 0000000000..9da9469c15 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/BinaryParser.java @@ -0,0 +1,122 @@ +package crosby.binary; + + +import java.util.Date; +import java.util.List; + +import com.google.protobuf.InvalidProtocolBufferException; + +import crosby.binary.Osmformat; +import crosby.binary.file.BlockReaderAdapter; +import crosby.binary.file.FileBlock; +import crosby.binary.file.FileBlockPosition; + +public abstract class BinaryParser implements BlockReaderAdapter { + protected int granularity; + private long lat_offset; + private long lon_offset; + protected int date_granularity; + private String strings[]; + + /** Take a Info protocol buffer containing a date and convert it into a java Date object */ + protected Date getDate(Osmformat.Info info) { + if (info.hasTimestamp()) { + return new Date(date_granularity * (long) info.getTimestamp()); + } else + return NODATE; + } + public static final Date NODATE = new Date(); + + /** Get a string based on the index used. + * + * Index 0 is reserved to use as a delimiter, therefore, index 1 corresponds to the first string in the table + * @param id + * @return + */ + protected String getStringById(int id) { + return strings[id]; + } + + @Override + public void handleBlock(FileBlock message) { + // TODO Auto-generated method stub + try { + if (message.getType().equals("OSMHeader")) { + Osmformat.HeaderBlock headerblock = Osmformat.HeaderBlock + .parseFrom(message.getData()); + parse(headerblock); + } else if (message.getType().equals("OSMData")) { + Osmformat.PrimitiveBlock primblock = Osmformat.PrimitiveBlock + .parseFrom(message.getData()); + parse(primblock); + } + } catch (InvalidProtocolBufferException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new Error("ParseError"); // TODO + } + + } + + + @Override + public boolean skipBlock(FileBlockPosition block) { + // System.out.println("Seeing block of type: "+block.getType()); + if (block.getType().equals("OSMData")) + return false; + if (block.getType().equals("OSMHeader")) + return false; + System.out.println("Skipped block of type: " + block.getType()); + return true; + } + + + /** Convert a latitude value stored in a protobuf into a double, compensating for granularity and latitude offset */ + public double parseLat(long degree) { + // Support non-zero offsets. (We don't currently generate them) + return (granularity * degree + lat_offset) * .000000001; + } + + /** Convert a longitude value stored in a protobuf into a double, compensating for granularity and longitude offset */ + public double parseLon(long degree) { + // Support non-zero offsets. (We don't currently generate them) + return (granularity * degree + lon_offset) * .000000001; + } + + /** Parse a Primitive block (containing a string table, other paramaters, and PrimitiveGroups */ + public void parse(Osmformat.PrimitiveBlock block) { + Osmformat.StringTable stablemessage = block.getStringtable(); + strings = new String[stablemessage.getSCount()]; + + for (int i = 0; i < strings.length; i++) { + strings[i] = stablemessage.getS(i).toStringUtf8(); + } + + granularity = block.getGranularity(); + lat_offset = block.getLatOffset(); + lon_offset = block.getLonOffset(); + date_granularity = block.getDateGranularity(); + + for (Osmformat.PrimitiveGroup groupmessage : block + .getPrimitivegroupList()) { + // Exactly one of these should trigger on each loop. + parseNodes(groupmessage.getNodesList()); + parseWays(groupmessage.getWaysList()); + parseRelations(groupmessage.getRelationsList()); + if (groupmessage.hasDense()) + parseDense(groupmessage.getDense()); + } + } + + /** Parse a list of Relation protocol buffers and send the resulting relations to a sink. */ + protected abstract void parseRelations(List rels); + /** Parse a DenseNode protocol buffer and send the resulting nodes to a sink. */ + protected abstract void parseDense(Osmformat.DenseNodes nodes); + /** Parse a list of Node protocol buffers and send the resulting nodes to a sink. */ + protected abstract void parseNodes(List nodes); + /** Parse a list of Way protocol buffers and send the resulting ways to a sink. */ + protected abstract void parseWays(List ways); + /** Parse a header message. */ + protected abstract void parse(Osmformat.HeaderBlock header); + +} \ No newline at end of file diff --git a/DataExtractionOSM/src/crosby/binary/BinarySerializer.java b/DataExtractionOSM/src/crosby/binary/BinarySerializer.java new file mode 100644 index 0000000000..9e80e75eae --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/BinarySerializer.java @@ -0,0 +1,148 @@ +package crosby.binary; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import crosby.binary.Osmformat.PrimitiveGroup; +import crosby.binary.file.BlockOutputStream; +import crosby.binary.file.FileBlock; + +/** + * Generic serializer common code + * + * Serialize a set of blobs and process them. Subclasses implement handlers for + * different API's (osmosis, mkgmap, splitter, etc.) + * + * All data is converted into PrimGroupWriterInterface objects, which are then + * ordered to process their data at the appropriate time. + * */ + +public class BinarySerializer { + + /** + * Interface used to write a group of primitives. One of these for each + * group type (Node, Way, Relation, DenseNode, Changeset) + */ + protected interface PrimGroupWriterInterface { + /** This callback is invoked on each group that is going into the fileblock in order to give it a chance to + * add to the stringtable pool of strings. */ + public void addStringsToStringtable(); + + /** + * This callback is invoked to request that the primgroup serialize itself into the given protocol buffer object. + */ + public Osmformat.PrimitiveGroup serialize(); + } + + /** Set the granularity (precision of lat/lon, measured in unites of nanodegrees. */ + public void configGranularity(int granularity) { + this.granularity = granularity; + } + + /** Set whether metadata is to be omitted */ + public void configOmit(boolean omit_metadata) { + this.omit_metadata = omit_metadata; + } + + /** Configure the maximum number of entities in a batch */ + public void configBatchLimit(int batch_limit) { + this.batch_limit = batch_limit; + } + + // Paramaters affecting the output size. + protected final int MIN_DENSE = 10; + protected int batch_limit = 4000; + + // Parmaters affecting the output. + + protected int granularity = 100; + protected int date_granularity = 1000; + protected boolean omit_metadata = false; + + /** How many primitives have been seen in this batch */ + protected int batch_size = 0; + protected int total_entities = 0; + private StringTable stringtable = new StringTable(); + protected List groups = new ArrayList(); + protected BlockOutputStream output; + + public BinarySerializer(BlockOutputStream output) { + this.output = output; + } + + public StringTable getStringTable() { + return stringtable; + } + + public void flush() throws IOException { + processBatch(); + output.flush(); + } + + public void close() throws IOException { + flush(); + output.close(); + } + + long debug_bytes = 0; + + public void processBatch() { + // System.out.format("Batch of %d groups: ",groups.size()); + if (groups.size() == 0) + return; + Osmformat.PrimitiveBlock.Builder primblock = Osmformat.PrimitiveBlock + .newBuilder(); + stringtable.clear(); + // Preprocessing: Figure out the stringtable. + for (PrimGroupWriterInterface i : groups) + i.addStringsToStringtable(); + + stringtable.finish(); + // Now, start serializing. + for (PrimGroupWriterInterface i : groups) { + PrimitiveGroup group = i.serialize(); + if (group != null) + primblock.addPrimitivegroup(group); + } + primblock.setStringtable(stringtable.serialize()); + primblock.setGranularity(this.granularity); + primblock.setDateGranularity(this.date_granularity); + + // Only generate data with offset (0,0) + // + Osmformat.PrimitiveBlock message = primblock.build(); + + // System.out.println(message); + debug_bytes += message.getSerializedSize(); + if (false) // TODO: Prettyprinted output. + System.out.format(" =======> %.2f / %.2f (%dk)\n", message + .getSerializedSize() / 1024.0, debug_bytes / 1024 / 1024.0, + total_entities / 1000); + // if (message.getSerializedSize() > 1000000) + // System.out.println(message); + + try { + output.write(FileBlock.newInstance("OSMData", message + .toByteString(), null)); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new Error(e); + } finally { + batch_size = 0; + groups.clear(); + } + // System.out.format("\n"); + } + + /** Convert from a degrees represented as a double into the serialized offset in nanodegrees.. */ + public long mapRawDegrees(double degrees) { + return (long) ((degrees / .000000001)); + } + + /** Convert from a degrees represented as a double into the serialized offset. */ + public int mapDegrees(double degrees) { + return (int) ((degrees / .0000001) / (granularity / 100)); + } +} diff --git a/DataExtractionOSM/src/crosby/binary/Fileformat.java b/DataExtractionOSM/src/crosby/binary/Fileformat.java new file mode 100644 index 0000000000..5dd17601dd --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/Fileformat.java @@ -0,0 +1,891 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: fileformat.proto + +package crosby.binary; + +public final class Fileformat { + private Fileformat() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public static final class Blob extends + com.google.protobuf.GeneratedMessage { + // Use Blob.newBuilder() to construct. + private Blob() { + initFields(); + } + private Blob(boolean noInit) {} + + private static final Blob defaultInstance; + public static Blob getDefaultInstance() { + return defaultInstance; + } + + public Blob getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Fileformat.internal_static_Blob_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Fileformat.internal_static_Blob_fieldAccessorTable; + } + + // optional bytes raw = 1; + public static final int RAW_FIELD_NUMBER = 1; + private boolean hasRaw; + private com.google.protobuf.ByteString raw_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasRaw() { return hasRaw; } + public com.google.protobuf.ByteString getRaw() { return raw_; } + + // optional int32 raw_size = 2; + public static final int RAW_SIZE_FIELD_NUMBER = 2; + private boolean hasRawSize; + private int rawSize_ = 0; + public boolean hasRawSize() { return hasRawSize; } + public int getRawSize() { return rawSize_; } + + // optional bytes zlib_data = 3; + public static final int ZLIB_DATA_FIELD_NUMBER = 3; + private boolean hasZlibData; + private com.google.protobuf.ByteString zlibData_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasZlibData() { return hasZlibData; } + public com.google.protobuf.ByteString getZlibData() { return zlibData_; } + + // optional bytes lzma_data = 4; + public static final int LZMA_DATA_FIELD_NUMBER = 4; + private boolean hasLzmaData; + private com.google.protobuf.ByteString lzmaData_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasLzmaData() { return hasLzmaData; } + public com.google.protobuf.ByteString getLzmaData() { return lzmaData_; } + + // optional bytes bzip2_data = 5; + public static final int BZIP2_DATA_FIELD_NUMBER = 5; + private boolean hasBzip2Data; + private com.google.protobuf.ByteString bzip2Data_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasBzip2Data() { return hasBzip2Data; } + public com.google.protobuf.ByteString getBzip2Data() { return bzip2Data_; } + + private void initFields() { + } + public final boolean isInitialized() { + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasRaw()) { + output.writeBytes(1, getRaw()); + } + if (hasRawSize()) { + output.writeInt32(2, getRawSize()); + } + if (hasZlibData()) { + output.writeBytes(3, getZlibData()); + } + if (hasLzmaData()) { + output.writeBytes(4, getLzmaData()); + } + if (hasBzip2Data()) { + output.writeBytes(5, getBzip2Data()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasRaw()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, getRaw()); + } + if (hasRawSize()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, getRawSize()); + } + if (hasZlibData()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(3, getZlibData()); + } + if (hasLzmaData()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(4, getLzmaData()); + } + if (hasBzip2Data()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(5, getBzip2Data()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Fileformat.Blob parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Fileformat.Blob parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Fileformat.Blob parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Fileformat.Blob parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Fileformat.Blob prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Fileformat.Blob result; + + // Construct using crosby.binary.Fileformat.Blob.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Fileformat.Blob(); + return builder; + } + + protected crosby.binary.Fileformat.Blob internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Fileformat.Blob(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Fileformat.Blob.getDescriptor(); + } + + public crosby.binary.Fileformat.Blob getDefaultInstanceForType() { + return crosby.binary.Fileformat.Blob.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Fileformat.Blob build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Fileformat.Blob buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Fileformat.Blob buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + crosby.binary.Fileformat.Blob returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Fileformat.Blob) { + return mergeFrom((crosby.binary.Fileformat.Blob)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Fileformat.Blob other) { + if (other == crosby.binary.Fileformat.Blob.getDefaultInstance()) return this; + if (other.hasRaw()) { + setRaw(other.getRaw()); + } + if (other.hasRawSize()) { + setRawSize(other.getRawSize()); + } + if (other.hasZlibData()) { + setZlibData(other.getZlibData()); + } + if (other.hasLzmaData()) { + setLzmaData(other.getLzmaData()); + } + if (other.hasBzip2Data()) { + setBzip2Data(other.getBzip2Data()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + setRaw(input.readBytes()); + break; + } + case 16: { + setRawSize(input.readInt32()); + break; + } + case 26: { + setZlibData(input.readBytes()); + break; + } + case 34: { + setLzmaData(input.readBytes()); + break; + } + case 42: { + setBzip2Data(input.readBytes()); + break; + } + } + } + } + + + // optional bytes raw = 1; + public boolean hasRaw() { + return result.hasRaw(); + } + public com.google.protobuf.ByteString getRaw() { + return result.getRaw(); + } + public Builder setRaw(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasRaw = true; + result.raw_ = value; + return this; + } + public Builder clearRaw() { + result.hasRaw = false; + result.raw_ = getDefaultInstance().getRaw(); + return this; + } + + // optional int32 raw_size = 2; + public boolean hasRawSize() { + return result.hasRawSize(); + } + public int getRawSize() { + return result.getRawSize(); + } + public Builder setRawSize(int value) { + result.hasRawSize = true; + result.rawSize_ = value; + return this; + } + public Builder clearRawSize() { + result.hasRawSize = false; + result.rawSize_ = 0; + return this; + } + + // optional bytes zlib_data = 3; + public boolean hasZlibData() { + return result.hasZlibData(); + } + public com.google.protobuf.ByteString getZlibData() { + return result.getZlibData(); + } + public Builder setZlibData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasZlibData = true; + result.zlibData_ = value; + return this; + } + public Builder clearZlibData() { + result.hasZlibData = false; + result.zlibData_ = getDefaultInstance().getZlibData(); + return this; + } + + // optional bytes lzma_data = 4; + public boolean hasLzmaData() { + return result.hasLzmaData(); + } + public com.google.protobuf.ByteString getLzmaData() { + return result.getLzmaData(); + } + public Builder setLzmaData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasLzmaData = true; + result.lzmaData_ = value; + return this; + } + public Builder clearLzmaData() { + result.hasLzmaData = false; + result.lzmaData_ = getDefaultInstance().getLzmaData(); + return this; + } + + // optional bytes bzip2_data = 5; + public boolean hasBzip2Data() { + return result.hasBzip2Data(); + } + public com.google.protobuf.ByteString getBzip2Data() { + return result.getBzip2Data(); + } + public Builder setBzip2Data(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasBzip2Data = true; + result.bzip2Data_ = value; + return this; + } + public Builder clearBzip2Data() { + result.hasBzip2Data = false; + result.bzip2Data_ = getDefaultInstance().getBzip2Data(); + return this; + } + + // @@protoc_insertion_point(builder_scope:Blob) + } + + static { + defaultInstance = new Blob(true); + crosby.binary.Fileformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:Blob) + } + + public static final class BlockHeader extends + com.google.protobuf.GeneratedMessage { + // Use BlockHeader.newBuilder() to construct. + private BlockHeader() { + initFields(); + } + private BlockHeader(boolean noInit) {} + + private static final BlockHeader defaultInstance; + public static BlockHeader getDefaultInstance() { + return defaultInstance; + } + + public BlockHeader getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Fileformat.internal_static_BlockHeader_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Fileformat.internal_static_BlockHeader_fieldAccessorTable; + } + + // required string type = 1; + public static final int TYPE_FIELD_NUMBER = 1; + private boolean hasType; + private java.lang.String type_ = ""; + public boolean hasType() { return hasType; } + public java.lang.String getType() { return type_; } + + // optional bytes indexdata = 2; + public static final int INDEXDATA_FIELD_NUMBER = 2; + private boolean hasIndexdata; + private com.google.protobuf.ByteString indexdata_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasIndexdata() { return hasIndexdata; } + public com.google.protobuf.ByteString getIndexdata() { return indexdata_; } + + // required int32 datasize = 3; + public static final int DATASIZE_FIELD_NUMBER = 3; + private boolean hasDatasize; + private int datasize_ = 0; + public boolean hasDatasize() { return hasDatasize; } + public int getDatasize() { return datasize_; } + + private void initFields() { + } + public final boolean isInitialized() { + if (!hasType) return false; + if (!hasDatasize) return false; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasType()) { + output.writeString(1, getType()); + } + if (hasIndexdata()) { + output.writeBytes(2, getIndexdata()); + } + if (hasDatasize()) { + output.writeInt32(3, getDatasize()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasType()) { + size += com.google.protobuf.CodedOutputStream + .computeStringSize(1, getType()); + } + if (hasIndexdata()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(2, getIndexdata()); + } + if (hasDatasize()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(3, getDatasize()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Fileformat.BlockHeader parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Fileformat.BlockHeader parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Fileformat.BlockHeader parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Fileformat.BlockHeader parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Fileformat.BlockHeader prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Fileformat.BlockHeader result; + + // Construct using crosby.binary.Fileformat.BlockHeader.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Fileformat.BlockHeader(); + return builder; + } + + protected crosby.binary.Fileformat.BlockHeader internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Fileformat.BlockHeader(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Fileformat.BlockHeader.getDescriptor(); + } + + public crosby.binary.Fileformat.BlockHeader getDefaultInstanceForType() { + return crosby.binary.Fileformat.BlockHeader.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Fileformat.BlockHeader build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Fileformat.BlockHeader buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Fileformat.BlockHeader buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + crosby.binary.Fileformat.BlockHeader returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Fileformat.BlockHeader) { + return mergeFrom((crosby.binary.Fileformat.BlockHeader)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Fileformat.BlockHeader other) { + if (other == crosby.binary.Fileformat.BlockHeader.getDefaultInstance()) return this; + if (other.hasType()) { + setType(other.getType()); + } + if (other.hasIndexdata()) { + setIndexdata(other.getIndexdata()); + } + if (other.hasDatasize()) { + setDatasize(other.getDatasize()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + setType(input.readString()); + break; + } + case 18: { + setIndexdata(input.readBytes()); + break; + } + case 24: { + setDatasize(input.readInt32()); + break; + } + } + } + } + + + // required string type = 1; + public boolean hasType() { + return result.hasType(); + } + public java.lang.String getType() { + return result.getType(); + } + public Builder setType(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasType = true; + result.type_ = value; + return this; + } + public Builder clearType() { + result.hasType = false; + result.type_ = getDefaultInstance().getType(); + return this; + } + + // optional bytes indexdata = 2; + public boolean hasIndexdata() { + return result.hasIndexdata(); + } + public com.google.protobuf.ByteString getIndexdata() { + return result.getIndexdata(); + } + public Builder setIndexdata(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasIndexdata = true; + result.indexdata_ = value; + return this; + } + public Builder clearIndexdata() { + result.hasIndexdata = false; + result.indexdata_ = getDefaultInstance().getIndexdata(); + return this; + } + + // required int32 datasize = 3; + public boolean hasDatasize() { + return result.hasDatasize(); + } + public int getDatasize() { + return result.getDatasize(); + } + public Builder setDatasize(int value) { + result.hasDatasize = true; + result.datasize_ = value; + return this; + } + public Builder clearDatasize() { + result.hasDatasize = false; + result.datasize_ = 0; + return this; + } + + // @@protoc_insertion_point(builder_scope:BlockHeader) + } + + static { + defaultInstance = new BlockHeader(true); + crosby.binary.Fileformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:BlockHeader) + } + + private static com.google.protobuf.Descriptors.Descriptor + internal_static_Blob_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_Blob_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_BlockHeader_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_BlockHeader_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\020fileformat.proto\"_\n\004Blob\022\013\n\003raw\030\001 \001(\014\022" + + "\020\n\010raw_size\030\002 \001(\005\022\021\n\tzlib_data\030\003 \001(\014\022\021\n\t" + + "lzma_data\030\004 \001(\014\022\022\n\nbzip2_data\030\005 \001(\014\"@\n\013B" + + "lockHeader\022\014\n\004type\030\001 \002(\t\022\021\n\tindexdata\030\002 " + + "\001(\014\022\020\n\010datasize\030\003 \002(\005B\017\n\rcrosby.binary" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + internal_static_Blob_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_Blob_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_Blob_descriptor, + new java.lang.String[] { "Raw", "RawSize", "ZlibData", "LzmaData", "Bzip2Data", }, + crosby.binary.Fileformat.Blob.class, + crosby.binary.Fileformat.Blob.Builder.class); + internal_static_BlockHeader_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_BlockHeader_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_BlockHeader_descriptor, + new java.lang.String[] { "Type", "Indexdata", "Datasize", }, + crosby.binary.Fileformat.BlockHeader.class, + crosby.binary.Fileformat.BlockHeader.Builder.class); + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + } + + public static void internalForceInit() {} + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/DataExtractionOSM/src/crosby/binary/Osmformat.java b/DataExtractionOSM/src/crosby/binary/Osmformat.java new file mode 100644 index 0000000000..b5364a174a --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/Osmformat.java @@ -0,0 +1,6949 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: src/osmformat.proto + +package crosby.binary; + +public final class Osmformat { + private Osmformat() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public static final class HeaderBlock extends + com.google.protobuf.GeneratedMessage { + // Use HeaderBlock.newBuilder() to construct. + private HeaderBlock() { + initFields(); + } + private HeaderBlock(boolean noInit) {} + + private static final HeaderBlock defaultInstance; + public static HeaderBlock getDefaultInstance() { + return defaultInstance; + } + + public HeaderBlock getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_HeaderBlock_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_HeaderBlock_fieldAccessorTable; + } + + // optional .HeaderBBox bbox = 1; + public static final int BBOX_FIELD_NUMBER = 1; + private boolean hasBbox; + private crosby.binary.Osmformat.HeaderBBox bbox_; + public boolean hasBbox() { return hasBbox; } + public crosby.binary.Osmformat.HeaderBBox getBbox() { return bbox_; } + + // repeated string required_features = 4; + public static final int REQUIRED_FEATURES_FIELD_NUMBER = 4; + private java.util.List requiredFeatures_ = + java.util.Collections.emptyList(); + public java.util.List getRequiredFeaturesList() { + return requiredFeatures_; + } + public int getRequiredFeaturesCount() { return requiredFeatures_.size(); } + public java.lang.String getRequiredFeatures(int index) { + return requiredFeatures_.get(index); + } + + // repeated string optional_features = 5; + public static final int OPTIONAL_FEATURES_FIELD_NUMBER = 5; + private java.util.List optionalFeatures_ = + java.util.Collections.emptyList(); + public java.util.List getOptionalFeaturesList() { + return optionalFeatures_; + } + public int getOptionalFeaturesCount() { return optionalFeatures_.size(); } + public java.lang.String getOptionalFeatures(int index) { + return optionalFeatures_.get(index); + } + + // optional string writingprogram = 16; + public static final int WRITINGPROGRAM_FIELD_NUMBER = 16; + private boolean hasWritingprogram; + private java.lang.String writingprogram_ = ""; + public boolean hasWritingprogram() { return hasWritingprogram; } + public java.lang.String getWritingprogram() { return writingprogram_; } + + // optional string source = 17; + public static final int SOURCE_FIELD_NUMBER = 17; + private boolean hasSource; + private java.lang.String source_ = ""; + public boolean hasSource() { return hasSource; } + public java.lang.String getSource() { return source_; } + + private void initFields() { + bbox_ = crosby.binary.Osmformat.HeaderBBox.getDefaultInstance(); + } + public final boolean isInitialized() { + if (hasBbox()) { + if (!getBbox().isInitialized()) return false; + } + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasBbox()) { + output.writeMessage(1, getBbox()); + } + for (java.lang.String element : getRequiredFeaturesList()) { + output.writeString(4, element); + } + for (java.lang.String element : getOptionalFeaturesList()) { + output.writeString(5, element); + } + if (hasWritingprogram()) { + output.writeString(16, getWritingprogram()); + } + if (hasSource()) { + output.writeString(17, getSource()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasBbox()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, getBbox()); + } + { + int dataSize = 0; + for (java.lang.String element : getRequiredFeaturesList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeStringSizeNoTag(element); + } + size += dataSize; + size += 1 * getRequiredFeaturesList().size(); + } + { + int dataSize = 0; + for (java.lang.String element : getOptionalFeaturesList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeStringSizeNoTag(element); + } + size += dataSize; + size += 1 * getOptionalFeaturesList().size(); + } + if (hasWritingprogram()) { + size += com.google.protobuf.CodedOutputStream + .computeStringSize(16, getWritingprogram()); + } + if (hasSource()) { + size += com.google.protobuf.CodedOutputStream + .computeStringSize(17, getSource()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.HeaderBlock parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.HeaderBlock parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBlock parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.HeaderBlock prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.HeaderBlock result; + + // Construct using crosby.binary.Osmformat.HeaderBlock.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.HeaderBlock(); + return builder; + } + + protected crosby.binary.Osmformat.HeaderBlock internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.HeaderBlock(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.HeaderBlock.getDescriptor(); + } + + public crosby.binary.Osmformat.HeaderBlock getDefaultInstanceForType() { + return crosby.binary.Osmformat.HeaderBlock.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.HeaderBlock build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.HeaderBlock buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.HeaderBlock buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.requiredFeatures_ != java.util.Collections.EMPTY_LIST) { + result.requiredFeatures_ = + java.util.Collections.unmodifiableList(result.requiredFeatures_); + } + if (result.optionalFeatures_ != java.util.Collections.EMPTY_LIST) { + result.optionalFeatures_ = + java.util.Collections.unmodifiableList(result.optionalFeatures_); + } + crosby.binary.Osmformat.HeaderBlock returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.HeaderBlock) { + return mergeFrom((crosby.binary.Osmformat.HeaderBlock)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.HeaderBlock other) { + if (other == crosby.binary.Osmformat.HeaderBlock.getDefaultInstance()) return this; + if (other.hasBbox()) { + mergeBbox(other.getBbox()); + } + if (!other.requiredFeatures_.isEmpty()) { + if (result.requiredFeatures_.isEmpty()) { + result.requiredFeatures_ = new java.util.ArrayList(); + } + result.requiredFeatures_.addAll(other.requiredFeatures_); + } + if (!other.optionalFeatures_.isEmpty()) { + if (result.optionalFeatures_.isEmpty()) { + result.optionalFeatures_ = new java.util.ArrayList(); + } + result.optionalFeatures_.addAll(other.optionalFeatures_); + } + if (other.hasWritingprogram()) { + setWritingprogram(other.getWritingprogram()); + } + if (other.hasSource()) { + setSource(other.getSource()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + crosby.binary.Osmformat.HeaderBBox.Builder subBuilder = crosby.binary.Osmformat.HeaderBBox.newBuilder(); + if (hasBbox()) { + subBuilder.mergeFrom(getBbox()); + } + input.readMessage(subBuilder, extensionRegistry); + setBbox(subBuilder.buildPartial()); + break; + } + case 34: { + addRequiredFeatures(input.readString()); + break; + } + case 42: { + addOptionalFeatures(input.readString()); + break; + } + case 130: { + setWritingprogram(input.readString()); + break; + } + case 138: { + setSource(input.readString()); + break; + } + } + } + } + + + // optional .HeaderBBox bbox = 1; + public boolean hasBbox() { + return result.hasBbox(); + } + public crosby.binary.Osmformat.HeaderBBox getBbox() { + return result.getBbox(); + } + public Builder setBbox(crosby.binary.Osmformat.HeaderBBox value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasBbox = true; + result.bbox_ = value; + return this; + } + public Builder setBbox(crosby.binary.Osmformat.HeaderBBox.Builder builderForValue) { + result.hasBbox = true; + result.bbox_ = builderForValue.build(); + return this; + } + public Builder mergeBbox(crosby.binary.Osmformat.HeaderBBox value) { + if (result.hasBbox() && + result.bbox_ != crosby.binary.Osmformat.HeaderBBox.getDefaultInstance()) { + result.bbox_ = + crosby.binary.Osmformat.HeaderBBox.newBuilder(result.bbox_).mergeFrom(value).buildPartial(); + } else { + result.bbox_ = value; + } + result.hasBbox = true; + return this; + } + public Builder clearBbox() { + result.hasBbox = false; + result.bbox_ = crosby.binary.Osmformat.HeaderBBox.getDefaultInstance(); + return this; + } + + // repeated string required_features = 4; + public java.util.List getRequiredFeaturesList() { + return java.util.Collections.unmodifiableList(result.requiredFeatures_); + } + public int getRequiredFeaturesCount() { + return result.getRequiredFeaturesCount(); + } + public java.lang.String getRequiredFeatures(int index) { + return result.getRequiredFeatures(index); + } + public Builder setRequiredFeatures(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.requiredFeatures_.set(index, value); + return this; + } + public Builder addRequiredFeatures(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.requiredFeatures_.isEmpty()) { + result.requiredFeatures_ = new java.util.ArrayList(); + } + result.requiredFeatures_.add(value); + return this; + } + public Builder addAllRequiredFeatures( + java.lang.Iterable values) { + if (result.requiredFeatures_.isEmpty()) { + result.requiredFeatures_ = new java.util.ArrayList(); + } + super.addAll(values, result.requiredFeatures_); + return this; + } + public Builder clearRequiredFeatures() { + result.requiredFeatures_ = java.util.Collections.emptyList(); + return this; + } + + // repeated string optional_features = 5; + public java.util.List getOptionalFeaturesList() { + return java.util.Collections.unmodifiableList(result.optionalFeatures_); + } + public int getOptionalFeaturesCount() { + return result.getOptionalFeaturesCount(); + } + public java.lang.String getOptionalFeatures(int index) { + return result.getOptionalFeatures(index); + } + public Builder setOptionalFeatures(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.optionalFeatures_.set(index, value); + return this; + } + public Builder addOptionalFeatures(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.optionalFeatures_.isEmpty()) { + result.optionalFeatures_ = new java.util.ArrayList(); + } + result.optionalFeatures_.add(value); + return this; + } + public Builder addAllOptionalFeatures( + java.lang.Iterable values) { + if (result.optionalFeatures_.isEmpty()) { + result.optionalFeatures_ = new java.util.ArrayList(); + } + super.addAll(values, result.optionalFeatures_); + return this; + } + public Builder clearOptionalFeatures() { + result.optionalFeatures_ = java.util.Collections.emptyList(); + return this; + } + + // optional string writingprogram = 16; + public boolean hasWritingprogram() { + return result.hasWritingprogram(); + } + public java.lang.String getWritingprogram() { + return result.getWritingprogram(); + } + public Builder setWritingprogram(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasWritingprogram = true; + result.writingprogram_ = value; + return this; + } + public Builder clearWritingprogram() { + result.hasWritingprogram = false; + result.writingprogram_ = getDefaultInstance().getWritingprogram(); + return this; + } + + // optional string source = 17; + public boolean hasSource() { + return result.hasSource(); + } + public java.lang.String getSource() { + return result.getSource(); + } + public Builder setSource(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasSource = true; + result.source_ = value; + return this; + } + public Builder clearSource() { + result.hasSource = false; + result.source_ = getDefaultInstance().getSource(); + return this; + } + + // @@protoc_insertion_point(builder_scope:HeaderBlock) + } + + static { + defaultInstance = new HeaderBlock(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:HeaderBlock) + } + + public static final class HeaderBBox extends + com.google.protobuf.GeneratedMessage { + // Use HeaderBBox.newBuilder() to construct. + private HeaderBBox() { + initFields(); + } + private HeaderBBox(boolean noInit) {} + + private static final HeaderBBox defaultInstance; + public static HeaderBBox getDefaultInstance() { + return defaultInstance; + } + + public HeaderBBox getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_HeaderBBox_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_HeaderBBox_fieldAccessorTable; + } + + // required sint64 left = 1; + public static final int LEFT_FIELD_NUMBER = 1; + private boolean hasLeft; + private long left_ = 0L; + public boolean hasLeft() { return hasLeft; } + public long getLeft() { return left_; } + + // required sint64 right = 2; + public static final int RIGHT_FIELD_NUMBER = 2; + private boolean hasRight; + private long right_ = 0L; + public boolean hasRight() { return hasRight; } + public long getRight() { return right_; } + + // required sint64 top = 3; + public static final int TOP_FIELD_NUMBER = 3; + private boolean hasTop; + private long top_ = 0L; + public boolean hasTop() { return hasTop; } + public long getTop() { return top_; } + + // required sint64 bottom = 4; + public static final int BOTTOM_FIELD_NUMBER = 4; + private boolean hasBottom; + private long bottom_ = 0L; + public boolean hasBottom() { return hasBottom; } + public long getBottom() { return bottom_; } + + private void initFields() { + } + public final boolean isInitialized() { + if (!hasLeft) return false; + if (!hasRight) return false; + if (!hasTop) return false; + if (!hasBottom) return false; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasLeft()) { + output.writeSInt64(1, getLeft()); + } + if (hasRight()) { + output.writeSInt64(2, getRight()); + } + if (hasTop()) { + output.writeSInt64(3, getTop()); + } + if (hasBottom()) { + output.writeSInt64(4, getBottom()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasLeft()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(1, getLeft()); + } + if (hasRight()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(2, getRight()); + } + if (hasTop()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(3, getTop()); + } + if (hasBottom()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(4, getBottom()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.HeaderBBox parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.HeaderBBox parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.HeaderBBox parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.HeaderBBox prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.HeaderBBox result; + + // Construct using crosby.binary.Osmformat.HeaderBBox.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.HeaderBBox(); + return builder; + } + + protected crosby.binary.Osmformat.HeaderBBox internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.HeaderBBox(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.HeaderBBox.getDescriptor(); + } + + public crosby.binary.Osmformat.HeaderBBox getDefaultInstanceForType() { + return crosby.binary.Osmformat.HeaderBBox.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.HeaderBBox build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.HeaderBBox buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.HeaderBBox buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + crosby.binary.Osmformat.HeaderBBox returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.HeaderBBox) { + return mergeFrom((crosby.binary.Osmformat.HeaderBBox)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.HeaderBBox other) { + if (other == crosby.binary.Osmformat.HeaderBBox.getDefaultInstance()) return this; + if (other.hasLeft()) { + setLeft(other.getLeft()); + } + if (other.hasRight()) { + setRight(other.getRight()); + } + if (other.hasTop()) { + setTop(other.getTop()); + } + if (other.hasBottom()) { + setBottom(other.getBottom()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setLeft(input.readSInt64()); + break; + } + case 16: { + setRight(input.readSInt64()); + break; + } + case 24: { + setTop(input.readSInt64()); + break; + } + case 32: { + setBottom(input.readSInt64()); + break; + } + } + } + } + + + // required sint64 left = 1; + public boolean hasLeft() { + return result.hasLeft(); + } + public long getLeft() { + return result.getLeft(); + } + public Builder setLeft(long value) { + result.hasLeft = true; + result.left_ = value; + return this; + } + public Builder clearLeft() { + result.hasLeft = false; + result.left_ = 0L; + return this; + } + + // required sint64 right = 2; + public boolean hasRight() { + return result.hasRight(); + } + public long getRight() { + return result.getRight(); + } + public Builder setRight(long value) { + result.hasRight = true; + result.right_ = value; + return this; + } + public Builder clearRight() { + result.hasRight = false; + result.right_ = 0L; + return this; + } + + // required sint64 top = 3; + public boolean hasTop() { + return result.hasTop(); + } + public long getTop() { + return result.getTop(); + } + public Builder setTop(long value) { + result.hasTop = true; + result.top_ = value; + return this; + } + public Builder clearTop() { + result.hasTop = false; + result.top_ = 0L; + return this; + } + + // required sint64 bottom = 4; + public boolean hasBottom() { + return result.hasBottom(); + } + public long getBottom() { + return result.getBottom(); + } + public Builder setBottom(long value) { + result.hasBottom = true; + result.bottom_ = value; + return this; + } + public Builder clearBottom() { + result.hasBottom = false; + result.bottom_ = 0L; + return this; + } + + // @@protoc_insertion_point(builder_scope:HeaderBBox) + } + + static { + defaultInstance = new HeaderBBox(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:HeaderBBox) + } + + public static final class PrimitiveBlock extends + com.google.protobuf.GeneratedMessage { + // Use PrimitiveBlock.newBuilder() to construct. + private PrimitiveBlock() { + initFields(); + } + private PrimitiveBlock(boolean noInit) {} + + private static final PrimitiveBlock defaultInstance; + public static PrimitiveBlock getDefaultInstance() { + return defaultInstance; + } + + public PrimitiveBlock getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_PrimitiveBlock_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_PrimitiveBlock_fieldAccessorTable; + } + + // required .StringTable stringtable = 1; + public static final int STRINGTABLE_FIELD_NUMBER = 1; + private boolean hasStringtable; + private crosby.binary.Osmformat.StringTable stringtable_; + public boolean hasStringtable() { return hasStringtable; } + public crosby.binary.Osmformat.StringTable getStringtable() { return stringtable_; } + + // repeated .PrimitiveGroup primitivegroup = 2; + public static final int PRIMITIVEGROUP_FIELD_NUMBER = 2; + private java.util.List primitivegroup_ = + java.util.Collections.emptyList(); + public java.util.List getPrimitivegroupList() { + return primitivegroup_; + } + public int getPrimitivegroupCount() { return primitivegroup_.size(); } + public crosby.binary.Osmformat.PrimitiveGroup getPrimitivegroup(int index) { + return primitivegroup_.get(index); + } + + // optional int32 granularity = 17 [default = 100]; + public static final int GRANULARITY_FIELD_NUMBER = 17; + private boolean hasGranularity; + private int granularity_ = 100; + public boolean hasGranularity() { return hasGranularity; } + public int getGranularity() { return granularity_; } + + // optional int64 lat_offset = 19 [default = 0]; + public static final int LAT_OFFSET_FIELD_NUMBER = 19; + private boolean hasLatOffset; + private long latOffset_ = 0L; + public boolean hasLatOffset() { return hasLatOffset; } + public long getLatOffset() { return latOffset_; } + + // optional int64 lon_offset = 20 [default = 0]; + public static final int LON_OFFSET_FIELD_NUMBER = 20; + private boolean hasLonOffset; + private long lonOffset_ = 0L; + public boolean hasLonOffset() { return hasLonOffset; } + public long getLonOffset() { return lonOffset_; } + + // optional int32 date_granularity = 18 [default = 1000]; + public static final int DATE_GRANULARITY_FIELD_NUMBER = 18; + private boolean hasDateGranularity; + private int dateGranularity_ = 1000; + public boolean hasDateGranularity() { return hasDateGranularity; } + public int getDateGranularity() { return dateGranularity_; } + + private void initFields() { + stringtable_ = crosby.binary.Osmformat.StringTable.getDefaultInstance(); + } + public final boolean isInitialized() { + if (!hasStringtable) return false; + for (crosby.binary.Osmformat.PrimitiveGroup element : getPrimitivegroupList()) { + if (!element.isInitialized()) return false; + } + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasStringtable()) { + output.writeMessage(1, getStringtable()); + } + for (crosby.binary.Osmformat.PrimitiveGroup element : getPrimitivegroupList()) { + output.writeMessage(2, element); + } + if (hasGranularity()) { + output.writeInt32(17, getGranularity()); + } + if (hasDateGranularity()) { + output.writeInt32(18, getDateGranularity()); + } + if (hasLatOffset()) { + output.writeInt64(19, getLatOffset()); + } + if (hasLonOffset()) { + output.writeInt64(20, getLonOffset()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasStringtable()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, getStringtable()); + } + for (crosby.binary.Osmformat.PrimitiveGroup element : getPrimitivegroupList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, element); + } + if (hasGranularity()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(17, getGranularity()); + } + if (hasDateGranularity()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(18, getDateGranularity()); + } + if (hasLatOffset()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(19, getLatOffset()); + } + if (hasLonOffset()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(20, getLonOffset()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.PrimitiveBlock parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveBlock parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.PrimitiveBlock prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.PrimitiveBlock result; + + // Construct using crosby.binary.Osmformat.PrimitiveBlock.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.PrimitiveBlock(); + return builder; + } + + protected crosby.binary.Osmformat.PrimitiveBlock internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.PrimitiveBlock(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.PrimitiveBlock.getDescriptor(); + } + + public crosby.binary.Osmformat.PrimitiveBlock getDefaultInstanceForType() { + return crosby.binary.Osmformat.PrimitiveBlock.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.PrimitiveBlock build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.PrimitiveBlock buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.PrimitiveBlock buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.primitivegroup_ != java.util.Collections.EMPTY_LIST) { + result.primitivegroup_ = + java.util.Collections.unmodifiableList(result.primitivegroup_); + } + crosby.binary.Osmformat.PrimitiveBlock returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.PrimitiveBlock) { + return mergeFrom((crosby.binary.Osmformat.PrimitiveBlock)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.PrimitiveBlock other) { + if (other == crosby.binary.Osmformat.PrimitiveBlock.getDefaultInstance()) return this; + if (other.hasStringtable()) { + mergeStringtable(other.getStringtable()); + } + if (!other.primitivegroup_.isEmpty()) { + if (result.primitivegroup_.isEmpty()) { + result.primitivegroup_ = new java.util.ArrayList(); + } + result.primitivegroup_.addAll(other.primitivegroup_); + } + if (other.hasGranularity()) { + setGranularity(other.getGranularity()); + } + if (other.hasLatOffset()) { + setLatOffset(other.getLatOffset()); + } + if (other.hasLonOffset()) { + setLonOffset(other.getLonOffset()); + } + if (other.hasDateGranularity()) { + setDateGranularity(other.getDateGranularity()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + crosby.binary.Osmformat.StringTable.Builder subBuilder = crosby.binary.Osmformat.StringTable.newBuilder(); + if (hasStringtable()) { + subBuilder.mergeFrom(getStringtable()); + } + input.readMessage(subBuilder, extensionRegistry); + setStringtable(subBuilder.buildPartial()); + break; + } + case 18: { + crosby.binary.Osmformat.PrimitiveGroup.Builder subBuilder = crosby.binary.Osmformat.PrimitiveGroup.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addPrimitivegroup(subBuilder.buildPartial()); + break; + } + case 136: { + setGranularity(input.readInt32()); + break; + } + case 144: { + setDateGranularity(input.readInt32()); + break; + } + case 152: { + setLatOffset(input.readInt64()); + break; + } + case 160: { + setLonOffset(input.readInt64()); + break; + } + } + } + } + + + // required .StringTable stringtable = 1; + public boolean hasStringtable() { + return result.hasStringtable(); + } + public crosby.binary.Osmformat.StringTable getStringtable() { + return result.getStringtable(); + } + public Builder setStringtable(crosby.binary.Osmformat.StringTable value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasStringtable = true; + result.stringtable_ = value; + return this; + } + public Builder setStringtable(crosby.binary.Osmformat.StringTable.Builder builderForValue) { + result.hasStringtable = true; + result.stringtable_ = builderForValue.build(); + return this; + } + public Builder mergeStringtable(crosby.binary.Osmformat.StringTable value) { + if (result.hasStringtable() && + result.stringtable_ != crosby.binary.Osmformat.StringTable.getDefaultInstance()) { + result.stringtable_ = + crosby.binary.Osmformat.StringTable.newBuilder(result.stringtable_).mergeFrom(value).buildPartial(); + } else { + result.stringtable_ = value; + } + result.hasStringtable = true; + return this; + } + public Builder clearStringtable() { + result.hasStringtable = false; + result.stringtable_ = crosby.binary.Osmformat.StringTable.getDefaultInstance(); + return this; + } + + // repeated .PrimitiveGroup primitivegroup = 2; + public java.util.List getPrimitivegroupList() { + return java.util.Collections.unmodifiableList(result.primitivegroup_); + } + public int getPrimitivegroupCount() { + return result.getPrimitivegroupCount(); + } + public crosby.binary.Osmformat.PrimitiveGroup getPrimitivegroup(int index) { + return result.getPrimitivegroup(index); + } + public Builder setPrimitivegroup(int index, crosby.binary.Osmformat.PrimitiveGroup value) { + if (value == null) { + throw new NullPointerException(); + } + result.primitivegroup_.set(index, value); + return this; + } + public Builder setPrimitivegroup(int index, crosby.binary.Osmformat.PrimitiveGroup.Builder builderForValue) { + result.primitivegroup_.set(index, builderForValue.build()); + return this; + } + public Builder addPrimitivegroup(crosby.binary.Osmformat.PrimitiveGroup value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.primitivegroup_.isEmpty()) { + result.primitivegroup_ = new java.util.ArrayList(); + } + result.primitivegroup_.add(value); + return this; + } + public Builder addPrimitivegroup(crosby.binary.Osmformat.PrimitiveGroup.Builder builderForValue) { + if (result.primitivegroup_.isEmpty()) { + result.primitivegroup_ = new java.util.ArrayList(); + } + result.primitivegroup_.add(builderForValue.build()); + return this; + } + public Builder addAllPrimitivegroup( + java.lang.Iterable values) { + if (result.primitivegroup_.isEmpty()) { + result.primitivegroup_ = new java.util.ArrayList(); + } + super.addAll(values, result.primitivegroup_); + return this; + } + public Builder clearPrimitivegroup() { + result.primitivegroup_ = java.util.Collections.emptyList(); + return this; + } + + // optional int32 granularity = 17 [default = 100]; + public boolean hasGranularity() { + return result.hasGranularity(); + } + public int getGranularity() { + return result.getGranularity(); + } + public Builder setGranularity(int value) { + result.hasGranularity = true; + result.granularity_ = value; + return this; + } + public Builder clearGranularity() { + result.hasGranularity = false; + result.granularity_ = 100; + return this; + } + + // optional int64 lat_offset = 19 [default = 0]; + public boolean hasLatOffset() { + return result.hasLatOffset(); + } + public long getLatOffset() { + return result.getLatOffset(); + } + public Builder setLatOffset(long value) { + result.hasLatOffset = true; + result.latOffset_ = value; + return this; + } + public Builder clearLatOffset() { + result.hasLatOffset = false; + result.latOffset_ = 0L; + return this; + } + + // optional int64 lon_offset = 20 [default = 0]; + public boolean hasLonOffset() { + return result.hasLonOffset(); + } + public long getLonOffset() { + return result.getLonOffset(); + } + public Builder setLonOffset(long value) { + result.hasLonOffset = true; + result.lonOffset_ = value; + return this; + } + public Builder clearLonOffset() { + result.hasLonOffset = false; + result.lonOffset_ = 0L; + return this; + } + + // optional int32 date_granularity = 18 [default = 1000]; + public boolean hasDateGranularity() { + return result.hasDateGranularity(); + } + public int getDateGranularity() { + return result.getDateGranularity(); + } + public Builder setDateGranularity(int value) { + result.hasDateGranularity = true; + result.dateGranularity_ = value; + return this; + } + public Builder clearDateGranularity() { + result.hasDateGranularity = false; + result.dateGranularity_ = 1000; + return this; + } + + // @@protoc_insertion_point(builder_scope:PrimitiveBlock) + } + + static { + defaultInstance = new PrimitiveBlock(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:PrimitiveBlock) + } + + public static final class PrimitiveGroup extends + com.google.protobuf.GeneratedMessage { + // Use PrimitiveGroup.newBuilder() to construct. + private PrimitiveGroup() { + initFields(); + } + private PrimitiveGroup(boolean noInit) {} + + private static final PrimitiveGroup defaultInstance; + public static PrimitiveGroup getDefaultInstance() { + return defaultInstance; + } + + public PrimitiveGroup getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_PrimitiveGroup_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_PrimitiveGroup_fieldAccessorTable; + } + + // repeated .Node nodes = 1; + public static final int NODES_FIELD_NUMBER = 1; + private java.util.List nodes_ = + java.util.Collections.emptyList(); + public java.util.List getNodesList() { + return nodes_; + } + public int getNodesCount() { return nodes_.size(); } + public crosby.binary.Osmformat.Node getNodes(int index) { + return nodes_.get(index); + } + + // optional .DenseNodes dense = 2; + public static final int DENSE_FIELD_NUMBER = 2; + private boolean hasDense; + private crosby.binary.Osmformat.DenseNodes dense_; + public boolean hasDense() { return hasDense; } + public crosby.binary.Osmformat.DenseNodes getDense() { return dense_; } + + // repeated .Way ways = 3; + public static final int WAYS_FIELD_NUMBER = 3; + private java.util.List ways_ = + java.util.Collections.emptyList(); + public java.util.List getWaysList() { + return ways_; + } + public int getWaysCount() { return ways_.size(); } + public crosby.binary.Osmformat.Way getWays(int index) { + return ways_.get(index); + } + + // repeated .Relation relations = 4; + public static final int RELATIONS_FIELD_NUMBER = 4; + private java.util.List relations_ = + java.util.Collections.emptyList(); + public java.util.List getRelationsList() { + return relations_; + } + public int getRelationsCount() { return relations_.size(); } + public crosby.binary.Osmformat.Relation getRelations(int index) { + return relations_.get(index); + } + + // repeated .ChangeSet changesets = 5; + public static final int CHANGESETS_FIELD_NUMBER = 5; + private java.util.List changesets_ = + java.util.Collections.emptyList(); + public java.util.List getChangesetsList() { + return changesets_; + } + public int getChangesetsCount() { return changesets_.size(); } + public crosby.binary.Osmformat.ChangeSet getChangesets(int index) { + return changesets_.get(index); + } + + private void initFields() { + dense_ = crosby.binary.Osmformat.DenseNodes.getDefaultInstance(); + } + public final boolean isInitialized() { + for (crosby.binary.Osmformat.Node element : getNodesList()) { + if (!element.isInitialized()) return false; + } + for (crosby.binary.Osmformat.Way element : getWaysList()) { + if (!element.isInitialized()) return false; + } + for (crosby.binary.Osmformat.Relation element : getRelationsList()) { + if (!element.isInitialized()) return false; + } + for (crosby.binary.Osmformat.ChangeSet element : getChangesetsList()) { + if (!element.isInitialized()) return false; + } + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + for (crosby.binary.Osmformat.Node element : getNodesList()) { + output.writeMessage(1, element); + } + if (hasDense()) { + output.writeMessage(2, getDense()); + } + for (crosby.binary.Osmformat.Way element : getWaysList()) { + output.writeMessage(3, element); + } + for (crosby.binary.Osmformat.Relation element : getRelationsList()) { + output.writeMessage(4, element); + } + for (crosby.binary.Osmformat.ChangeSet element : getChangesetsList()) { + output.writeMessage(5, element); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + for (crosby.binary.Osmformat.Node element : getNodesList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, element); + } + if (hasDense()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, getDense()); + } + for (crosby.binary.Osmformat.Way element : getWaysList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, element); + } + for (crosby.binary.Osmformat.Relation element : getRelationsList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, element); + } + for (crosby.binary.Osmformat.ChangeSet element : getChangesetsList()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, element); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.PrimitiveGroup parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.PrimitiveGroup parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.PrimitiveGroup prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.PrimitiveGroup result; + + // Construct using crosby.binary.Osmformat.PrimitiveGroup.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.PrimitiveGroup(); + return builder; + } + + protected crosby.binary.Osmformat.PrimitiveGroup internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.PrimitiveGroup(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.PrimitiveGroup.getDescriptor(); + } + + public crosby.binary.Osmformat.PrimitiveGroup getDefaultInstanceForType() { + return crosby.binary.Osmformat.PrimitiveGroup.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.PrimitiveGroup build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.PrimitiveGroup buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.PrimitiveGroup buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.nodes_ != java.util.Collections.EMPTY_LIST) { + result.nodes_ = + java.util.Collections.unmodifiableList(result.nodes_); + } + if (result.ways_ != java.util.Collections.EMPTY_LIST) { + result.ways_ = + java.util.Collections.unmodifiableList(result.ways_); + } + if (result.relations_ != java.util.Collections.EMPTY_LIST) { + result.relations_ = + java.util.Collections.unmodifiableList(result.relations_); + } + if (result.changesets_ != java.util.Collections.EMPTY_LIST) { + result.changesets_ = + java.util.Collections.unmodifiableList(result.changesets_); + } + crosby.binary.Osmformat.PrimitiveGroup returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.PrimitiveGroup) { + return mergeFrom((crosby.binary.Osmformat.PrimitiveGroup)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.PrimitiveGroup other) { + if (other == crosby.binary.Osmformat.PrimitiveGroup.getDefaultInstance()) return this; + if (!other.nodes_.isEmpty()) { + if (result.nodes_.isEmpty()) { + result.nodes_ = new java.util.ArrayList(); + } + result.nodes_.addAll(other.nodes_); + } + if (other.hasDense()) { + mergeDense(other.getDense()); + } + if (!other.ways_.isEmpty()) { + if (result.ways_.isEmpty()) { + result.ways_ = new java.util.ArrayList(); + } + result.ways_.addAll(other.ways_); + } + if (!other.relations_.isEmpty()) { + if (result.relations_.isEmpty()) { + result.relations_ = new java.util.ArrayList(); + } + result.relations_.addAll(other.relations_); + } + if (!other.changesets_.isEmpty()) { + if (result.changesets_.isEmpty()) { + result.changesets_ = new java.util.ArrayList(); + } + result.changesets_.addAll(other.changesets_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + crosby.binary.Osmformat.Node.Builder subBuilder = crosby.binary.Osmformat.Node.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addNodes(subBuilder.buildPartial()); + break; + } + case 18: { + crosby.binary.Osmformat.DenseNodes.Builder subBuilder = crosby.binary.Osmformat.DenseNodes.newBuilder(); + if (hasDense()) { + subBuilder.mergeFrom(getDense()); + } + input.readMessage(subBuilder, extensionRegistry); + setDense(subBuilder.buildPartial()); + break; + } + case 26: { + crosby.binary.Osmformat.Way.Builder subBuilder = crosby.binary.Osmformat.Way.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addWays(subBuilder.buildPartial()); + break; + } + case 34: { + crosby.binary.Osmformat.Relation.Builder subBuilder = crosby.binary.Osmformat.Relation.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addRelations(subBuilder.buildPartial()); + break; + } + case 42: { + crosby.binary.Osmformat.ChangeSet.Builder subBuilder = crosby.binary.Osmformat.ChangeSet.newBuilder(); + input.readMessage(subBuilder, extensionRegistry); + addChangesets(subBuilder.buildPartial()); + break; + } + } + } + } + + + // repeated .Node nodes = 1; + public java.util.List getNodesList() { + return java.util.Collections.unmodifiableList(result.nodes_); + } + public int getNodesCount() { + return result.getNodesCount(); + } + public crosby.binary.Osmformat.Node getNodes(int index) { + return result.getNodes(index); + } + public Builder setNodes(int index, crosby.binary.Osmformat.Node value) { + if (value == null) { + throw new NullPointerException(); + } + result.nodes_.set(index, value); + return this; + } + public Builder setNodes(int index, crosby.binary.Osmformat.Node.Builder builderForValue) { + result.nodes_.set(index, builderForValue.build()); + return this; + } + public Builder addNodes(crosby.binary.Osmformat.Node value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.nodes_.isEmpty()) { + result.nodes_ = new java.util.ArrayList(); + } + result.nodes_.add(value); + return this; + } + public Builder addNodes(crosby.binary.Osmformat.Node.Builder builderForValue) { + if (result.nodes_.isEmpty()) { + result.nodes_ = new java.util.ArrayList(); + } + result.nodes_.add(builderForValue.build()); + return this; + } + public Builder addAllNodes( + java.lang.Iterable values) { + if (result.nodes_.isEmpty()) { + result.nodes_ = new java.util.ArrayList(); + } + super.addAll(values, result.nodes_); + return this; + } + public Builder clearNodes() { + result.nodes_ = java.util.Collections.emptyList(); + return this; + } + + // optional .DenseNodes dense = 2; + public boolean hasDense() { + return result.hasDense(); + } + public crosby.binary.Osmformat.DenseNodes getDense() { + return result.getDense(); + } + public Builder setDense(crosby.binary.Osmformat.DenseNodes value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasDense = true; + result.dense_ = value; + return this; + } + public Builder setDense(crosby.binary.Osmformat.DenseNodes.Builder builderForValue) { + result.hasDense = true; + result.dense_ = builderForValue.build(); + return this; + } + public Builder mergeDense(crosby.binary.Osmformat.DenseNodes value) { + if (result.hasDense() && + result.dense_ != crosby.binary.Osmformat.DenseNodes.getDefaultInstance()) { + result.dense_ = + crosby.binary.Osmformat.DenseNodes.newBuilder(result.dense_).mergeFrom(value).buildPartial(); + } else { + result.dense_ = value; + } + result.hasDense = true; + return this; + } + public Builder clearDense() { + result.hasDense = false; + result.dense_ = crosby.binary.Osmformat.DenseNodes.getDefaultInstance(); + return this; + } + + // repeated .Way ways = 3; + public java.util.List getWaysList() { + return java.util.Collections.unmodifiableList(result.ways_); + } + public int getWaysCount() { + return result.getWaysCount(); + } + public crosby.binary.Osmformat.Way getWays(int index) { + return result.getWays(index); + } + public Builder setWays(int index, crosby.binary.Osmformat.Way value) { + if (value == null) { + throw new NullPointerException(); + } + result.ways_.set(index, value); + return this; + } + public Builder setWays(int index, crosby.binary.Osmformat.Way.Builder builderForValue) { + result.ways_.set(index, builderForValue.build()); + return this; + } + public Builder addWays(crosby.binary.Osmformat.Way value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.ways_.isEmpty()) { + result.ways_ = new java.util.ArrayList(); + } + result.ways_.add(value); + return this; + } + public Builder addWays(crosby.binary.Osmformat.Way.Builder builderForValue) { + if (result.ways_.isEmpty()) { + result.ways_ = new java.util.ArrayList(); + } + result.ways_.add(builderForValue.build()); + return this; + } + public Builder addAllWays( + java.lang.Iterable values) { + if (result.ways_.isEmpty()) { + result.ways_ = new java.util.ArrayList(); + } + super.addAll(values, result.ways_); + return this; + } + public Builder clearWays() { + result.ways_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .Relation relations = 4; + public java.util.List getRelationsList() { + return java.util.Collections.unmodifiableList(result.relations_); + } + public int getRelationsCount() { + return result.getRelationsCount(); + } + public crosby.binary.Osmformat.Relation getRelations(int index) { + return result.getRelations(index); + } + public Builder setRelations(int index, crosby.binary.Osmformat.Relation value) { + if (value == null) { + throw new NullPointerException(); + } + result.relations_.set(index, value); + return this; + } + public Builder setRelations(int index, crosby.binary.Osmformat.Relation.Builder builderForValue) { + result.relations_.set(index, builderForValue.build()); + return this; + } + public Builder addRelations(crosby.binary.Osmformat.Relation value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.relations_.isEmpty()) { + result.relations_ = new java.util.ArrayList(); + } + result.relations_.add(value); + return this; + } + public Builder addRelations(crosby.binary.Osmformat.Relation.Builder builderForValue) { + if (result.relations_.isEmpty()) { + result.relations_ = new java.util.ArrayList(); + } + result.relations_.add(builderForValue.build()); + return this; + } + public Builder addAllRelations( + java.lang.Iterable values) { + if (result.relations_.isEmpty()) { + result.relations_ = new java.util.ArrayList(); + } + super.addAll(values, result.relations_); + return this; + } + public Builder clearRelations() { + result.relations_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .ChangeSet changesets = 5; + public java.util.List getChangesetsList() { + return java.util.Collections.unmodifiableList(result.changesets_); + } + public int getChangesetsCount() { + return result.getChangesetsCount(); + } + public crosby.binary.Osmformat.ChangeSet getChangesets(int index) { + return result.getChangesets(index); + } + public Builder setChangesets(int index, crosby.binary.Osmformat.ChangeSet value) { + if (value == null) { + throw new NullPointerException(); + } + result.changesets_.set(index, value); + return this; + } + public Builder setChangesets(int index, crosby.binary.Osmformat.ChangeSet.Builder builderForValue) { + result.changesets_.set(index, builderForValue.build()); + return this; + } + public Builder addChangesets(crosby.binary.Osmformat.ChangeSet value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.changesets_.isEmpty()) { + result.changesets_ = new java.util.ArrayList(); + } + result.changesets_.add(value); + return this; + } + public Builder addChangesets(crosby.binary.Osmformat.ChangeSet.Builder builderForValue) { + if (result.changesets_.isEmpty()) { + result.changesets_ = new java.util.ArrayList(); + } + result.changesets_.add(builderForValue.build()); + return this; + } + public Builder addAllChangesets( + java.lang.Iterable values) { + if (result.changesets_.isEmpty()) { + result.changesets_ = new java.util.ArrayList(); + } + super.addAll(values, result.changesets_); + return this; + } + public Builder clearChangesets() { + result.changesets_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:PrimitiveGroup) + } + + static { + defaultInstance = new PrimitiveGroup(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:PrimitiveGroup) + } + + public static final class StringTable extends + com.google.protobuf.GeneratedMessage { + // Use StringTable.newBuilder() to construct. + private StringTable() { + initFields(); + } + private StringTable(boolean noInit) {} + + private static final StringTable defaultInstance; + public static StringTable getDefaultInstance() { + return defaultInstance; + } + + public StringTable getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_StringTable_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_StringTable_fieldAccessorTable; + } + + // repeated bytes s = 1; + public static final int S_FIELD_NUMBER = 1; + private java.util.List s_ = + java.util.Collections.emptyList(); + public java.util.List getSList() { + return s_; + } + public int getSCount() { return s_.size(); } + public com.google.protobuf.ByteString getS(int index) { + return s_.get(index); + } + + private void initFields() { + } + public final boolean isInitialized() { + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + for (com.google.protobuf.ByteString element : getSList()) { + output.writeBytes(1, element); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (com.google.protobuf.ByteString element : getSList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeBytesSizeNoTag(element); + } + size += dataSize; + size += 1 * getSList().size(); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.StringTable parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.StringTable parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.StringTable parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.StringTable parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.StringTable prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.StringTable result; + + // Construct using crosby.binary.Osmformat.StringTable.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.StringTable(); + return builder; + } + + protected crosby.binary.Osmformat.StringTable internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.StringTable(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.StringTable.getDescriptor(); + } + + public crosby.binary.Osmformat.StringTable getDefaultInstanceForType() { + return crosby.binary.Osmformat.StringTable.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.StringTable build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.StringTable buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.StringTable buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.s_ != java.util.Collections.EMPTY_LIST) { + result.s_ = + java.util.Collections.unmodifiableList(result.s_); + } + crosby.binary.Osmformat.StringTable returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.StringTable) { + return mergeFrom((crosby.binary.Osmformat.StringTable)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.StringTable other) { + if (other == crosby.binary.Osmformat.StringTable.getDefaultInstance()) return this; + if (!other.s_.isEmpty()) { + if (result.s_.isEmpty()) { + result.s_ = new java.util.ArrayList(); + } + result.s_.addAll(other.s_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 10: { + addS(input.readBytes()); + break; + } + } + } + } + + + // repeated bytes s = 1; + public java.util.List getSList() { + return java.util.Collections.unmodifiableList(result.s_); + } + public int getSCount() { + return result.getSCount(); + } + public com.google.protobuf.ByteString getS(int index) { + return result.getS(index); + } + public Builder setS(int index, com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + result.s_.set(index, value); + return this; + } + public Builder addS(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.s_.isEmpty()) { + result.s_ = new java.util.ArrayList(); + } + result.s_.add(value); + return this; + } + public Builder addAllS( + java.lang.Iterable values) { + if (result.s_.isEmpty()) { + result.s_ = new java.util.ArrayList(); + } + super.addAll(values, result.s_); + return this; + } + public Builder clearS() { + result.s_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:StringTable) + } + + static { + defaultInstance = new StringTable(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:StringTable) + } + + public static final class Info extends + com.google.protobuf.GeneratedMessage { + // Use Info.newBuilder() to construct. + private Info() { + initFields(); + } + private Info(boolean noInit) {} + + private static final Info defaultInstance; + public static Info getDefaultInstance() { + return defaultInstance; + } + + public Info getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_Info_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_Info_fieldAccessorTable; + } + + // optional int32 version = 1 [default = -1]; + public static final int VERSION_FIELD_NUMBER = 1; + private boolean hasVersion; + private int version_ = -1; + public boolean hasVersion() { return hasVersion; } + public int getVersion() { return version_; } + + // optional int64 timestamp = 2; + public static final int TIMESTAMP_FIELD_NUMBER = 2; + private boolean hasTimestamp; + private long timestamp_ = 0L; + public boolean hasTimestamp() { return hasTimestamp; } + public long getTimestamp() { return timestamp_; } + + // optional int64 changeset = 3; + public static final int CHANGESET_FIELD_NUMBER = 3; + private boolean hasChangeset; + private long changeset_ = 0L; + public boolean hasChangeset() { return hasChangeset; } + public long getChangeset() { return changeset_; } + + // optional int32 uid = 4; + public static final int UID_FIELD_NUMBER = 4; + private boolean hasUid; + private int uid_ = 0; + public boolean hasUid() { return hasUid; } + public int getUid() { return uid_; } + + // optional int32 user_sid = 5; + public static final int USER_SID_FIELD_NUMBER = 5; + private boolean hasUserSid; + private int userSid_ = 0; + public boolean hasUserSid() { return hasUserSid; } + public int getUserSid() { return userSid_; } + + private void initFields() { + } + public final boolean isInitialized() { + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasVersion()) { + output.writeInt32(1, getVersion()); + } + if (hasTimestamp()) { + output.writeInt64(2, getTimestamp()); + } + if (hasChangeset()) { + output.writeInt64(3, getChangeset()); + } + if (hasUid()) { + output.writeInt32(4, getUid()); + } + if (hasUserSid()) { + output.writeInt32(5, getUserSid()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasVersion()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, getVersion()); + } + if (hasTimestamp()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(2, getTimestamp()); + } + if (hasChangeset()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(3, getChangeset()); + } + if (hasUid()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(4, getUid()); + } + if (hasUserSid()) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(5, getUserSid()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.Info parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Info parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Info parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Info parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Info parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Info parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Info parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Info parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Info parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Info parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.Info prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.Info result; + + // Construct using crosby.binary.Osmformat.Info.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.Info(); + return builder; + } + + protected crosby.binary.Osmformat.Info internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.Info(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.Info.getDescriptor(); + } + + public crosby.binary.Osmformat.Info getDefaultInstanceForType() { + return crosby.binary.Osmformat.Info.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.Info build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.Info buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.Info buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + crosby.binary.Osmformat.Info returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.Info) { + return mergeFrom((crosby.binary.Osmformat.Info)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.Info other) { + if (other == crosby.binary.Osmformat.Info.getDefaultInstance()) return this; + if (other.hasVersion()) { + setVersion(other.getVersion()); + } + if (other.hasTimestamp()) { + setTimestamp(other.getTimestamp()); + } + if (other.hasChangeset()) { + setChangeset(other.getChangeset()); + } + if (other.hasUid()) { + setUid(other.getUid()); + } + if (other.hasUserSid()) { + setUserSid(other.getUserSid()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setVersion(input.readInt32()); + break; + } + case 16: { + setTimestamp(input.readInt64()); + break; + } + case 24: { + setChangeset(input.readInt64()); + break; + } + case 32: { + setUid(input.readInt32()); + break; + } + case 40: { + setUserSid(input.readInt32()); + break; + } + } + } + } + + + // optional int32 version = 1 [default = -1]; + public boolean hasVersion() { + return result.hasVersion(); + } + public int getVersion() { + return result.getVersion(); + } + public Builder setVersion(int value) { + result.hasVersion = true; + result.version_ = value; + return this; + } + public Builder clearVersion() { + result.hasVersion = false; + result.version_ = -1; + return this; + } + + // optional int64 timestamp = 2; + public boolean hasTimestamp() { + return result.hasTimestamp(); + } + public long getTimestamp() { + return result.getTimestamp(); + } + public Builder setTimestamp(long value) { + result.hasTimestamp = true; + result.timestamp_ = value; + return this; + } + public Builder clearTimestamp() { + result.hasTimestamp = false; + result.timestamp_ = 0L; + return this; + } + + // optional int64 changeset = 3; + public boolean hasChangeset() { + return result.hasChangeset(); + } + public long getChangeset() { + return result.getChangeset(); + } + public Builder setChangeset(long value) { + result.hasChangeset = true; + result.changeset_ = value; + return this; + } + public Builder clearChangeset() { + result.hasChangeset = false; + result.changeset_ = 0L; + return this; + } + + // optional int32 uid = 4; + public boolean hasUid() { + return result.hasUid(); + } + public int getUid() { + return result.getUid(); + } + public Builder setUid(int value) { + result.hasUid = true; + result.uid_ = value; + return this; + } + public Builder clearUid() { + result.hasUid = false; + result.uid_ = 0; + return this; + } + + // optional int32 user_sid = 5; + public boolean hasUserSid() { + return result.hasUserSid(); + } + public int getUserSid() { + return result.getUserSid(); + } + public Builder setUserSid(int value) { + result.hasUserSid = true; + result.userSid_ = value; + return this; + } + public Builder clearUserSid() { + result.hasUserSid = false; + result.userSid_ = 0; + return this; + } + + // @@protoc_insertion_point(builder_scope:Info) + } + + static { + defaultInstance = new Info(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:Info) + } + + public static final class DenseInfo extends + com.google.protobuf.GeneratedMessage { + // Use DenseInfo.newBuilder() to construct. + private DenseInfo() { + initFields(); + } + private DenseInfo(boolean noInit) {} + + private static final DenseInfo defaultInstance; + public static DenseInfo getDefaultInstance() { + return defaultInstance; + } + + public DenseInfo getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_DenseInfo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_DenseInfo_fieldAccessorTable; + } + + // repeated int32 version = 1 [packed = true]; + public static final int VERSION_FIELD_NUMBER = 1; + private java.util.List version_ = + java.util.Collections.emptyList(); + public java.util.List getVersionList() { + return version_; + } + public int getVersionCount() { return version_.size(); } + public int getVersion(int index) { + return version_.get(index); + } + private int versionMemoizedSerializedSize = -1; + + // repeated sint64 timestamp = 2 [packed = true]; + public static final int TIMESTAMP_FIELD_NUMBER = 2; + private java.util.List timestamp_ = + java.util.Collections.emptyList(); + public java.util.List getTimestampList() { + return timestamp_; + } + public int getTimestampCount() { return timestamp_.size(); } + public long getTimestamp(int index) { + return timestamp_.get(index); + } + private int timestampMemoizedSerializedSize = -1; + + // repeated sint64 changeset = 3 [packed = true]; + public static final int CHANGESET_FIELD_NUMBER = 3; + private java.util.List changeset_ = + java.util.Collections.emptyList(); + public java.util.List getChangesetList() { + return changeset_; + } + public int getChangesetCount() { return changeset_.size(); } + public long getChangeset(int index) { + return changeset_.get(index); + } + private int changesetMemoizedSerializedSize = -1; + + // repeated sint32 uid = 4 [packed = true]; + public static final int UID_FIELD_NUMBER = 4; + private java.util.List uid_ = + java.util.Collections.emptyList(); + public java.util.List getUidList() { + return uid_; + } + public int getUidCount() { return uid_.size(); } + public int getUid(int index) { + return uid_.get(index); + } + private int uidMemoizedSerializedSize = -1; + + // repeated sint32 user_sid = 5 [packed = true]; + public static final int USER_SID_FIELD_NUMBER = 5; + private java.util.List userSid_ = + java.util.Collections.emptyList(); + public java.util.List getUserSidList() { + return userSid_; + } + public int getUserSidCount() { return userSid_.size(); } + public int getUserSid(int index) { + return userSid_.get(index); + } + private int userSidMemoizedSerializedSize = -1; + + private void initFields() { + } + public final boolean isInitialized() { + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (getVersionList().size() > 0) { + output.writeRawVarint32(10); + output.writeRawVarint32(versionMemoizedSerializedSize); + } + for (int element : getVersionList()) { + output.writeInt32NoTag(element); + } + if (getTimestampList().size() > 0) { + output.writeRawVarint32(18); + output.writeRawVarint32(timestampMemoizedSerializedSize); + } + for (long element : getTimestampList()) { + output.writeSInt64NoTag(element); + } + if (getChangesetList().size() > 0) { + output.writeRawVarint32(26); + output.writeRawVarint32(changesetMemoizedSerializedSize); + } + for (long element : getChangesetList()) { + output.writeSInt64NoTag(element); + } + if (getUidList().size() > 0) { + output.writeRawVarint32(34); + output.writeRawVarint32(uidMemoizedSerializedSize); + } + for (int element : getUidList()) { + output.writeSInt32NoTag(element); + } + if (getUserSidList().size() > 0) { + output.writeRawVarint32(42); + output.writeRawVarint32(userSidMemoizedSerializedSize); + } + for (int element : getUserSidList()) { + output.writeSInt32NoTag(element); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int element : getVersionList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(element); + } + size += dataSize; + if (!getVersionList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + versionMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (long element : getTimestampList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getTimestampList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + timestampMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (long element : getChangesetList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getChangesetList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + changesetMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int element : getUidList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt32SizeNoTag(element); + } + size += dataSize; + if (!getUidList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + uidMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int element : getUserSidList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt32SizeNoTag(element); + } + size += dataSize; + if (!getUserSidList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + userSidMemoizedSerializedSize = dataSize; + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.DenseInfo parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.DenseInfo parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.DenseInfo parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.DenseInfo parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.DenseInfo prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.DenseInfo result; + + // Construct using crosby.binary.Osmformat.DenseInfo.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.DenseInfo(); + return builder; + } + + protected crosby.binary.Osmformat.DenseInfo internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.DenseInfo(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.DenseInfo.getDescriptor(); + } + + public crosby.binary.Osmformat.DenseInfo getDefaultInstanceForType() { + return crosby.binary.Osmformat.DenseInfo.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.DenseInfo build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.DenseInfo buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.DenseInfo buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.version_ != java.util.Collections.EMPTY_LIST) { + result.version_ = + java.util.Collections.unmodifiableList(result.version_); + } + if (result.timestamp_ != java.util.Collections.EMPTY_LIST) { + result.timestamp_ = + java.util.Collections.unmodifiableList(result.timestamp_); + } + if (result.changeset_ != java.util.Collections.EMPTY_LIST) { + result.changeset_ = + java.util.Collections.unmodifiableList(result.changeset_); + } + if (result.uid_ != java.util.Collections.EMPTY_LIST) { + result.uid_ = + java.util.Collections.unmodifiableList(result.uid_); + } + if (result.userSid_ != java.util.Collections.EMPTY_LIST) { + result.userSid_ = + java.util.Collections.unmodifiableList(result.userSid_); + } + crosby.binary.Osmformat.DenseInfo returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.DenseInfo) { + return mergeFrom((crosby.binary.Osmformat.DenseInfo)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.DenseInfo other) { + if (other == crosby.binary.Osmformat.DenseInfo.getDefaultInstance()) return this; + if (!other.version_.isEmpty()) { + if (result.version_.isEmpty()) { + result.version_ = new java.util.ArrayList(); + } + result.version_.addAll(other.version_); + } + if (!other.timestamp_.isEmpty()) { + if (result.timestamp_.isEmpty()) { + result.timestamp_ = new java.util.ArrayList(); + } + result.timestamp_.addAll(other.timestamp_); + } + if (!other.changeset_.isEmpty()) { + if (result.changeset_.isEmpty()) { + result.changeset_ = new java.util.ArrayList(); + } + result.changeset_.addAll(other.changeset_); + } + if (!other.uid_.isEmpty()) { + if (result.uid_.isEmpty()) { + result.uid_ = new java.util.ArrayList(); + } + result.uid_.addAll(other.uid_); + } + if (!other.userSid_.isEmpty()) { + if (result.userSid_.isEmpty()) { + result.userSid_ = new java.util.ArrayList(); + } + result.userSid_.addAll(other.userSid_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + addVersion(input.readInt32()); + break; + } + case 10: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addVersion(input.readInt32()); + } + input.popLimit(limit); + break; + } + case 16: { + addTimestamp(input.readSInt64()); + break; + } + case 18: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addTimestamp(input.readSInt64()); + } + input.popLimit(limit); + break; + } + case 24: { + addChangeset(input.readSInt64()); + break; + } + case 26: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addChangeset(input.readSInt64()); + } + input.popLimit(limit); + break; + } + case 32: { + addUid(input.readSInt32()); + break; + } + case 34: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addUid(input.readSInt32()); + } + input.popLimit(limit); + break; + } + case 40: { + addUserSid(input.readSInt32()); + break; + } + case 42: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addUserSid(input.readSInt32()); + } + input.popLimit(limit); + break; + } + } + } + } + + + // repeated int32 version = 1 [packed = true]; + public java.util.List getVersionList() { + return java.util.Collections.unmodifiableList(result.version_); + } + public int getVersionCount() { + return result.getVersionCount(); + } + public int getVersion(int index) { + return result.getVersion(index); + } + public Builder setVersion(int index, int value) { + result.version_.set(index, value); + return this; + } + public Builder addVersion(int value) { + if (result.version_.isEmpty()) { + result.version_ = new java.util.ArrayList(); + } + result.version_.add(value); + return this; + } + public Builder addAllVersion( + java.lang.Iterable values) { + if (result.version_.isEmpty()) { + result.version_ = new java.util.ArrayList(); + } + super.addAll(values, result.version_); + return this; + } + public Builder clearVersion() { + result.version_ = java.util.Collections.emptyList(); + return this; + } + + // repeated sint64 timestamp = 2 [packed = true]; + public java.util.List getTimestampList() { + return java.util.Collections.unmodifiableList(result.timestamp_); + } + public int getTimestampCount() { + return result.getTimestampCount(); + } + public long getTimestamp(int index) { + return result.getTimestamp(index); + } + public Builder setTimestamp(int index, long value) { + result.timestamp_.set(index, value); + return this; + } + public Builder addTimestamp(long value) { + if (result.timestamp_.isEmpty()) { + result.timestamp_ = new java.util.ArrayList(); + } + result.timestamp_.add(value); + return this; + } + public Builder addAllTimestamp( + java.lang.Iterable values) { + if (result.timestamp_.isEmpty()) { + result.timestamp_ = new java.util.ArrayList(); + } + super.addAll(values, result.timestamp_); + return this; + } + public Builder clearTimestamp() { + result.timestamp_ = java.util.Collections.emptyList(); + return this; + } + + // repeated sint64 changeset = 3 [packed = true]; + public java.util.List getChangesetList() { + return java.util.Collections.unmodifiableList(result.changeset_); + } + public int getChangesetCount() { + return result.getChangesetCount(); + } + public long getChangeset(int index) { + return result.getChangeset(index); + } + public Builder setChangeset(int index, long value) { + result.changeset_.set(index, value); + return this; + } + public Builder addChangeset(long value) { + if (result.changeset_.isEmpty()) { + result.changeset_ = new java.util.ArrayList(); + } + result.changeset_.add(value); + return this; + } + public Builder addAllChangeset( + java.lang.Iterable values) { + if (result.changeset_.isEmpty()) { + result.changeset_ = new java.util.ArrayList(); + } + super.addAll(values, result.changeset_); + return this; + } + public Builder clearChangeset() { + result.changeset_ = java.util.Collections.emptyList(); + return this; + } + + // repeated sint32 uid = 4 [packed = true]; + public java.util.List getUidList() { + return java.util.Collections.unmodifiableList(result.uid_); + } + public int getUidCount() { + return result.getUidCount(); + } + public int getUid(int index) { + return result.getUid(index); + } + public Builder setUid(int index, int value) { + result.uid_.set(index, value); + return this; + } + public Builder addUid(int value) { + if (result.uid_.isEmpty()) { + result.uid_ = new java.util.ArrayList(); + } + result.uid_.add(value); + return this; + } + public Builder addAllUid( + java.lang.Iterable values) { + if (result.uid_.isEmpty()) { + result.uid_ = new java.util.ArrayList(); + } + super.addAll(values, result.uid_); + return this; + } + public Builder clearUid() { + result.uid_ = java.util.Collections.emptyList(); + return this; + } + + // repeated sint32 user_sid = 5 [packed = true]; + public java.util.List getUserSidList() { + return java.util.Collections.unmodifiableList(result.userSid_); + } + public int getUserSidCount() { + return result.getUserSidCount(); + } + public int getUserSid(int index) { + return result.getUserSid(index); + } + public Builder setUserSid(int index, int value) { + result.userSid_.set(index, value); + return this; + } + public Builder addUserSid(int value) { + if (result.userSid_.isEmpty()) { + result.userSid_ = new java.util.ArrayList(); + } + result.userSid_.add(value); + return this; + } + public Builder addAllUserSid( + java.lang.Iterable values) { + if (result.userSid_.isEmpty()) { + result.userSid_ = new java.util.ArrayList(); + } + super.addAll(values, result.userSid_); + return this; + } + public Builder clearUserSid() { + result.userSid_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:DenseInfo) + } + + static { + defaultInstance = new DenseInfo(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:DenseInfo) + } + + public static final class ChangeSet extends + com.google.protobuf.GeneratedMessage { + // Use ChangeSet.newBuilder() to construct. + private ChangeSet() { + initFields(); + } + private ChangeSet(boolean noInit) {} + + private static final ChangeSet defaultInstance; + public static ChangeSet getDefaultInstance() { + return defaultInstance; + } + + public ChangeSet getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_ChangeSet_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_ChangeSet_fieldAccessorTable; + } + + // required int64 id = 1; + public static final int ID_FIELD_NUMBER = 1; + private boolean hasId; + private long id_ = 0L; + public boolean hasId() { return hasId; } + public long getId() { return id_; } + + private void initFields() { + } + public final boolean isInitialized() { + if (!hasId) return false; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasId()) { + output.writeInt64(1, getId()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasId()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(1, getId()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.ChangeSet parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.ChangeSet parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.ChangeSet parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.ChangeSet parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.ChangeSet prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.ChangeSet result; + + // Construct using crosby.binary.Osmformat.ChangeSet.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.ChangeSet(); + return builder; + } + + protected crosby.binary.Osmformat.ChangeSet internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.ChangeSet(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.ChangeSet.getDescriptor(); + } + + public crosby.binary.Osmformat.ChangeSet getDefaultInstanceForType() { + return crosby.binary.Osmformat.ChangeSet.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.ChangeSet build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.ChangeSet buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.ChangeSet buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + crosby.binary.Osmformat.ChangeSet returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.ChangeSet) { + return mergeFrom((crosby.binary.Osmformat.ChangeSet)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.ChangeSet other) { + if (other == crosby.binary.Osmformat.ChangeSet.getDefaultInstance()) return this; + if (other.hasId()) { + setId(other.getId()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setId(input.readInt64()); + break; + } + } + } + } + + + // required int64 id = 1; + public boolean hasId() { + return result.hasId(); + } + public long getId() { + return result.getId(); + } + public Builder setId(long value) { + result.hasId = true; + result.id_ = value; + return this; + } + public Builder clearId() { + result.hasId = false; + result.id_ = 0L; + return this; + } + + // @@protoc_insertion_point(builder_scope:ChangeSet) + } + + static { + defaultInstance = new ChangeSet(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:ChangeSet) + } + + public static final class Node extends + com.google.protobuf.GeneratedMessage { + // Use Node.newBuilder() to construct. + private Node() { + initFields(); + } + private Node(boolean noInit) {} + + private static final Node defaultInstance; + public static Node getDefaultInstance() { + return defaultInstance; + } + + public Node getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_Node_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_Node_fieldAccessorTable; + } + + // required sint64 id = 1; + public static final int ID_FIELD_NUMBER = 1; + private boolean hasId; + private long id_ = 0L; + public boolean hasId() { return hasId; } + public long getId() { return id_; } + + // repeated uint32 keys = 2 [packed = true]; + public static final int KEYS_FIELD_NUMBER = 2; + private java.util.List keys_ = + java.util.Collections.emptyList(); + public java.util.List getKeysList() { + return keys_; + } + public int getKeysCount() { return keys_.size(); } + public int getKeys(int index) { + return keys_.get(index); + } + private int keysMemoizedSerializedSize = -1; + + // repeated uint32 vals = 3 [packed = true]; + public static final int VALS_FIELD_NUMBER = 3; + private java.util.List vals_ = + java.util.Collections.emptyList(); + public java.util.List getValsList() { + return vals_; + } + public int getValsCount() { return vals_.size(); } + public int getVals(int index) { + return vals_.get(index); + } + private int valsMemoizedSerializedSize = -1; + + // optional .Info info = 4; + public static final int INFO_FIELD_NUMBER = 4; + private boolean hasInfo; + private crosby.binary.Osmformat.Info info_; + public boolean hasInfo() { return hasInfo; } + public crosby.binary.Osmformat.Info getInfo() { return info_; } + + // required sint64 lat = 8; + public static final int LAT_FIELD_NUMBER = 8; + private boolean hasLat; + private long lat_ = 0L; + public boolean hasLat() { return hasLat; } + public long getLat() { return lat_; } + + // required sint64 lon = 9; + public static final int LON_FIELD_NUMBER = 9; + private boolean hasLon; + private long lon_ = 0L; + public boolean hasLon() { return hasLon; } + public long getLon() { return lon_; } + + private void initFields() { + info_ = crosby.binary.Osmformat.Info.getDefaultInstance(); + } + public final boolean isInitialized() { + if (!hasId) return false; + if (!hasLat) return false; + if (!hasLon) return false; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasId()) { + output.writeSInt64(1, getId()); + } + if (getKeysList().size() > 0) { + output.writeRawVarint32(18); + output.writeRawVarint32(keysMemoizedSerializedSize); + } + for (int element : getKeysList()) { + output.writeUInt32NoTag(element); + } + if (getValsList().size() > 0) { + output.writeRawVarint32(26); + output.writeRawVarint32(valsMemoizedSerializedSize); + } + for (int element : getValsList()) { + output.writeUInt32NoTag(element); + } + if (hasInfo()) { + output.writeMessage(4, getInfo()); + } + if (hasLat()) { + output.writeSInt64(8, getLat()); + } + if (hasLon()) { + output.writeSInt64(9, getLon()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasId()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(1, getId()); + } + { + int dataSize = 0; + for (int element : getKeysList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeUInt32SizeNoTag(element); + } + size += dataSize; + if (!getKeysList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + keysMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int element : getValsList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeUInt32SizeNoTag(element); + } + size += dataSize; + if (!getValsList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + valsMemoizedSerializedSize = dataSize; + } + if (hasInfo()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, getInfo()); + } + if (hasLat()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(8, getLat()); + } + if (hasLon()) { + size += com.google.protobuf.CodedOutputStream + .computeSInt64Size(9, getLon()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.Node parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Node parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Node parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Node parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Node parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Node parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Node parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Node parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Node parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Node parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.Node prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.Node result; + + // Construct using crosby.binary.Osmformat.Node.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.Node(); + return builder; + } + + protected crosby.binary.Osmformat.Node internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.Node(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.Node.getDescriptor(); + } + + public crosby.binary.Osmformat.Node getDefaultInstanceForType() { + return crosby.binary.Osmformat.Node.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.Node build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.Node buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.Node buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.keys_ != java.util.Collections.EMPTY_LIST) { + result.keys_ = + java.util.Collections.unmodifiableList(result.keys_); + } + if (result.vals_ != java.util.Collections.EMPTY_LIST) { + result.vals_ = + java.util.Collections.unmodifiableList(result.vals_); + } + crosby.binary.Osmformat.Node returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.Node) { + return mergeFrom((crosby.binary.Osmformat.Node)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.Node other) { + if (other == crosby.binary.Osmformat.Node.getDefaultInstance()) return this; + if (other.hasId()) { + setId(other.getId()); + } + if (!other.keys_.isEmpty()) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + result.keys_.addAll(other.keys_); + } + if (!other.vals_.isEmpty()) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + result.vals_.addAll(other.vals_); + } + if (other.hasInfo()) { + mergeInfo(other.getInfo()); + } + if (other.hasLat()) { + setLat(other.getLat()); + } + if (other.hasLon()) { + setLon(other.getLon()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setId(input.readSInt64()); + break; + } + case 16: { + addKeys(input.readUInt32()); + break; + } + case 18: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addKeys(input.readUInt32()); + } + input.popLimit(limit); + break; + } + case 24: { + addVals(input.readUInt32()); + break; + } + case 26: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addVals(input.readUInt32()); + } + input.popLimit(limit); + break; + } + case 34: { + crosby.binary.Osmformat.Info.Builder subBuilder = crosby.binary.Osmformat.Info.newBuilder(); + if (hasInfo()) { + subBuilder.mergeFrom(getInfo()); + } + input.readMessage(subBuilder, extensionRegistry); + setInfo(subBuilder.buildPartial()); + break; + } + case 64: { + setLat(input.readSInt64()); + break; + } + case 72: { + setLon(input.readSInt64()); + break; + } + } + } + } + + + // required sint64 id = 1; + public boolean hasId() { + return result.hasId(); + } + public long getId() { + return result.getId(); + } + public Builder setId(long value) { + result.hasId = true; + result.id_ = value; + return this; + } + public Builder clearId() { + result.hasId = false; + result.id_ = 0L; + return this; + } + + // repeated uint32 keys = 2 [packed = true]; + public java.util.List getKeysList() { + return java.util.Collections.unmodifiableList(result.keys_); + } + public int getKeysCount() { + return result.getKeysCount(); + } + public int getKeys(int index) { + return result.getKeys(index); + } + public Builder setKeys(int index, int value) { + result.keys_.set(index, value); + return this; + } + public Builder addKeys(int value) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + result.keys_.add(value); + return this; + } + public Builder addAllKeys( + java.lang.Iterable values) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + super.addAll(values, result.keys_); + return this; + } + public Builder clearKeys() { + result.keys_ = java.util.Collections.emptyList(); + return this; + } + + // repeated uint32 vals = 3 [packed = true]; + public java.util.List getValsList() { + return java.util.Collections.unmodifiableList(result.vals_); + } + public int getValsCount() { + return result.getValsCount(); + } + public int getVals(int index) { + return result.getVals(index); + } + public Builder setVals(int index, int value) { + result.vals_.set(index, value); + return this; + } + public Builder addVals(int value) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + result.vals_.add(value); + return this; + } + public Builder addAllVals( + java.lang.Iterable values) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + super.addAll(values, result.vals_); + return this; + } + public Builder clearVals() { + result.vals_ = java.util.Collections.emptyList(); + return this; + } + + // optional .Info info = 4; + public boolean hasInfo() { + return result.hasInfo(); + } + public crosby.binary.Osmformat.Info getInfo() { + return result.getInfo(); + } + public Builder setInfo(crosby.binary.Osmformat.Info value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasInfo = true; + result.info_ = value; + return this; + } + public Builder setInfo(crosby.binary.Osmformat.Info.Builder builderForValue) { + result.hasInfo = true; + result.info_ = builderForValue.build(); + return this; + } + public Builder mergeInfo(crosby.binary.Osmformat.Info value) { + if (result.hasInfo() && + result.info_ != crosby.binary.Osmformat.Info.getDefaultInstance()) { + result.info_ = + crosby.binary.Osmformat.Info.newBuilder(result.info_).mergeFrom(value).buildPartial(); + } else { + result.info_ = value; + } + result.hasInfo = true; + return this; + } + public Builder clearInfo() { + result.hasInfo = false; + result.info_ = crosby.binary.Osmformat.Info.getDefaultInstance(); + return this; + } + + // required sint64 lat = 8; + public boolean hasLat() { + return result.hasLat(); + } + public long getLat() { + return result.getLat(); + } + public Builder setLat(long value) { + result.hasLat = true; + result.lat_ = value; + return this; + } + public Builder clearLat() { + result.hasLat = false; + result.lat_ = 0L; + return this; + } + + // required sint64 lon = 9; + public boolean hasLon() { + return result.hasLon(); + } + public long getLon() { + return result.getLon(); + } + public Builder setLon(long value) { + result.hasLon = true; + result.lon_ = value; + return this; + } + public Builder clearLon() { + result.hasLon = false; + result.lon_ = 0L; + return this; + } + + // @@protoc_insertion_point(builder_scope:Node) + } + + static { + defaultInstance = new Node(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:Node) + } + + public static final class DenseNodes extends + com.google.protobuf.GeneratedMessage { + // Use DenseNodes.newBuilder() to construct. + private DenseNodes() { + initFields(); + } + private DenseNodes(boolean noInit) {} + + private static final DenseNodes defaultInstance; + public static DenseNodes getDefaultInstance() { + return defaultInstance; + } + + public DenseNodes getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_DenseNodes_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_DenseNodes_fieldAccessorTable; + } + + // repeated sint64 id = 1 [packed = true]; + public static final int ID_FIELD_NUMBER = 1; + private java.util.List id_ = + java.util.Collections.emptyList(); + public java.util.List getIdList() { + return id_; + } + public int getIdCount() { return id_.size(); } + public long getId(int index) { + return id_.get(index); + } + private int idMemoizedSerializedSize = -1; + + // optional .DenseInfo denseinfo = 5; + public static final int DENSEINFO_FIELD_NUMBER = 5; + private boolean hasDenseinfo; + private crosby.binary.Osmformat.DenseInfo denseinfo_; + public boolean hasDenseinfo() { return hasDenseinfo; } + public crosby.binary.Osmformat.DenseInfo getDenseinfo() { return denseinfo_; } + + // repeated sint64 lat = 8 [packed = true]; + public static final int LAT_FIELD_NUMBER = 8; + private java.util.List lat_ = + java.util.Collections.emptyList(); + public java.util.List getLatList() { + return lat_; + } + public int getLatCount() { return lat_.size(); } + public long getLat(int index) { + return lat_.get(index); + } + private int latMemoizedSerializedSize = -1; + + // repeated sint64 lon = 9 [packed = true]; + public static final int LON_FIELD_NUMBER = 9; + private java.util.List lon_ = + java.util.Collections.emptyList(); + public java.util.List getLonList() { + return lon_; + } + public int getLonCount() { return lon_.size(); } + public long getLon(int index) { + return lon_.get(index); + } + private int lonMemoizedSerializedSize = -1; + + // repeated int32 keys_vals = 10 [packed = true]; + public static final int KEYS_VALS_FIELD_NUMBER = 10; + private java.util.List keysVals_ = + java.util.Collections.emptyList(); + public java.util.List getKeysValsList() { + return keysVals_; + } + public int getKeysValsCount() { return keysVals_.size(); } + public int getKeysVals(int index) { + return keysVals_.get(index); + } + private int keysValsMemoizedSerializedSize = -1; + + private void initFields() { + denseinfo_ = crosby.binary.Osmformat.DenseInfo.getDefaultInstance(); + } + public final boolean isInitialized() { + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (getIdList().size() > 0) { + output.writeRawVarint32(10); + output.writeRawVarint32(idMemoizedSerializedSize); + } + for (long element : getIdList()) { + output.writeSInt64NoTag(element); + } + if (hasDenseinfo()) { + output.writeMessage(5, getDenseinfo()); + } + if (getLatList().size() > 0) { + output.writeRawVarint32(66); + output.writeRawVarint32(latMemoizedSerializedSize); + } + for (long element : getLatList()) { + output.writeSInt64NoTag(element); + } + if (getLonList().size() > 0) { + output.writeRawVarint32(74); + output.writeRawVarint32(lonMemoizedSerializedSize); + } + for (long element : getLonList()) { + output.writeSInt64NoTag(element); + } + if (getKeysValsList().size() > 0) { + output.writeRawVarint32(82); + output.writeRawVarint32(keysValsMemoizedSerializedSize); + } + for (int element : getKeysValsList()) { + output.writeInt32NoTag(element); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (long element : getIdList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getIdList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + idMemoizedSerializedSize = dataSize; + } + if (hasDenseinfo()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, getDenseinfo()); + } + { + int dataSize = 0; + for (long element : getLatList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getLatList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + latMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (long element : getLonList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getLonList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + lonMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int element : getKeysValsList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(element); + } + size += dataSize; + if (!getKeysValsList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + keysValsMemoizedSerializedSize = dataSize; + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.DenseNodes parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.DenseNodes parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.DenseNodes parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.DenseNodes parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.DenseNodes prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.DenseNodes result; + + // Construct using crosby.binary.Osmformat.DenseNodes.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.DenseNodes(); + return builder; + } + + protected crosby.binary.Osmformat.DenseNodes internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.DenseNodes(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.DenseNodes.getDescriptor(); + } + + public crosby.binary.Osmformat.DenseNodes getDefaultInstanceForType() { + return crosby.binary.Osmformat.DenseNodes.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.DenseNodes build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.DenseNodes buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.DenseNodes buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.id_ != java.util.Collections.EMPTY_LIST) { + result.id_ = + java.util.Collections.unmodifiableList(result.id_); + } + if (result.lat_ != java.util.Collections.EMPTY_LIST) { + result.lat_ = + java.util.Collections.unmodifiableList(result.lat_); + } + if (result.lon_ != java.util.Collections.EMPTY_LIST) { + result.lon_ = + java.util.Collections.unmodifiableList(result.lon_); + } + if (result.keysVals_ != java.util.Collections.EMPTY_LIST) { + result.keysVals_ = + java.util.Collections.unmodifiableList(result.keysVals_); + } + crosby.binary.Osmformat.DenseNodes returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.DenseNodes) { + return mergeFrom((crosby.binary.Osmformat.DenseNodes)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.DenseNodes other) { + if (other == crosby.binary.Osmformat.DenseNodes.getDefaultInstance()) return this; + if (!other.id_.isEmpty()) { + if (result.id_.isEmpty()) { + result.id_ = new java.util.ArrayList(); + } + result.id_.addAll(other.id_); + } + if (other.hasDenseinfo()) { + mergeDenseinfo(other.getDenseinfo()); + } + if (!other.lat_.isEmpty()) { + if (result.lat_.isEmpty()) { + result.lat_ = new java.util.ArrayList(); + } + result.lat_.addAll(other.lat_); + } + if (!other.lon_.isEmpty()) { + if (result.lon_.isEmpty()) { + result.lon_ = new java.util.ArrayList(); + } + result.lon_.addAll(other.lon_); + } + if (!other.keysVals_.isEmpty()) { + if (result.keysVals_.isEmpty()) { + result.keysVals_ = new java.util.ArrayList(); + } + result.keysVals_.addAll(other.keysVals_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + addId(input.readSInt64()); + break; + } + case 10: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addId(input.readSInt64()); + } + input.popLimit(limit); + break; + } + case 42: { + crosby.binary.Osmformat.DenseInfo.Builder subBuilder = crosby.binary.Osmformat.DenseInfo.newBuilder(); + if (hasDenseinfo()) { + subBuilder.mergeFrom(getDenseinfo()); + } + input.readMessage(subBuilder, extensionRegistry); + setDenseinfo(subBuilder.buildPartial()); + break; + } + case 64: { + addLat(input.readSInt64()); + break; + } + case 66: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addLat(input.readSInt64()); + } + input.popLimit(limit); + break; + } + case 72: { + addLon(input.readSInt64()); + break; + } + case 74: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addLon(input.readSInt64()); + } + input.popLimit(limit); + break; + } + case 80: { + addKeysVals(input.readInt32()); + break; + } + case 82: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addKeysVals(input.readInt32()); + } + input.popLimit(limit); + break; + } + } + } + } + + + // repeated sint64 id = 1 [packed = true]; + public java.util.List getIdList() { + return java.util.Collections.unmodifiableList(result.id_); + } + public int getIdCount() { + return result.getIdCount(); + } + public long getId(int index) { + return result.getId(index); + } + public Builder setId(int index, long value) { + result.id_.set(index, value); + return this; + } + public Builder addId(long value) { + if (result.id_.isEmpty()) { + result.id_ = new java.util.ArrayList(); + } + result.id_.add(value); + return this; + } + public Builder addAllId( + java.lang.Iterable values) { + if (result.id_.isEmpty()) { + result.id_ = new java.util.ArrayList(); + } + super.addAll(values, result.id_); + return this; + } + public Builder clearId() { + result.id_ = java.util.Collections.emptyList(); + return this; + } + + // optional .DenseInfo denseinfo = 5; + public boolean hasDenseinfo() { + return result.hasDenseinfo(); + } + public crosby.binary.Osmformat.DenseInfo getDenseinfo() { + return result.getDenseinfo(); + } + public Builder setDenseinfo(crosby.binary.Osmformat.DenseInfo value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasDenseinfo = true; + result.denseinfo_ = value; + return this; + } + public Builder setDenseinfo(crosby.binary.Osmformat.DenseInfo.Builder builderForValue) { + result.hasDenseinfo = true; + result.denseinfo_ = builderForValue.build(); + return this; + } + public Builder mergeDenseinfo(crosby.binary.Osmformat.DenseInfo value) { + if (result.hasDenseinfo() && + result.denseinfo_ != crosby.binary.Osmformat.DenseInfo.getDefaultInstance()) { + result.denseinfo_ = + crosby.binary.Osmformat.DenseInfo.newBuilder(result.denseinfo_).mergeFrom(value).buildPartial(); + } else { + result.denseinfo_ = value; + } + result.hasDenseinfo = true; + return this; + } + public Builder clearDenseinfo() { + result.hasDenseinfo = false; + result.denseinfo_ = crosby.binary.Osmformat.DenseInfo.getDefaultInstance(); + return this; + } + + // repeated sint64 lat = 8 [packed = true]; + public java.util.List getLatList() { + return java.util.Collections.unmodifiableList(result.lat_); + } + public int getLatCount() { + return result.getLatCount(); + } + public long getLat(int index) { + return result.getLat(index); + } + public Builder setLat(int index, long value) { + result.lat_.set(index, value); + return this; + } + public Builder addLat(long value) { + if (result.lat_.isEmpty()) { + result.lat_ = new java.util.ArrayList(); + } + result.lat_.add(value); + return this; + } + public Builder addAllLat( + java.lang.Iterable values) { + if (result.lat_.isEmpty()) { + result.lat_ = new java.util.ArrayList(); + } + super.addAll(values, result.lat_); + return this; + } + public Builder clearLat() { + result.lat_ = java.util.Collections.emptyList(); + return this; + } + + // repeated sint64 lon = 9 [packed = true]; + public java.util.List getLonList() { + return java.util.Collections.unmodifiableList(result.lon_); + } + public int getLonCount() { + return result.getLonCount(); + } + public long getLon(int index) { + return result.getLon(index); + } + public Builder setLon(int index, long value) { + result.lon_.set(index, value); + return this; + } + public Builder addLon(long value) { + if (result.lon_.isEmpty()) { + result.lon_ = new java.util.ArrayList(); + } + result.lon_.add(value); + return this; + } + public Builder addAllLon( + java.lang.Iterable values) { + if (result.lon_.isEmpty()) { + result.lon_ = new java.util.ArrayList(); + } + super.addAll(values, result.lon_); + return this; + } + public Builder clearLon() { + result.lon_ = java.util.Collections.emptyList(); + return this; + } + + // repeated int32 keys_vals = 10 [packed = true]; + public java.util.List getKeysValsList() { + return java.util.Collections.unmodifiableList(result.keysVals_); + } + public int getKeysValsCount() { + return result.getKeysValsCount(); + } + public int getKeysVals(int index) { + return result.getKeysVals(index); + } + public Builder setKeysVals(int index, int value) { + result.keysVals_.set(index, value); + return this; + } + public Builder addKeysVals(int value) { + if (result.keysVals_.isEmpty()) { + result.keysVals_ = new java.util.ArrayList(); + } + result.keysVals_.add(value); + return this; + } + public Builder addAllKeysVals( + java.lang.Iterable values) { + if (result.keysVals_.isEmpty()) { + result.keysVals_ = new java.util.ArrayList(); + } + super.addAll(values, result.keysVals_); + return this; + } + public Builder clearKeysVals() { + result.keysVals_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:DenseNodes) + } + + static { + defaultInstance = new DenseNodes(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:DenseNodes) + } + + public static final class Way extends + com.google.protobuf.GeneratedMessage { + // Use Way.newBuilder() to construct. + private Way() { + initFields(); + } + private Way(boolean noInit) {} + + private static final Way defaultInstance; + public static Way getDefaultInstance() { + return defaultInstance; + } + + public Way getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_Way_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_Way_fieldAccessorTable; + } + + // required int64 id = 1; + public static final int ID_FIELD_NUMBER = 1; + private boolean hasId; + private long id_ = 0L; + public boolean hasId() { return hasId; } + public long getId() { return id_; } + + // repeated uint32 keys = 2 [packed = true]; + public static final int KEYS_FIELD_NUMBER = 2; + private java.util.List keys_ = + java.util.Collections.emptyList(); + public java.util.List getKeysList() { + return keys_; + } + public int getKeysCount() { return keys_.size(); } + public int getKeys(int index) { + return keys_.get(index); + } + private int keysMemoizedSerializedSize = -1; + + // repeated uint32 vals = 3 [packed = true]; + public static final int VALS_FIELD_NUMBER = 3; + private java.util.List vals_ = + java.util.Collections.emptyList(); + public java.util.List getValsList() { + return vals_; + } + public int getValsCount() { return vals_.size(); } + public int getVals(int index) { + return vals_.get(index); + } + private int valsMemoizedSerializedSize = -1; + + // optional .Info info = 4; + public static final int INFO_FIELD_NUMBER = 4; + private boolean hasInfo; + private crosby.binary.Osmformat.Info info_; + public boolean hasInfo() { return hasInfo; } + public crosby.binary.Osmformat.Info getInfo() { return info_; } + + // repeated sint64 refs = 8 [packed = true]; + public static final int REFS_FIELD_NUMBER = 8; + private java.util.List refs_ = + java.util.Collections.emptyList(); + public java.util.List getRefsList() { + return refs_; + } + public int getRefsCount() { return refs_.size(); } + public long getRefs(int index) { + return refs_.get(index); + } + private int refsMemoizedSerializedSize = -1; + + private void initFields() { + info_ = crosby.binary.Osmformat.Info.getDefaultInstance(); + } + public final boolean isInitialized() { + if (!hasId) return false; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasId()) { + output.writeInt64(1, getId()); + } + if (getKeysList().size() > 0) { + output.writeRawVarint32(18); + output.writeRawVarint32(keysMemoizedSerializedSize); + } + for (int element : getKeysList()) { + output.writeUInt32NoTag(element); + } + if (getValsList().size() > 0) { + output.writeRawVarint32(26); + output.writeRawVarint32(valsMemoizedSerializedSize); + } + for (int element : getValsList()) { + output.writeUInt32NoTag(element); + } + if (hasInfo()) { + output.writeMessage(4, getInfo()); + } + if (getRefsList().size() > 0) { + output.writeRawVarint32(66); + output.writeRawVarint32(refsMemoizedSerializedSize); + } + for (long element : getRefsList()) { + output.writeSInt64NoTag(element); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasId()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(1, getId()); + } + { + int dataSize = 0; + for (int element : getKeysList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeUInt32SizeNoTag(element); + } + size += dataSize; + if (!getKeysList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + keysMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int element : getValsList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeUInt32SizeNoTag(element); + } + size += dataSize; + if (!getValsList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + valsMemoizedSerializedSize = dataSize; + } + if (hasInfo()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, getInfo()); + } + { + int dataSize = 0; + for (long element : getRefsList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getRefsList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + refsMemoizedSerializedSize = dataSize; + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.Way parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Way parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Way parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Way parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Way parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Way parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Way parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Way parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Way parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Way parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.Way prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.Way result; + + // Construct using crosby.binary.Osmformat.Way.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.Way(); + return builder; + } + + protected crosby.binary.Osmformat.Way internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.Way(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.Way.getDescriptor(); + } + + public crosby.binary.Osmformat.Way getDefaultInstanceForType() { + return crosby.binary.Osmformat.Way.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.Way build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.Way buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.Way buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.keys_ != java.util.Collections.EMPTY_LIST) { + result.keys_ = + java.util.Collections.unmodifiableList(result.keys_); + } + if (result.vals_ != java.util.Collections.EMPTY_LIST) { + result.vals_ = + java.util.Collections.unmodifiableList(result.vals_); + } + if (result.refs_ != java.util.Collections.EMPTY_LIST) { + result.refs_ = + java.util.Collections.unmodifiableList(result.refs_); + } + crosby.binary.Osmformat.Way returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.Way) { + return mergeFrom((crosby.binary.Osmformat.Way)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.Way other) { + if (other == crosby.binary.Osmformat.Way.getDefaultInstance()) return this; + if (other.hasId()) { + setId(other.getId()); + } + if (!other.keys_.isEmpty()) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + result.keys_.addAll(other.keys_); + } + if (!other.vals_.isEmpty()) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + result.vals_.addAll(other.vals_); + } + if (other.hasInfo()) { + mergeInfo(other.getInfo()); + } + if (!other.refs_.isEmpty()) { + if (result.refs_.isEmpty()) { + result.refs_ = new java.util.ArrayList(); + } + result.refs_.addAll(other.refs_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setId(input.readInt64()); + break; + } + case 16: { + addKeys(input.readUInt32()); + break; + } + case 18: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addKeys(input.readUInt32()); + } + input.popLimit(limit); + break; + } + case 24: { + addVals(input.readUInt32()); + break; + } + case 26: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addVals(input.readUInt32()); + } + input.popLimit(limit); + break; + } + case 34: { + crosby.binary.Osmformat.Info.Builder subBuilder = crosby.binary.Osmformat.Info.newBuilder(); + if (hasInfo()) { + subBuilder.mergeFrom(getInfo()); + } + input.readMessage(subBuilder, extensionRegistry); + setInfo(subBuilder.buildPartial()); + break; + } + case 64: { + addRefs(input.readSInt64()); + break; + } + case 66: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addRefs(input.readSInt64()); + } + input.popLimit(limit); + break; + } + } + } + } + + + // required int64 id = 1; + public boolean hasId() { + return result.hasId(); + } + public long getId() { + return result.getId(); + } + public Builder setId(long value) { + result.hasId = true; + result.id_ = value; + return this; + } + public Builder clearId() { + result.hasId = false; + result.id_ = 0L; + return this; + } + + // repeated uint32 keys = 2 [packed = true]; + public java.util.List getKeysList() { + return java.util.Collections.unmodifiableList(result.keys_); + } + public int getKeysCount() { + return result.getKeysCount(); + } + public int getKeys(int index) { + return result.getKeys(index); + } + public Builder setKeys(int index, int value) { + result.keys_.set(index, value); + return this; + } + public Builder addKeys(int value) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + result.keys_.add(value); + return this; + } + public Builder addAllKeys( + java.lang.Iterable values) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + super.addAll(values, result.keys_); + return this; + } + public Builder clearKeys() { + result.keys_ = java.util.Collections.emptyList(); + return this; + } + + // repeated uint32 vals = 3 [packed = true]; + public java.util.List getValsList() { + return java.util.Collections.unmodifiableList(result.vals_); + } + public int getValsCount() { + return result.getValsCount(); + } + public int getVals(int index) { + return result.getVals(index); + } + public Builder setVals(int index, int value) { + result.vals_.set(index, value); + return this; + } + public Builder addVals(int value) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + result.vals_.add(value); + return this; + } + public Builder addAllVals( + java.lang.Iterable values) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + super.addAll(values, result.vals_); + return this; + } + public Builder clearVals() { + result.vals_ = java.util.Collections.emptyList(); + return this; + } + + // optional .Info info = 4; + public boolean hasInfo() { + return result.hasInfo(); + } + public crosby.binary.Osmformat.Info getInfo() { + return result.getInfo(); + } + public Builder setInfo(crosby.binary.Osmformat.Info value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasInfo = true; + result.info_ = value; + return this; + } + public Builder setInfo(crosby.binary.Osmformat.Info.Builder builderForValue) { + result.hasInfo = true; + result.info_ = builderForValue.build(); + return this; + } + public Builder mergeInfo(crosby.binary.Osmformat.Info value) { + if (result.hasInfo() && + result.info_ != crosby.binary.Osmformat.Info.getDefaultInstance()) { + result.info_ = + crosby.binary.Osmformat.Info.newBuilder(result.info_).mergeFrom(value).buildPartial(); + } else { + result.info_ = value; + } + result.hasInfo = true; + return this; + } + public Builder clearInfo() { + result.hasInfo = false; + result.info_ = crosby.binary.Osmformat.Info.getDefaultInstance(); + return this; + } + + // repeated sint64 refs = 8 [packed = true]; + public java.util.List getRefsList() { + return java.util.Collections.unmodifiableList(result.refs_); + } + public int getRefsCount() { + return result.getRefsCount(); + } + public long getRefs(int index) { + return result.getRefs(index); + } + public Builder setRefs(int index, long value) { + result.refs_.set(index, value); + return this; + } + public Builder addRefs(long value) { + if (result.refs_.isEmpty()) { + result.refs_ = new java.util.ArrayList(); + } + result.refs_.add(value); + return this; + } + public Builder addAllRefs( + java.lang.Iterable values) { + if (result.refs_.isEmpty()) { + result.refs_ = new java.util.ArrayList(); + } + super.addAll(values, result.refs_); + return this; + } + public Builder clearRefs() { + result.refs_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:Way) + } + + static { + defaultInstance = new Way(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:Way) + } + + public static final class Relation extends + com.google.protobuf.GeneratedMessage { + // Use Relation.newBuilder() to construct. + private Relation() { + initFields(); + } + private Relation(boolean noInit) {} + + private static final Relation defaultInstance; + public static Relation getDefaultInstance() { + return defaultInstance; + } + + public Relation getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return crosby.binary.Osmformat.internal_static_Relation_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return crosby.binary.Osmformat.internal_static_Relation_fieldAccessorTable; + } + + public enum MemberType + implements com.google.protobuf.ProtocolMessageEnum { + NODE(0, 0), + WAY(1, 1), + RELATION(2, 2), + ; + + + public final int getNumber() { return value; } + + public static MemberType valueOf(int value) { + switch (value) { + case 0: return NODE; + case 1: return WAY; + case 2: return RELATION; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public MemberType findValueByNumber(int number) { + return MemberType.valueOf(number) + ; } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return crosby.binary.Osmformat.Relation.getDescriptor().getEnumTypes().get(0); + } + + private static final MemberType[] VALUES = { + NODE, WAY, RELATION, + }; + public static MemberType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + private final int index; + private final int value; + private MemberType(int index, int value) { + this.index = index; + this.value = value; + } + + static { + crosby.binary.Osmformat.getDescriptor(); + } + + // @@protoc_insertion_point(enum_scope:Relation.MemberType) + } + + // required int64 id = 1; + public static final int ID_FIELD_NUMBER = 1; + private boolean hasId; + private long id_ = 0L; + public boolean hasId() { return hasId; } + public long getId() { return id_; } + + // repeated uint32 keys = 2 [packed = true]; + public static final int KEYS_FIELD_NUMBER = 2; + private java.util.List keys_ = + java.util.Collections.emptyList(); + public java.util.List getKeysList() { + return keys_; + } + public int getKeysCount() { return keys_.size(); } + public int getKeys(int index) { + return keys_.get(index); + } + private int keysMemoizedSerializedSize = -1; + + // repeated uint32 vals = 3 [packed = true]; + public static final int VALS_FIELD_NUMBER = 3; + private java.util.List vals_ = + java.util.Collections.emptyList(); + public java.util.List getValsList() { + return vals_; + } + public int getValsCount() { return vals_.size(); } + public int getVals(int index) { + return vals_.get(index); + } + private int valsMemoizedSerializedSize = -1; + + // optional .Info info = 4; + public static final int INFO_FIELD_NUMBER = 4; + private boolean hasInfo; + private crosby.binary.Osmformat.Info info_; + public boolean hasInfo() { return hasInfo; } + public crosby.binary.Osmformat.Info getInfo() { return info_; } + + // repeated int32 roles_sid = 8 [packed = true]; + public static final int ROLES_SID_FIELD_NUMBER = 8; + private java.util.List rolesSid_ = + java.util.Collections.emptyList(); + public java.util.List getRolesSidList() { + return rolesSid_; + } + public int getRolesSidCount() { return rolesSid_.size(); } + public int getRolesSid(int index) { + return rolesSid_.get(index); + } + private int rolesSidMemoizedSerializedSize = -1; + + // repeated sint64 memids = 9 [packed = true]; + public static final int MEMIDS_FIELD_NUMBER = 9; + private java.util.List memids_ = + java.util.Collections.emptyList(); + public java.util.List getMemidsList() { + return memids_; + } + public int getMemidsCount() { return memids_.size(); } + public long getMemids(int index) { + return memids_.get(index); + } + private int memidsMemoizedSerializedSize = -1; + + // repeated .Relation.MemberType types = 10 [packed = true]; + public static final int TYPES_FIELD_NUMBER = 10; + private java.util.List types_ = + java.util.Collections.emptyList(); + public java.util.List getTypesList() { + return types_; + } + public int getTypesCount() { return types_.size(); } + public crosby.binary.Osmformat.Relation.MemberType getTypes(int index) { + return types_.get(index); + } + private int typesMemoizedSerializedSize; + + private void initFields() { + info_ = crosby.binary.Osmformat.Info.getDefaultInstance(); + } + public final boolean isInitialized() { + if (!hasId) return false; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (hasId()) { + output.writeInt64(1, getId()); + } + if (getKeysList().size() > 0) { + output.writeRawVarint32(18); + output.writeRawVarint32(keysMemoizedSerializedSize); + } + for (int element : getKeysList()) { + output.writeUInt32NoTag(element); + } + if (getValsList().size() > 0) { + output.writeRawVarint32(26); + output.writeRawVarint32(valsMemoizedSerializedSize); + } + for (int element : getValsList()) { + output.writeUInt32NoTag(element); + } + if (hasInfo()) { + output.writeMessage(4, getInfo()); + } + if (getRolesSidList().size() > 0) { + output.writeRawVarint32(66); + output.writeRawVarint32(rolesSidMemoizedSerializedSize); + } + for (int element : getRolesSidList()) { + output.writeInt32NoTag(element); + } + if (getMemidsList().size() > 0) { + output.writeRawVarint32(74); + output.writeRawVarint32(memidsMemoizedSerializedSize); + } + for (long element : getMemidsList()) { + output.writeSInt64NoTag(element); + } + if (getTypesList().size() > 0) { + output.writeRawVarint32(82); + output.writeRawVarint32(typesMemoizedSerializedSize); + } + for (crosby.binary.Osmformat.Relation.MemberType element : getTypesList()) { + output.writeEnumNoTag(element.getNumber()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (hasId()) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(1, getId()); + } + { + int dataSize = 0; + for (int element : getKeysList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeUInt32SizeNoTag(element); + } + size += dataSize; + if (!getKeysList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + keysMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int element : getValsList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeUInt32SizeNoTag(element); + } + size += dataSize; + if (!getValsList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + valsMemoizedSerializedSize = dataSize; + } + if (hasInfo()) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, getInfo()); + } + { + int dataSize = 0; + for (int element : getRolesSidList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(element); + } + size += dataSize; + if (!getRolesSidList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + rolesSidMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (long element : getMemidsList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeSInt64SizeNoTag(element); + } + size += dataSize; + if (!getMemidsList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + memidsMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (crosby.binary.Osmformat.Relation.MemberType element : getTypesList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeEnumSizeNoTag(element.getNumber()); + } + size += dataSize; + if (!getTypesList().isEmpty()) { size += 1; + size += com.google.protobuf.CodedOutputStream + .computeRawVarint32Size(dataSize); + }typesMemoizedSerializedSize = dataSize; + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + public static crosby.binary.Osmformat.Relation parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Relation parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static crosby.binary.Osmformat.Relation parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static crosby.binary.Osmformat.Relation parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(crosby.binary.Osmformat.Relation prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder { + private crosby.binary.Osmformat.Relation result; + + // Construct using crosby.binary.Osmformat.Relation.newBuilder() + private Builder() {} + + private static Builder create() { + Builder builder = new Builder(); + builder.result = new crosby.binary.Osmformat.Relation(); + return builder; + } + + protected crosby.binary.Osmformat.Relation internalGetResult() { + return result; + } + + public Builder clear() { + if (result == null) { + throw new IllegalStateException( + "Cannot call clear() after build()."); + } + result = new crosby.binary.Osmformat.Relation(); + return this; + } + + public Builder clone() { + return create().mergeFrom(result); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return crosby.binary.Osmformat.Relation.getDescriptor(); + } + + public crosby.binary.Osmformat.Relation getDefaultInstanceForType() { + return crosby.binary.Osmformat.Relation.getDefaultInstance(); + } + + public boolean isInitialized() { + return result.isInitialized(); + } + public crosby.binary.Osmformat.Relation build() { + if (result != null && !isInitialized()) { + throw newUninitializedMessageException(result); + } + return buildPartial(); + } + + private crosby.binary.Osmformat.Relation buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + if (!isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return buildPartial(); + } + + public crosby.binary.Osmformat.Relation buildPartial() { + if (result == null) { + throw new IllegalStateException( + "build() has already been called on this Builder."); + } + if (result.keys_ != java.util.Collections.EMPTY_LIST) { + result.keys_ = + java.util.Collections.unmodifiableList(result.keys_); + } + if (result.vals_ != java.util.Collections.EMPTY_LIST) { + result.vals_ = + java.util.Collections.unmodifiableList(result.vals_); + } + if (result.rolesSid_ != java.util.Collections.EMPTY_LIST) { + result.rolesSid_ = + java.util.Collections.unmodifiableList(result.rolesSid_); + } + if (result.memids_ != java.util.Collections.EMPTY_LIST) { + result.memids_ = + java.util.Collections.unmodifiableList(result.memids_); + } + if (result.types_ != java.util.Collections.EMPTY_LIST) { + result.types_ = + java.util.Collections.unmodifiableList(result.types_); + } + crosby.binary.Osmformat.Relation returnMe = result; + result = null; + return returnMe; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof crosby.binary.Osmformat.Relation) { + return mergeFrom((crosby.binary.Osmformat.Relation)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(crosby.binary.Osmformat.Relation other) { + if (other == crosby.binary.Osmformat.Relation.getDefaultInstance()) return this; + if (other.hasId()) { + setId(other.getId()); + } + if (!other.keys_.isEmpty()) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + result.keys_.addAll(other.keys_); + } + if (!other.vals_.isEmpty()) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + result.vals_.addAll(other.vals_); + } + if (other.hasInfo()) { + mergeInfo(other.getInfo()); + } + if (!other.rolesSid_.isEmpty()) { + if (result.rolesSid_.isEmpty()) { + result.rolesSid_ = new java.util.ArrayList(); + } + result.rolesSid_.addAll(other.rolesSid_); + } + if (!other.memids_.isEmpty()) { + if (result.memids_.isEmpty()) { + result.memids_ = new java.util.ArrayList(); + } + result.memids_.addAll(other.memids_); + } + if (!other.types_.isEmpty()) { + if (result.types_.isEmpty()) { + result.types_ = new java.util.ArrayList(); + } + result.types_.addAll(other.types_); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + return this; + } + break; + } + case 8: { + setId(input.readInt64()); + break; + } + case 16: { + addKeys(input.readUInt32()); + break; + } + case 18: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addKeys(input.readUInt32()); + } + input.popLimit(limit); + break; + } + case 24: { + addVals(input.readUInt32()); + break; + } + case 26: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addVals(input.readUInt32()); + } + input.popLimit(limit); + break; + } + case 34: { + crosby.binary.Osmformat.Info.Builder subBuilder = crosby.binary.Osmformat.Info.newBuilder(); + if (hasInfo()) { + subBuilder.mergeFrom(getInfo()); + } + input.readMessage(subBuilder, extensionRegistry); + setInfo(subBuilder.buildPartial()); + break; + } + case 64: { + addRolesSid(input.readInt32()); + break; + } + case 66: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addRolesSid(input.readInt32()); + } + input.popLimit(limit); + break; + } + case 72: { + addMemids(input.readSInt64()); + break; + } + case 74: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + while (input.getBytesUntilLimit() > 0) { + addMemids(input.readSInt64()); + } + input.popLimit(limit); + break; + } + case 80: { + int rawValue = input.readEnum(); + crosby.binary.Osmformat.Relation.MemberType value = crosby.binary.Osmformat.Relation.MemberType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(10, rawValue); + } else { + addTypes(value); + } + break; + } + case 82: { + int length = input.readRawVarint32(); + int oldLimit = input.pushLimit(length); + while(input.getBytesUntilLimit() > 0) { + int rawValue = input.readEnum(); + crosby.binary.Osmformat.Relation.MemberType value = crosby.binary.Osmformat.Relation.MemberType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(10, rawValue); + } else { + addTypes(value); + } + } + input.popLimit(oldLimit); + break; + } + } + } + } + + + // required int64 id = 1; + public boolean hasId() { + return result.hasId(); + } + public long getId() { + return result.getId(); + } + public Builder setId(long value) { + result.hasId = true; + result.id_ = value; + return this; + } + public Builder clearId() { + result.hasId = false; + result.id_ = 0L; + return this; + } + + // repeated uint32 keys = 2 [packed = true]; + public java.util.List getKeysList() { + return java.util.Collections.unmodifiableList(result.keys_); + } + public int getKeysCount() { + return result.getKeysCount(); + } + public int getKeys(int index) { + return result.getKeys(index); + } + public Builder setKeys(int index, int value) { + result.keys_.set(index, value); + return this; + } + public Builder addKeys(int value) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + result.keys_.add(value); + return this; + } + public Builder addAllKeys( + java.lang.Iterable values) { + if (result.keys_.isEmpty()) { + result.keys_ = new java.util.ArrayList(); + } + super.addAll(values, result.keys_); + return this; + } + public Builder clearKeys() { + result.keys_ = java.util.Collections.emptyList(); + return this; + } + + // repeated uint32 vals = 3 [packed = true]; + public java.util.List getValsList() { + return java.util.Collections.unmodifiableList(result.vals_); + } + public int getValsCount() { + return result.getValsCount(); + } + public int getVals(int index) { + return result.getVals(index); + } + public Builder setVals(int index, int value) { + result.vals_.set(index, value); + return this; + } + public Builder addVals(int value) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + result.vals_.add(value); + return this; + } + public Builder addAllVals( + java.lang.Iterable values) { + if (result.vals_.isEmpty()) { + result.vals_ = new java.util.ArrayList(); + } + super.addAll(values, result.vals_); + return this; + } + public Builder clearVals() { + result.vals_ = java.util.Collections.emptyList(); + return this; + } + + // optional .Info info = 4; + public boolean hasInfo() { + return result.hasInfo(); + } + public crosby.binary.Osmformat.Info getInfo() { + return result.getInfo(); + } + public Builder setInfo(crosby.binary.Osmformat.Info value) { + if (value == null) { + throw new NullPointerException(); + } + result.hasInfo = true; + result.info_ = value; + return this; + } + public Builder setInfo(crosby.binary.Osmformat.Info.Builder builderForValue) { + result.hasInfo = true; + result.info_ = builderForValue.build(); + return this; + } + public Builder mergeInfo(crosby.binary.Osmformat.Info value) { + if (result.hasInfo() && + result.info_ != crosby.binary.Osmformat.Info.getDefaultInstance()) { + result.info_ = + crosby.binary.Osmformat.Info.newBuilder(result.info_).mergeFrom(value).buildPartial(); + } else { + result.info_ = value; + } + result.hasInfo = true; + return this; + } + public Builder clearInfo() { + result.hasInfo = false; + result.info_ = crosby.binary.Osmformat.Info.getDefaultInstance(); + return this; + } + + // repeated int32 roles_sid = 8 [packed = true]; + public java.util.List getRolesSidList() { + return java.util.Collections.unmodifiableList(result.rolesSid_); + } + public int getRolesSidCount() { + return result.getRolesSidCount(); + } + public int getRolesSid(int index) { + return result.getRolesSid(index); + } + public Builder setRolesSid(int index, int value) { + result.rolesSid_.set(index, value); + return this; + } + public Builder addRolesSid(int value) { + if (result.rolesSid_.isEmpty()) { + result.rolesSid_ = new java.util.ArrayList(); + } + result.rolesSid_.add(value); + return this; + } + public Builder addAllRolesSid( + java.lang.Iterable values) { + if (result.rolesSid_.isEmpty()) { + result.rolesSid_ = new java.util.ArrayList(); + } + super.addAll(values, result.rolesSid_); + return this; + } + public Builder clearRolesSid() { + result.rolesSid_ = java.util.Collections.emptyList(); + return this; + } + + // repeated sint64 memids = 9 [packed = true]; + public java.util.List getMemidsList() { + return java.util.Collections.unmodifiableList(result.memids_); + } + public int getMemidsCount() { + return result.getMemidsCount(); + } + public long getMemids(int index) { + return result.getMemids(index); + } + public Builder setMemids(int index, long value) { + result.memids_.set(index, value); + return this; + } + public Builder addMemids(long value) { + if (result.memids_.isEmpty()) { + result.memids_ = new java.util.ArrayList(); + } + result.memids_.add(value); + return this; + } + public Builder addAllMemids( + java.lang.Iterable values) { + if (result.memids_.isEmpty()) { + result.memids_ = new java.util.ArrayList(); + } + super.addAll(values, result.memids_); + return this; + } + public Builder clearMemids() { + result.memids_ = java.util.Collections.emptyList(); + return this; + } + + // repeated .Relation.MemberType types = 10 [packed = true]; + public java.util.List getTypesList() { + return java.util.Collections.unmodifiableList(result.types_); + } + public int getTypesCount() { + return result.getTypesCount(); + } + public crosby.binary.Osmformat.Relation.MemberType getTypes(int index) { + return result.getTypes(index); + } + public Builder setTypes(int index, crosby.binary.Osmformat.Relation.MemberType value) { + if (value == null) { + throw new NullPointerException(); + } + result.types_.set(index, value); + return this; + } + public Builder addTypes(crosby.binary.Osmformat.Relation.MemberType value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.types_.isEmpty()) { + result.types_ = new java.util.ArrayList(); + } + result.types_.add(value); + return this; + } + public Builder addAllTypes( + java.lang.Iterable values) { + if (result.types_.isEmpty()) { + result.types_ = new java.util.ArrayList(); + } + super.addAll(values, result.types_); + return this; + } + public Builder clearTypes() { + result.types_ = java.util.Collections.emptyList(); + return this; + } + + // @@protoc_insertion_point(builder_scope:Relation) + } + + static { + defaultInstance = new Relation(true); + crosby.binary.Osmformat.internalForceInit(); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:Relation) + } + + private static com.google.protobuf.Descriptors.Descriptor + internal_static_HeaderBlock_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_HeaderBlock_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_HeaderBBox_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_HeaderBBox_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_PrimitiveBlock_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_PrimitiveBlock_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_PrimitiveGroup_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_PrimitiveGroup_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_StringTable_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_StringTable_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_Info_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_Info_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_DenseInfo_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_DenseInfo_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_ChangeSet_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_ChangeSet_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_Node_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_Node_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_DenseNodes_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_DenseNodes_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_Way_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_Way_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_Relation_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_Relation_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\023src/osmformat.proto\"\206\001\n\013HeaderBlock\022\031\n" + + "\004bbox\030\001 \001(\0132\013.HeaderBBox\022\031\n\021required_fea" + + "tures\030\004 \003(\t\022\031\n\021optional_features\030\005 \003(\t\022\026" + + "\n\016writingprogram\030\020 \001(\t\022\016\n\006source\030\021 \001(\t\"F" + + "\n\nHeaderBBox\022\014\n\004left\030\001 \002(\022\022\r\n\005right\030\002 \002(" + + "\022\022\013\n\003top\030\003 \002(\022\022\016\n\006bottom\030\004 \002(\022\"\304\001\n\016Primi" + + "tiveBlock\022!\n\013stringtable\030\001 \002(\0132\014.StringT" + + "able\022\'\n\016primitivegroup\030\002 \003(\0132\017.Primitive" + + "Group\022\030\n\013granularity\030\021 \001(\005:\003100\022\025\n\nlat_o" + + "ffset\030\023 \001(\003:\0010\022\025\n\nlon_offset\030\024 \001(\003:\0010\022\036\n", + "\020date_granularity\030\022 \001(\005:\0041000\"\224\001\n\016Primit" + + "iveGroup\022\024\n\005nodes\030\001 \003(\0132\005.Node\022\032\n\005dense\030" + + "\002 \001(\0132\013.DenseNodes\022\022\n\004ways\030\003 \003(\0132\004.Way\022\034" + + "\n\trelations\030\004 \003(\0132\t.Relation\022\036\n\nchangese" + + "ts\030\005 \003(\0132\n.ChangeSet\"\030\n\013StringTable\022\t\n\001s" + + "\030\001 \003(\014\"`\n\004Info\022\023\n\007version\030\001 \001(\005:\002-1\022\021\n\tt" + + "imestamp\030\002 \001(\003\022\021\n\tchangeset\030\003 \001(\003\022\013\n\003uid" + + "\030\004 \001(\005\022\020\n\010user_sid\030\005 \001(\005\"u\n\tDenseInfo\022\023\n" + + "\007version\030\001 \003(\005B\002\020\001\022\025\n\ttimestamp\030\002 \003(\022B\002\020" + + "\001\022\025\n\tchangeset\030\003 \003(\022B\002\020\001\022\017\n\003uid\030\004 \003(\021B\002\020", + "\001\022\024\n\010user_sid\030\005 \003(\021B\002\020\001\"\027\n\tChangeSet\022\n\n\002" + + "id\030\001 \002(\003\"e\n\004Node\022\n\n\002id\030\001 \002(\022\022\020\n\004keys\030\002 \003" + + "(\rB\002\020\001\022\020\n\004vals\030\003 \003(\rB\002\020\001\022\023\n\004info\030\004 \001(\0132\005" + + ".Info\022\013\n\003lat\030\010 \002(\022\022\013\n\003lon\030\t \002(\022\"t\n\nDense" + + "Nodes\022\016\n\002id\030\001 \003(\022B\002\020\001\022\035\n\tdenseinfo\030\005 \001(\013" + + "2\n.DenseInfo\022\017\n\003lat\030\010 \003(\022B\002\020\001\022\017\n\003lon\030\t \003" + + "(\022B\002\020\001\022\025\n\tkeys_vals\030\n \003(\005B\002\020\001\"\\\n\003Way\022\n\n\002" + + "id\030\001 \002(\003\022\020\n\004keys\030\002 \003(\rB\002\020\001\022\020\n\004vals\030\003 \003(\r" + + "B\002\020\001\022\023\n\004info\030\004 \001(\0132\005.Info\022\020\n\004refs\030\010 \003(\022B" + + "\002\020\001\"\322\001\n\010Relation\022\n\n\002id\030\001 \002(\003\022\020\n\004keys\030\002 \003", + "(\rB\002\020\001\022\020\n\004vals\030\003 \003(\rB\002\020\001\022\023\n\004info\030\004 \001(\0132\005" + + ".Info\022\025\n\troles_sid\030\010 \003(\005B\002\020\001\022\022\n\006memids\030\t" + + " \003(\022B\002\020\001\022\'\n\005types\030\n \003(\0162\024.Relation.Membe" + + "rTypeB\002\020\001\"-\n\nMemberType\022\010\n\004NODE\020\000\022\007\n\003WAY" + + "\020\001\022\014\n\010RELATION\020\002B\017\n\rcrosby.binary" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + internal_static_HeaderBlock_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_HeaderBlock_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_HeaderBlock_descriptor, + new java.lang.String[] { "Bbox", "RequiredFeatures", "OptionalFeatures", "Writingprogram", "Source", }, + crosby.binary.Osmformat.HeaderBlock.class, + crosby.binary.Osmformat.HeaderBlock.Builder.class); + internal_static_HeaderBBox_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_HeaderBBox_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_HeaderBBox_descriptor, + new java.lang.String[] { "Left", "Right", "Top", "Bottom", }, + crosby.binary.Osmformat.HeaderBBox.class, + crosby.binary.Osmformat.HeaderBBox.Builder.class); + internal_static_PrimitiveBlock_descriptor = + getDescriptor().getMessageTypes().get(2); + internal_static_PrimitiveBlock_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_PrimitiveBlock_descriptor, + new java.lang.String[] { "Stringtable", "Primitivegroup", "Granularity", "LatOffset", "LonOffset", "DateGranularity", }, + crosby.binary.Osmformat.PrimitiveBlock.class, + crosby.binary.Osmformat.PrimitiveBlock.Builder.class); + internal_static_PrimitiveGroup_descriptor = + getDescriptor().getMessageTypes().get(3); + internal_static_PrimitiveGroup_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_PrimitiveGroup_descriptor, + new java.lang.String[] { "Nodes", "Dense", "Ways", "Relations", "Changesets", }, + crosby.binary.Osmformat.PrimitiveGroup.class, + crosby.binary.Osmformat.PrimitiveGroup.Builder.class); + internal_static_StringTable_descriptor = + getDescriptor().getMessageTypes().get(4); + internal_static_StringTable_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_StringTable_descriptor, + new java.lang.String[] { "S", }, + crosby.binary.Osmformat.StringTable.class, + crosby.binary.Osmformat.StringTable.Builder.class); + internal_static_Info_descriptor = + getDescriptor().getMessageTypes().get(5); + internal_static_Info_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_Info_descriptor, + new java.lang.String[] { "Version", "Timestamp", "Changeset", "Uid", "UserSid", }, + crosby.binary.Osmformat.Info.class, + crosby.binary.Osmformat.Info.Builder.class); + internal_static_DenseInfo_descriptor = + getDescriptor().getMessageTypes().get(6); + internal_static_DenseInfo_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_DenseInfo_descriptor, + new java.lang.String[] { "Version", "Timestamp", "Changeset", "Uid", "UserSid", }, + crosby.binary.Osmformat.DenseInfo.class, + crosby.binary.Osmformat.DenseInfo.Builder.class); + internal_static_ChangeSet_descriptor = + getDescriptor().getMessageTypes().get(7); + internal_static_ChangeSet_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_ChangeSet_descriptor, + new java.lang.String[] { "Id", }, + crosby.binary.Osmformat.ChangeSet.class, + crosby.binary.Osmformat.ChangeSet.Builder.class); + internal_static_Node_descriptor = + getDescriptor().getMessageTypes().get(8); + internal_static_Node_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_Node_descriptor, + new java.lang.String[] { "Id", "Keys", "Vals", "Info", "Lat", "Lon", }, + crosby.binary.Osmformat.Node.class, + crosby.binary.Osmformat.Node.Builder.class); + internal_static_DenseNodes_descriptor = + getDescriptor().getMessageTypes().get(9); + internal_static_DenseNodes_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_DenseNodes_descriptor, + new java.lang.String[] { "Id", "Denseinfo", "Lat", "Lon", "KeysVals", }, + crosby.binary.Osmformat.DenseNodes.class, + crosby.binary.Osmformat.DenseNodes.Builder.class); + internal_static_Way_descriptor = + getDescriptor().getMessageTypes().get(10); + internal_static_Way_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_Way_descriptor, + new java.lang.String[] { "Id", "Keys", "Vals", "Info", "Refs", }, + crosby.binary.Osmformat.Way.class, + crosby.binary.Osmformat.Way.Builder.class); + internal_static_Relation_descriptor = + getDescriptor().getMessageTypes().get(11); + internal_static_Relation_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_Relation_descriptor, + new java.lang.String[] { "Id", "Keys", "Vals", "Info", "RolesSid", "Memids", "Types", }, + crosby.binary.Osmformat.Relation.class, + crosby.binary.Osmformat.Relation.Builder.class); + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + } + + public static void internalForceInit() {} + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/DataExtractionOSM/src/crosby/binary/StringTable.java b/DataExtractionOSM/src/crosby/binary/StringTable.java new file mode 100644 index 0000000000..e8287205c7 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/StringTable.java @@ -0,0 +1,86 @@ +package crosby.binary; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; + +import com.google.protobuf.ByteString; + +/** + * Class for mapping a set of strings to integers, giving frequently occuring + * strings small integers. + */ +public class StringTable { + public StringTable() { + clear(); + } + + private HashMap counts; + private HashMap stringmap; + private String set[]; + + public void incr(String s) { + if (counts.containsKey(s)) { + counts.put(s, new Integer(counts.get(s).intValue() + 1)); + } else { + counts.put(s, new Integer(1)); + } + } + + /** After the stringtable has been built, return the offset of a string in it. + * + * Note, value '0' is reserved for use as a delimiter and will not be returned. + * @param s + * @return + */ + public int getIndex(String s) { + return stringmap.get(s).intValue(); + } + + public void finish() { + Comparator comparator = new Comparator() { + @Override + public int compare(final String s1, String s2) { + int diff = counts.get(s2) - counts.get(s1); + return diff; + } + }; + + set = counts.keySet().toArray(new String[0]); + if (set.length > 0) { + // Sort based on the frequency. + Arrays.sort(set, comparator); + // Each group of keys that serializes to the same number of bytes is + // sorted lexiconographically. + // to maximize deflate compression. + + // Don't sort the first array. There's not likely to be much benefit, and we want frequent values to be small. + //Arrays.sort(set, Math.min(0, set.length-1), Math.min(1 << 7, set.length-1)); + + Arrays.sort(set, Math.min(1 << 7, set.length-1), Math.min(1 << 14, + set.length-1)); + Arrays.sort(set, Math.min(1 << 14, set.length-1), Math.min(1 << 21, + set.length-1), comparator); + } + stringmap = new HashMap(2 * set.length); + for (int i = 0; i < set.length; i++) { + stringmap.put(set[i], new Integer(i+1)); // Index 0 is reserved for use as a delimiter. + } + counts = null; + } + + public void clear() { + counts = new HashMap(100); + stringmap = null; + set = null; + } + + public Osmformat.StringTable.Builder serialize() { + Osmformat.StringTable.Builder builder = Osmformat.StringTable + .newBuilder(); + builder.addS(ByteString.copyFromUtf8("")); // Add a unused string at offset 0 which is used as a delimiter. + for (int i = 0; i < set.length; i++) + builder.addS(ByteString.copyFromUtf8(set[i])); + return builder; + } +} diff --git a/DataExtractionOSM/src/crosby/binary/file/BlockInputStream.java b/DataExtractionOSM/src/crosby/binary/file/BlockInputStream.java new file mode 100644 index 0000000000..238c201bff --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/BlockInputStream.java @@ -0,0 +1,26 @@ +package crosby.binary.file; + +import java.io.IOException; +import java.io.InputStream; + +public class BlockInputStream { + // TODO: Should be seekable input stream! + public BlockInputStream(InputStream input, BlockReaderAdapter adaptor) { + this.input = input; + this.adaptor = adaptor; + } + + public void process() throws IOException { + while (input.available() > 0) { + FileBlock.process(input, adaptor); + } + adaptor.complete(); + } + + public void close() throws IOException { + input.close(); + } + + InputStream input; + BlockReaderAdapter adaptor; +} diff --git a/DataExtractionOSM/src/crosby/binary/file/BlockOutputStream.java b/DataExtractionOSM/src/crosby/binary/file/BlockOutputStream.java new file mode 100644 index 0000000000..d45c20acd4 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/BlockOutputStream.java @@ -0,0 +1,58 @@ +package crosby.binary.file; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + + +public class BlockOutputStream { + public enum CompressFlags { + NONE, DEFLATE + } + + + public BlockOutputStream(OutputStream output) { + this.outwrite = new DataOutputStream(output); + this.compression = CompressFlags.DEFLATE; + } + + public void setCompress(CompressFlags flag) { + compression = flag; + } + + public void setCompress(String s) { + if (s.equals("none")) + compression = CompressFlags.NONE; + else if (s.equals("deflate")) + compression = CompressFlags.DEFLATE; + else + throw new Error("Unknown compression type: " + s); + } + + /** Write a block with the stream's default compression flag */ + public void write(FileBlock block) throws IOException { + this.write(block, compression); + } + + /** Write a specific block with a specific compression flags */ + public void write(FileBlock block, CompressFlags compression) + throws IOException { + FileBlockPosition ref = block.writeTo(outwrite, compression); + writtenblocks.add(ref); + } + + public void flush() throws IOException { + outwrite.flush(); + } + + public void close() throws IOException { + outwrite.flush(); + outwrite.close(); + } + + OutputStream outwrite; + List writtenblocks = new ArrayList(); + CompressFlags compression; +} diff --git a/DataExtractionOSM/src/crosby/binary/file/BlockReaderAdapter.java b/DataExtractionOSM/src/crosby/binary/file/BlockReaderAdapter.java new file mode 100644 index 0000000000..4ef4759e1e --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/BlockReaderAdapter.java @@ -0,0 +1,23 @@ +package crosby.binary.file; + +/** An adaptor that receives blocks from an input stream */ +public interface BlockReaderAdapter { + /** + * Does the reader understand this block? Does it want the data in it? + * + * A reference contains the metadata about a block and can saved --- or + * stored ---- for future random access. However, during a strea read of the + * file, does the user want this block? + * + * handleBlock will be called on all blocks that are not skipped, in file + * order. + * + * */ + boolean skipBlock(FileBlockPosition message); + + /** Called with the data in the block. */ + void handleBlock(FileBlock message); + + /** Called when the file is fully read. */ + void complete(); +} diff --git a/DataExtractionOSM/src/crosby/binary/file/FileBlock.java b/DataExtractionOSM/src/crosby/binary/file/FileBlock.java new file mode 100644 index 0000000000..0161fcca32 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/FileBlock.java @@ -0,0 +1,128 @@ +package crosby.binary.file; + +import java.io.DataOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.zip.Deflater; + +import com.google.protobuf.ByteString; + +import crosby.binary.Fileformat; +import crosby.binary.Fileformat.BlockHeader; +import crosby.binary.file.BlockOutputStream.CompressFlags; + +/** A full fileblock object contains both the metadata and data of a fileblock */ +public class FileBlock extends FileBlockBase { + /** Contains the contents of a block for use or further processing */ + ByteString data; // serialized Format.Blob + + /** Don't be noisy unless the warning occurs somewhat often */ + static int warncount = 0; + + private FileBlock(String type, ByteString blob, ByteString indexdata) { + super(type, indexdata); + this.data = blob; + } + + public static FileBlock newInstance(String type, ByteString blob, + ByteString indexdata) { + if (blob != null && blob.size() > MAX_BODY_SIZE/2) { + System.err.println("Warning: Fileblock has body size too large and may be considered corrupt"); + if (blob != null && blob.size() > MAX_BODY_SIZE-1024*1024) { + throw new Error("This file has too many entities in a block. Parsers will reject it."); + } + } + if (indexdata != null && indexdata.size() > MAX_HEADER_SIZE/2) { + System.err.println("Warning: Fileblock has indexdata too large and may be considered corrupt"); + if (indexdata != null && indexdata.size() > MAX_HEADER_SIZE-512) { + throw new Error("This file header is too large. Parsers will reject it."); + } + } + return new FileBlock(type, blob, indexdata); + } + + protected void deflateInto(crosby.binary.Fileformat.Blob.Builder blobbuilder) { + int size = data.size(); + Deflater deflater = new Deflater(); + deflater.setInput(data.toByteArray()); + deflater.finish(); + byte out[] = new byte[size]; + deflater.deflate(out); + + if (!deflater.finished()) { + // Buffer wasn't long enough. Be noisy. + ++warncount; + if (warncount > 10 && warncount%100 == 0) + System.out.println("Compressed buffers are too short, causing extra copy"); + + int newLength = size + size / 64 + 16; + byte[] copy = new byte[newLength]; + System.arraycopy(out, 0, copy, 0, Math.min(out.length, newLength)); + out = copy; + deflater.deflate(out, deflater.getTotalOut(), out.length - deflater.getTotalOut()); + if (!deflater.finished()) { + throw new Error("Internal error in compressor"); + } + } + ByteString compressed = ByteString.copyFrom(out, 0, deflater + .getTotalOut()); + blobbuilder.setZlibData(compressed); + deflater.end(); + } + + public FileBlockPosition writeTo(OutputStream outwrite, CompressFlags flags) + throws IOException { + BlockHeader.Builder builder = Fileformat.BlockHeader + .newBuilder(); + if (indexdata != null) + builder.setIndexdata(indexdata); + builder.setType(type); + + Fileformat.Blob.Builder blobbuilder = Fileformat.Blob.newBuilder(); + if (flags == CompressFlags.NONE) { + blobbuilder.setRaw(data); + } else { + blobbuilder.setRawSize(data.size()); + if (flags == CompressFlags.DEFLATE) + deflateInto(blobbuilder); + else + throw new Error("Compression flag not understood"); + } + Fileformat.Blob blob = blobbuilder.build(); + + builder.setDatasize(blob.getSerializedSize()); + Fileformat.BlockHeader message = builder.build(); + int size = message.getSerializedSize(); + + // System.out.format("Outputed header size %d bytes, header of %d bytes, and blob of %d bytes\n", + // size,message.getSerializedSize(),blob.getSerializedSize()); + (new DataOutputStream(outwrite)).writeInt(size); + message.writeTo(outwrite); + long offset = -1; + + if (outwrite instanceof FileOutputStream) + offset = ((FileOutputStream) outwrite).getChannel().position(); + + blob.writeTo(outwrite); + return FileBlockPosition.newInstance(this, offset, size); + } + + /** Reads or skips a fileblock. */ + static void process(InputStream input, BlockReaderAdapter callback) + throws IOException { + FileBlockHead fileblock = FileBlockHead.readHead(input); + if (callback.skipBlock(fileblock)) { + // System.out.format("Attempt to skip %d bytes\n",header.getDatasize()); + fileblock.skipContents(input); + } else { + callback.handleBlock(fileblock.readContents(input)); + } + } + + public ByteString getData() { + return data; + } +} diff --git a/DataExtractionOSM/src/crosby/binary/file/FileBlockBase.java b/DataExtractionOSM/src/crosby/binary/file/FileBlockBase.java new file mode 100644 index 0000000000..c5492814f2 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/FileBlockBase.java @@ -0,0 +1,41 @@ +package crosby.binary.file; + +import com.google.protobuf.ByteString; + +/** + * Base class that contains the metadata about a fileblock. + * + * Subclasses of this include additional fields, such as byte offsets that let a + * fileblock be read in a random-access fashion, or the data itself. + * + * @author crosby + * + */ +public class FileBlockBase { + + /** If a block header is bigger than this, fail. We use excessively large header size as an indication of corrupt files */ + static final int MAX_HEADER_SIZE = 64*1024; + /** If a block's size is bigger than this, fail. We use excessively large block sizes as an indication of corrupt files */ + static final int MAX_BODY_SIZE = 32*1024*1024; + + protected FileBlockBase(String type, ByteString indexdata) { + this.type = type; + this.indexdata = indexdata; + } + + /** Identifies the type of the data within a block */ + protected final String type; + /** + * Block metadata, stored in the index block and as a prefix for every + * block. + */ + protected final ByteString indexdata; + + public String getType() { + return type; + } + + public ByteString getIndexData() { + return indexdata; + } +} diff --git a/DataExtractionOSM/src/crosby/binary/file/FileBlockHead.java b/DataExtractionOSM/src/crosby/binary/file/FileBlockHead.java new file mode 100644 index 0000000000..6942b93104 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/FileBlockHead.java @@ -0,0 +1,80 @@ +package crosby.binary.file; + +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import com.google.protobuf.ByteString; + +import crosby.binary.Fileformat; + +/** + * Intermediate representation of the header of a fileblock when a set of + * fileblocks is read as in a stream. The data in the fileblock must be either + * skipped (where the returned value is a reference to the fileblock) or parsed. + * + * @author crosby + * + */ +public class FileBlockHead extends FileBlockReference { + protected FileBlockHead(String type, ByteString indexdata) { + super(type, indexdata); + } + + /** + * Read the header. After reading the header, either the contents must be + * skipped or read + */ + static FileBlockHead readHead(InputStream input) throws IOException { + DataInputStream datinput = new DataInputStream(input); + int headersize = datinput.readInt(); + // System.out.format("Header size %d %x\n",headersize,headersize); + if (headersize > MAX_HEADER_SIZE) { + throw new FileFormatException("Unexpectedly long header "+MAX_HEADER_SIZE+ " bytes. Possibly corrupt file."); + } + + byte buf[] = new byte[headersize]; + datinput.readFully(buf); + // System.out.format("Read buffer for header of %d bytes\n",buf.length); + Fileformat.BlockHeader header = Fileformat.BlockHeader + .parseFrom(buf); + FileBlockHead fileblock = new FileBlockHead(header.getType(), header + .getIndexdata()); + + fileblock.datasize = header.getDatasize(); + if (header.getDatasize() > MAX_BODY_SIZE) { + throw new FileFormatException("Unexpectedly long body "+MAX_BODY_SIZE+ " bytes. Possibly corrupt file."); + } + + fileblock.input = input; + if (input instanceof FileInputStream) + fileblock.data_offset = ((FileInputStream) input).getChannel() + .position(); + + return fileblock; + } + + /** + * Assumes the stream is positioned over at the start of the data, skip over + * it. + * + * @throws IOException + */ + void skipContents(InputStream input) throws IOException { + if (input.skip(getDatasize()) != getDatasize()) + assert false : "SHORT READ"; + } + + /** + * Assumes the stream is positioned over at the start of the data, read it + * and return the complete FileBlock + * + * @throws IOException + */ + FileBlock readContents(InputStream input) throws IOException { + DataInputStream datinput = new DataInputStream(input); + byte buf[] = new byte[getDatasize()]; + datinput.readFully(buf); + return parseData(buf); + } +} diff --git a/DataExtractionOSM/src/crosby/binary/file/FileBlockPosition.java b/DataExtractionOSM/src/crosby/binary/file/FileBlockPosition.java new file mode 100644 index 0000000000..f563d16727 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/FileBlockPosition.java @@ -0,0 +1,95 @@ +package crosby.binary.file; + +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; + +import crosby.binary.Fileformat; + +/** + * Stores the position in the stream of a fileblock so that it can be easily + * read in a random-access fashion. + * + * We can turn this into a 'real' block by appropriately seeking into the file + * and doing a 'read'. + * + * */ +public class FileBlockPosition extends FileBlockBase { + protected FileBlockPosition(String type, ByteString indexdata) { + super(type, indexdata); + } + + /** Parse out and decompress the data part of a fileblock helper function. */ + FileBlock parseData(byte buf[]) throws InvalidProtocolBufferException { + FileBlock out = FileBlock.newInstance(type, null, indexdata); + Fileformat.Blob blob = Fileformat.Blob.parseFrom(buf); + if (blob.hasRaw()) { + out.data = blob.getRaw(); + } else if (blob.hasZlibData()) { + byte buf2[] = new byte[blob.getRawSize()]; + Inflater decompresser = new Inflater(); + decompresser.setInput(blob.getZlibData().toByteArray()); + // decompresser.getRemaining(); + try { + decompresser.inflate(buf2); + } catch (DataFormatException e) { + e.printStackTrace(); + throw new Error(e); + } + assert (decompresser.finished()); + decompresser.end(); + out.data = ByteString.copyFrom(buf2); + } + return out; + } + + public int getDatasize() { + return datasize; + } + + /* + * Given any form of fileblock and an offset/length value, return a + * reference that can be used to dereference and read the contents. + */ + static FileBlockPosition newInstance(FileBlockBase base, long offset, + int length) { + FileBlockPosition out = new FileBlockPosition(base.type, base.indexdata); + out.datasize = length; + out.data_offset = offset; + return out; + } + + public FileBlock read(InputStream input) throws IOException { + if (input instanceof FileInputStream) { + ((FileInputStream) input).getChannel().position(data_offset); + byte buf[] = new byte[getDatasize()]; + (new DataInputStream(input)).readFully(buf); + return parseData(buf); + } else { + throw new Error("Random access binary reads require seekability"); + } + } + + /** + * TODO: Convert this reference into a serialized representation that can be + * stored. + */ + public ByteString serialize() { + throw new Error("TODO"); + } + + /** TODO: Parse a serialized representation of this block reference */ + static FileBlockPosition parseFrom(ByteString b) { + throw new Error("TODO"); + } + + protected int datasize; + /** Offset into the file of the data part of the block */ + long data_offset; +} diff --git a/DataExtractionOSM/src/crosby/binary/file/FileBlockReference.java b/DataExtractionOSM/src/crosby/binary/file/FileBlockReference.java new file mode 100644 index 0000000000..508d0c4978 --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/FileBlockReference.java @@ -0,0 +1,37 @@ +package crosby.binary.file; + +import java.io.IOException; +import java.io.InputStream; + +import com.google.protobuf.ByteString; + +/** + * A FileBlockPosition that remembers what file this is so that it can simply be + * dereferenced + */ +public class FileBlockReference extends FileBlockPosition { + + /** + * Convenience cache for storing the input this reference is contained + * within so that it can be cached + */ + protected InputStream input; + + protected FileBlockReference(String type, ByteString indexdata) { + super(type, indexdata); + } + + public FileBlock read() throws IOException { + return read(input); + } + + static FileBlockPosition newInstance(FileBlockBase base, InputStream input, + long offset, int length) { + FileBlockReference out = new FileBlockReference(base.type, + base.indexdata); + out.datasize = length; + out.data_offset = offset; + out.input = input; + return out; + } +} diff --git a/DataExtractionOSM/src/crosby/binary/file/FileFormatException.java b/DataExtractionOSM/src/crosby/binary/file/FileFormatException.java new file mode 100644 index 0000000000..178c958b9a --- /dev/null +++ b/DataExtractionOSM/src/crosby/binary/file/FileFormatException.java @@ -0,0 +1,16 @@ +package crosby.binary.file; + +import java.io.IOException; + +public class FileFormatException extends IOException { + + public FileFormatException(String string) { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = -8128010128748910923L; + +} diff --git a/DataExtractionOSM/src/fileformat.proto b/DataExtractionOSM/src/fileformat.proto new file mode 100644 index 0000000000..bbd818bae9 --- /dev/null +++ b/DataExtractionOSM/src/fileformat.proto @@ -0,0 +1,28 @@ +option java_package = "crosby.binary"; +//protoc --java_out=../.. fileformat.proto + + +// +// STORAGE LAYER: Storing primitives. +// + +message Blob { + optional bytes raw = 1; // No compression + optional int32 raw_size = 2; // When compressed, the uncompressed size + // Possible compressed versions of the data. + optional bytes zlib_data = 3; + optional bytes lzma_data = 4; + optional bytes bzip2_data = 5; +} + +/* A file contains an sequence of fileblock headers, each prefixed by +their length, followed by a data block containing the actual data. +types staring with a "_" are reserved. + +*/ + +message BlockHeader { + required string type = 1; + optional bytes indexdata = 2; + required int32 datasize = 3; +} diff --git a/DataExtractionOSM/src/gnu/trove/TFloatCollection.java b/DataExtractionOSM/src/gnu/trove/TFloatCollection.java new file mode 100644 index 0000000000..7117d064a1 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/TFloatCollection.java @@ -0,0 +1,316 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + +import gnu.trove.iterator.TFloatIterator; +import gnu.trove.procedure.TFloatProcedure; + +import java.util.Collection; +import java.io.Serializable; + +/** + * An interface that mimics the Collection interface. + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + * @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $ + */ + +public interface TFloatCollection extends Serializable { + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + float getNoEntryValue(); + + + /** + * Returns the number of elements in this collection (its cardinality). If this + * collection contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this collection (its cardinality) + */ + int size(); + + + /** + * Returns true if this collection contains no elements. + * + * @return true if this collection contains no elements + */ + boolean isEmpty(); + + + /** + * Returns true if this collection contains the specified element. + * + * @param entry an float value + * @return true if the collection contains the specified element. + */ + boolean contains( float entry ); + + + /** + * Creates an iterator over the values of the collection. The iterator + * supports element deletion. + * + * @return an TFloatIterator value + */ + TFloatIterator iterator(); + + + /** + * Returns an array containing all of the elements in this collection. + * If this collection makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the + * elements in the same order. + * + *

The returned array will be "safe" in that no references to it + * are maintained by this collection. (In other words, this method must + * allocate a new array even if this collection is backed by an array). + * The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this collection + */ + float[] toArray(); + + + /** + * Returns an array containing elements in this collection. + * + *

If this collection fits in the specified array with room to spare + * (i.e., the array has more elements than this collection), the element in + * the array immediately following the end of the collection is collection to + * {@link #getNoEntryValue()}. (This is useful in determining + * the length of this collection only if the caller knows that this + * collection does not contain any elements representing null.) + * + *

If the native array is smaller than the collection size, + * the array will be filled with elements in Iterator order + * until it is full and exclude the remainder. + * + *

If this collection makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the elements + * in the same order. + * + * @param dest the array into which the elements of this collection are to be + * stored. + * @return an float[] containing all the elements in this collection + * @throws NullPointerException if the specified array is null + */ + float[] toArray( float[] dest ); + + + /** + * Inserts a value into the collection. + * + * @param entry a float value + * @return true if the collection was modified by the add operation + */ + boolean add( float entry ); + + + /** + * Removes entry from the collection. + * + * @param entry an float value + * @return true if the collection was modified by the remove operation. + */ + boolean remove( float entry ); + + + /** + * Tests the collection to determine if all of the elements in + * collection are present. + * + * @param collection a Collection value + * @return true if all elements were present in the collection. + */ + boolean containsAll( Collection collection ); + + + /** + * Tests the collection to determine if all of the elements in + * TFloatCollection are present. + * + * @param collection a TFloatCollection value + * @return true if all elements were present in the collection. + */ + boolean containsAll( TFloatCollection collection ); + + + /** + * Tests the collection to determine if all of the elements in + * array are present. + * + * @param array as array of float primitives. + * @return true if all elements were present in the collection. + */ + boolean containsAll( float[] array ); + + + /** + * Adds all of the elements in collection to the collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( Collection collection ); + + + /** + * Adds all of the elements in the TFloatCollection to the collection. + * + * @param collection a TFloatCollection value + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( TFloatCollection collection ); + + + /** + * Adds all of the elements in the array to the collection. + * + * @param array a array of float primitives. + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( float[] array ); + + + /** + * Removes any values in the collection which are not contained in + * collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( Collection collection ); + + + /** + * Removes any values in the collection which are not contained in + * TFloatCollection. + * + * @param collection a TFloatCollection value + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( TFloatCollection collection ); + + + /** + * Removes any values in the collection which are not contained in + * array. + * + * @param array an array of float primitives. + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( float[] array ); + + + /** + * Removes all of the elements in collection from the collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( Collection collection ); + + + /** + * Removes all of the elements in TFloatCollection from the collection. + * + * @param collection a TFloatCollection value + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( TFloatCollection collection ); + + + /** + * Removes all of the elements in array from the collection. + * + * @param array an array of float primitives. + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( float[] array ); + + + /** + * Empties the collection. + */ + void clear(); + + + /** + * Executes procedure for each element in the collection. + * + * @param procedure a TFloatProcedure value + * @return false if the loop over the collection terminated because + * the procedure returned false for some value. + */ + boolean forEach( TFloatProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this collection for equality. Returns + * true if the specified object is also a collection, the two collection + * have the same size, and every member of the specified collection is + * contained in this collection (or equivalently, every member of this collection is + * contained in the specified collection). This definition ensures that the + * equals method works properly across different implementations of the + * collection interface. + * + * @param o object to be compared for equality with this collection + * @return true if the specified object is equal to this collection + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this collection. The hash code of a collection is + * defined to be the sum of the hash codes of the elements in the collection. + * This ensures that s1.equals(s2) implies that + * s1.hashCode()==s2.hashCode() for any two collection s1 + * and s2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this collection + * @see Object#equals(Object) + * @see Collection#equals(Object) + */ + int hashCode(); + + +} // TFloatCollection diff --git a/DataExtractionOSM/src/gnu/trove/TIntCollection.java b/DataExtractionOSM/src/gnu/trove/TIntCollection.java new file mode 100644 index 0000000000..4b71cc2fba --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/TIntCollection.java @@ -0,0 +1,316 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + +import gnu.trove.iterator.TIntIterator; +import gnu.trove.procedure.TIntProcedure; + +import java.util.Collection; +import java.io.Serializable; + +/** + * An interface that mimics the Collection interface. + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + * @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $ + */ + +public interface TIntCollection extends Serializable { + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + int getNoEntryValue(); + + + /** + * Returns the number of elements in this collection (its cardinality). If this + * collection contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this collection (its cardinality) + */ + int size(); + + + /** + * Returns true if this collection contains no elements. + * + * @return true if this collection contains no elements + */ + boolean isEmpty(); + + + /** + * Returns true if this collection contains the specified element. + * + * @param entry an int value + * @return true if the collection contains the specified element. + */ + boolean contains( int entry ); + + + /** + * Creates an iterator over the values of the collection. The iterator + * supports element deletion. + * + * @return an TIntIterator value + */ + TIntIterator iterator(); + + + /** + * Returns an array containing all of the elements in this collection. + * If this collection makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the + * elements in the same order. + * + *

The returned array will be "safe" in that no references to it + * are maintained by this collection. (In other words, this method must + * allocate a new array even if this collection is backed by an array). + * The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this collection + */ + int[] toArray(); + + + /** + * Returns an array containing elements in this collection. + * + *

If this collection fits in the specified array with room to spare + * (i.e., the array has more elements than this collection), the element in + * the array immediately following the end of the collection is collection to + * {@link #getNoEntryValue()}. (This is useful in determining + * the length of this collection only if the caller knows that this + * collection does not contain any elements representing null.) + * + *

If the native array is smaller than the collection size, + * the array will be filled with elements in Iterator order + * until it is full and exclude the remainder. + * + *

If this collection makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the elements + * in the same order. + * + * @param dest the array into which the elements of this collection are to be + * stored. + * @return an int[] containing all the elements in this collection + * @throws NullPointerException if the specified array is null + */ + int[] toArray( int[] dest ); + + + /** + * Inserts a value into the collection. + * + * @param entry a int value + * @return true if the collection was modified by the add operation + */ + boolean add( int entry ); + + + /** + * Removes entry from the collection. + * + * @param entry an int value + * @return true if the collection was modified by the remove operation. + */ + boolean remove( int entry ); + + + /** + * Tests the collection to determine if all of the elements in + * collection are present. + * + * @param collection a Collection value + * @return true if all elements were present in the collection. + */ + boolean containsAll( Collection collection ); + + + /** + * Tests the collection to determine if all of the elements in + * TIntCollection are present. + * + * @param collection a TIntCollection value + * @return true if all elements were present in the collection. + */ + boolean containsAll( TIntCollection collection ); + + + /** + * Tests the collection to determine if all of the elements in + * array are present. + * + * @param array as array of int primitives. + * @return true if all elements were present in the collection. + */ + boolean containsAll( int[] array ); + + + /** + * Adds all of the elements in collection to the collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( Collection collection ); + + + /** + * Adds all of the elements in the TIntCollection to the collection. + * + * @param collection a TIntCollection value + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( TIntCollection collection ); + + + /** + * Adds all of the elements in the array to the collection. + * + * @param array a array of int primitives. + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( int[] array ); + + + /** + * Removes any values in the collection which are not contained in + * collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( Collection collection ); + + + /** + * Removes any values in the collection which are not contained in + * TIntCollection. + * + * @param collection a TIntCollection value + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( TIntCollection collection ); + + + /** + * Removes any values in the collection which are not contained in + * array. + * + * @param array an array of int primitives. + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( int[] array ); + + + /** + * Removes all of the elements in collection from the collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( Collection collection ); + + + /** + * Removes all of the elements in TIntCollection from the collection. + * + * @param collection a TIntCollection value + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( TIntCollection collection ); + + + /** + * Removes all of the elements in array from the collection. + * + * @param array an array of int primitives. + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( int[] array ); + + + /** + * Empties the collection. + */ + void clear(); + + + /** + * Executes procedure for each element in the collection. + * + * @param procedure a TIntProcedure value + * @return false if the loop over the collection terminated because + * the procedure returned false for some value. + */ + boolean forEach( TIntProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this collection for equality. Returns + * true if the specified object is also a collection, the two collection + * have the same size, and every member of the specified collection is + * contained in this collection (or equivalently, every member of this collection is + * contained in the specified collection). This definition ensures that the + * equals method works properly across different implementations of the + * collection interface. + * + * @param o object to be compared for equality with this collection + * @return true if the specified object is equal to this collection + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this collection. The hash code of a collection is + * defined to be the sum of the hash codes of the elements in the collection. + * This ensures that s1.equals(s2) implies that + * s1.hashCode()==s2.hashCode() for any two collection s1 + * and s2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this collection + * @see Object#equals(Object) + * @see Collection#equals(Object) + */ + int hashCode(); + + +} // TIntCollection diff --git a/DataExtractionOSM/src/gnu/trove/TLongCollection.java b/DataExtractionOSM/src/gnu/trove/TLongCollection.java new file mode 100644 index 0000000000..d169391dab --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/TLongCollection.java @@ -0,0 +1,316 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + +import gnu.trove.iterator.TLongIterator; +import gnu.trove.procedure.TLongProcedure; + +import java.util.Collection; +import java.io.Serializable; + +/** + * An interface that mimics the Collection interface. + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + * @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $ + */ + +public interface TLongCollection extends Serializable { + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + long getNoEntryValue(); + + + /** + * Returns the number of elements in this collection (its cardinality). If this + * collection contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this collection (its cardinality) + */ + int size(); + + + /** + * Returns true if this collection contains no elements. + * + * @return true if this collection contains no elements + */ + boolean isEmpty(); + + + /** + * Returns true if this collection contains the specified element. + * + * @param entry an long value + * @return true if the collection contains the specified element. + */ + boolean contains( long entry ); + + + /** + * Creates an iterator over the values of the collection. The iterator + * supports element deletion. + * + * @return an TLongIterator value + */ + TLongIterator iterator(); + + + /** + * Returns an array containing all of the elements in this collection. + * If this collection makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the + * elements in the same order. + * + *

The returned array will be "safe" in that no references to it + * are maintained by this collection. (In other words, this method must + * allocate a new array even if this collection is backed by an array). + * The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this collection + */ + long[] toArray(); + + + /** + * Returns an array containing elements in this collection. + * + *

If this collection fits in the specified array with room to spare + * (i.e., the array has more elements than this collection), the element in + * the array immediately following the end of the collection is collection to + * {@link #getNoEntryValue()}. (This is useful in determining + * the length of this collection only if the caller knows that this + * collection does not contain any elements representing null.) + * + *

If the native array is smaller than the collection size, + * the array will be filled with elements in Iterator order + * until it is full and exclude the remainder. + * + *

If this collection makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the elements + * in the same order. + * + * @param dest the array into which the elements of this collection are to be + * stored. + * @return an long[] containing all the elements in this collection + * @throws NullPointerException if the specified array is null + */ + long[] toArray( long[] dest ); + + + /** + * Inserts a value into the collection. + * + * @param entry a long value + * @return true if the collection was modified by the add operation + */ + boolean add( long entry ); + + + /** + * Removes entry from the collection. + * + * @param entry an long value + * @return true if the collection was modified by the remove operation. + */ + boolean remove( long entry ); + + + /** + * Tests the collection to determine if all of the elements in + * collection are present. + * + * @param collection a Collection value + * @return true if all elements were present in the collection. + */ + boolean containsAll( Collection collection ); + + + /** + * Tests the collection to determine if all of the elements in + * TLongCollection are present. + * + * @param collection a TLongCollection value + * @return true if all elements were present in the collection. + */ + boolean containsAll( TLongCollection collection ); + + + /** + * Tests the collection to determine if all of the elements in + * array are present. + * + * @param array as array of long primitives. + * @return true if all elements were present in the collection. + */ + boolean containsAll( long[] array ); + + + /** + * Adds all of the elements in collection to the collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( Collection collection ); + + + /** + * Adds all of the elements in the TLongCollection to the collection. + * + * @param collection a TLongCollection value + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( TLongCollection collection ); + + + /** + * Adds all of the elements in the array to the collection. + * + * @param array a array of long primitives. + * @return true if the collection was modified by the add all operation. + */ + boolean addAll( long[] array ); + + + /** + * Removes any values in the collection which are not contained in + * collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( Collection collection ); + + + /** + * Removes any values in the collection which are not contained in + * TLongCollection. + * + * @param collection a TLongCollection value + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( TLongCollection collection ); + + + /** + * Removes any values in the collection which are not contained in + * array. + * + * @param array an array of long primitives. + * @return true if the collection was modified by the retain all operation + */ + boolean retainAll( long[] array ); + + + /** + * Removes all of the elements in collection from the collection. + * + * @param collection a Collection value + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( Collection collection ); + + + /** + * Removes all of the elements in TLongCollection from the collection. + * + * @param collection a TLongCollection value + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( TLongCollection collection ); + + + /** + * Removes all of the elements in array from the collection. + * + * @param array an array of long primitives. + * @return true if the collection was modified by the remove all operation. + */ + boolean removeAll( long[] array ); + + + /** + * Empties the collection. + */ + void clear(); + + + /** + * Executes procedure for each element in the collection. + * + * @param procedure a TLongProcedure value + * @return false if the loop over the collection terminated because + * the procedure returned false for some value. + */ + boolean forEach( TLongProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this collection for equality. Returns + * true if the specified object is also a collection, the two collection + * have the same size, and every member of the specified collection is + * contained in this collection (or equivalently, every member of this collection is + * contained in the specified collection). This definition ensures that the + * equals method works properly across different implementations of the + * collection interface. + * + * @param o object to be compared for equality with this collection + * @return true if the specified object is equal to this collection + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this collection. The hash code of a collection is + * defined to be the sum of the hash codes of the elements in the collection. + * This ensures that s1.equals(s2) implies that + * s1.hashCode()==s2.hashCode() for any two collection s1 + * and s2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this collection + * @see Object#equals(Object) + * @see Collection#equals(Object) + */ + int hashCode(); + + +} // TLongCollection diff --git a/DataExtractionOSM/src/gnu/trove/function/TFloatFunction.java b/DataExtractionOSM/src/gnu/trove/function/TFloatFunction.java new file mode 100644 index 0000000000..2b72646e69 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/function/TFloatFunction.java @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.function; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for functions that accept and return one float primitive. + */ +public interface TFloatFunction { + /** + * Execute this function with value + * + * @param value a float input + * @return a float result + */ + public float execute( float value ); +} diff --git a/DataExtractionOSM/src/gnu/trove/function/TIntFunction.java b/DataExtractionOSM/src/gnu/trove/function/TIntFunction.java new file mode 100644 index 0000000000..642eabdd63 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/function/TIntFunction.java @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.function; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for functions that accept and return one int primitive. + */ +public interface TIntFunction { + /** + * Execute this function with value + * + * @param value a int input + * @return a int result + */ + public int execute( int value ); +} diff --git a/DataExtractionOSM/src/gnu/trove/function/TLongFunction.java b/DataExtractionOSM/src/gnu/trove/function/TLongFunction.java new file mode 100644 index 0000000000..64219cb4f0 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/function/TLongFunction.java @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.function; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for functions that accept and return one long primitive. + */ +public interface TLongFunction { + /** + * Execute this function with value + * + * @param value a long input + * @return a long result + */ + public long execute( long value ); +} diff --git a/DataExtractionOSM/src/gnu/trove/function/TObjectFunction.java b/DataExtractionOSM/src/gnu/trove/function/TObjectFunction.java new file mode 100644 index 0000000000..397064049b --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/function/TObjectFunction.java @@ -0,0 +1,39 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.function; + +/** + * Interface for functions that accept and return one Object reference. + *

+ * Created: Mon Nov 5 22:19:36 2001 + * + * @author Eric D. Friedman + * @version $Id: TObjectFunction.java,v 1.1.2.1 2009/09/06 17:02:19 upholderoftruth Exp $ + */ + +public interface TObjectFunction { + + /** + * Execute this function with value + * + * @param value an Object input + * @return an Object result + */ + public R execute( T value ); +}// TObjectFunction diff --git a/DataExtractionOSM/src/gnu/trove/impl/Constants.java b/DataExtractionOSM/src/gnu/trove/impl/Constants.java new file mode 100644 index 0000000000..69a69c48d9 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/Constants.java @@ -0,0 +1,165 @@ +// //////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// //////////////////////////////////////////////////////////////////////////// +package gnu.trove.impl; + +/** + * Central location for constants needed by various implementations. + */ +public class Constants { + + private static final boolean VERBOSE = + System.getProperty( "gnu.trove.verbose", null ) != null; + + /** the default capacity for new collections */ + public static final int DEFAULT_CAPACITY = 10; + + /** the load above which rehashing occurs. */ + public static final float DEFAULT_LOAD_FACTOR = 0.5f; + + + /** the default value that represents for byte types. */ + public static final byte DEFAULT_BYTE_NO_ENTRY_VALUE; + static { + byte value; + String property = System.getProperty( "gnu.trove.no_entry.byte", "0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Byte.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Byte.MIN_VALUE; + else value = Byte.valueOf( property ); + + if ( value > Byte.MAX_VALUE ) value = Byte.MAX_VALUE; + else if ( value < Byte.MIN_VALUE ) value = Byte.MIN_VALUE; + DEFAULT_BYTE_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_BYTE_NO_ENTRY_VALUE: " + + DEFAULT_BYTE_NO_ENTRY_VALUE ); + } + } + + + /** the default value that represents for short types. */ + public static final short DEFAULT_SHORT_NO_ENTRY_VALUE; + static { + short value; + String property = System.getProperty( "gnu.trove.no_entry.short", "0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Short.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Short.MIN_VALUE; + else value = Short.valueOf( property ); + + if ( value > Short.MAX_VALUE ) value = Short.MAX_VALUE; + else if ( value < Short.MIN_VALUE ) value = Short.MIN_VALUE; + DEFAULT_SHORT_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_SHORT_NO_ENTRY_VALUE: " + + DEFAULT_SHORT_NO_ENTRY_VALUE ); + } + } + + + /** the default value that represents for char types. */ + public static final char DEFAULT_CHAR_NO_ENTRY_VALUE; + static { + char value; + String property = System.getProperty( "gnu.trove.no_entry.char", "\0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Character.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Character.MIN_VALUE; + else value = property.toCharArray()[0]; + + if ( value > Character.MAX_VALUE ) value = Character.MAX_VALUE; + else if ( value < Character.MIN_VALUE ) value = Character.MIN_VALUE; + DEFAULT_CHAR_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_CHAR_NO_ENTRY_VALUE: " + + Integer.valueOf( value ) ); + } + } + + + /** the default value that represents for int types. */ + public static final int DEFAULT_INT_NO_ENTRY_VALUE; + static { + int value; + String property = System.getProperty( "gnu.trove.no_entry.int", "0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Integer.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Integer.MIN_VALUE; + else value = Integer.valueOf( property ); + DEFAULT_INT_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_INT_NO_ENTRY_VALUE: " + + DEFAULT_INT_NO_ENTRY_VALUE ); + } + } + + + /** the default value that represents for long types. */ + public static final long DEFAULT_LONG_NO_ENTRY_VALUE; + static { + long value; + String property = System.getProperty( "gnu.trove.no_entry.long", "0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Long.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Long.MIN_VALUE; + else value = Long.valueOf( property ); + DEFAULT_LONG_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_LONG_NO_ENTRY_VALUE: " + + DEFAULT_LONG_NO_ENTRY_VALUE ); + } + } + + + /** the default value that represents for float types. */ + public static final float DEFAULT_FLOAT_NO_ENTRY_VALUE; + static { + float value; + String property = System.getProperty( "gnu.trove.no_entry.float", "0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Float.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Float.MIN_VALUE; + // Value from Float.MIN_NORMAL (introduced in 1.6) + else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-126f; + else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.NEGATIVE_INFINITY; + else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.POSITIVE_INFINITY; +// else if ( "NaN".equalsIgnoreCase( property ) ) value = Float.NaN; + else value = Float.valueOf( property ); + DEFAULT_FLOAT_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_FLOAT_NO_ENTRY_VALUE: " + + DEFAULT_FLOAT_NO_ENTRY_VALUE ); + } + } + + + /** the default value that represents for double types. */ + public static final double DEFAULT_DOUBLE_NO_ENTRY_VALUE; + static { + double value; + String property = System.getProperty( "gnu.trove.no_entry.double", "0" ); + if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Double.MAX_VALUE; + else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Double.MIN_VALUE; + // Value from Double.MIN_NORMAL (introduced in 1.6) + else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-1022; + else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.NEGATIVE_INFINITY; + else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.POSITIVE_INFINITY; +// else if ( "NaN".equalsIgnoreCase( property ) ) value = Double.NaN; + else value = Double.valueOf( property ); + DEFAULT_DOUBLE_NO_ENTRY_VALUE = value; + if ( VERBOSE ) { + System.out.println( "DEFAULT_DOUBLE_NO_ENTRY_VALUE: " + + DEFAULT_DOUBLE_NO_ENTRY_VALUE ); + } + } +} diff --git a/DataExtractionOSM/src/gnu/trove/impl/HashFunctions.java b/DataExtractionOSM/src/gnu/trove/impl/HashFunctions.java new file mode 100644 index 0000000000..9bc44ef960 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/HashFunctions.java @@ -0,0 +1,87 @@ +// Copyright (c) 1999 CERN - European Organization for Nuclear Research. + +// Permission to use, copy, modify, distribute and sell this software and +// its documentation for any purpose is hereby granted without fee, +// provided that the above copyright notice appear in all copies and that +// both that copyright notice and this permission notice appear in +// supporting documentation. CERN makes no representations about the +// suitability of this software for any purpose. It is provided "as is" +// without expressed or implied warranty. + +package gnu.trove.impl; + +/** + * Provides various hash functions. + * + * @author wolfgang.hoschek@cern.ch + * @version 1.0, 09/24/99 + */ +public final class HashFunctions { + /** + * Returns a hashcode for the specified value. + * + * @return a hash code value for the specified value. + */ + public static int hash(double value) { + assert !Double.isNaN(value) : "Values of NaN are not supported."; + + long bits = Double.doubleToLongBits(value); + return (int)(bits ^ (bits >>> 32)); + //return (int) Double.doubleToLongBits(value*663608941.737); + //this avoids excessive hashCollisions in the case values are + //of the form (1.0, 2.0, 3.0, ...) + } + + /** + * Returns a hashcode for the specified value. + * + * @return a hash code value for the specified value. + */ + public static int hash(float value) { + assert !Float.isNaN(value) : "Values of NaN are not supported."; + + return Float.floatToIntBits(value*663608941.737f); + // this avoids excessive hashCollisions in the case values are + // of the form (1.0, 2.0, 3.0, ...) + } + + /** + * Returns a hashcode for the specified value. + * + * @return a hash code value for the specified value. + */ + public static int hash(int value) { + // Multiply by prime to make sure hash can't be negative (see Knuth v3, p. 515-516) + return value * 31; + } + + /** + * Returns a hashcode for the specified value. + * + * @return a hash code value for the specified value. + */ + public static int hash(long value) { + // Multiply by prime to make sure hash can't be negative (see Knuth v3, p. 515-516) + return ((int)(value ^ (value >>> 32))) * 31; + } + + /** + * Returns a hashcode for the specified object. + * + * @return a hash code value for the specified object. + */ + public static int hash(Object object) { + return object==null ? 0 : object.hashCode(); + } + + + /** + * In profiling, it has been found to be faster to have our own local implementation + * of "ceil" rather than to call to {@link Math#ceil(double)}. + */ + public static int fastCeil( float v ) { + int possible_result = ( int ) v; + if ( v - possible_result > 0 ) possible_result++; + return possible_result; + } +} diff --git a/DataExtractionOSM/src/gnu/trove/impl/PrimeFinder.java b/DataExtractionOSM/src/gnu/trove/impl/PrimeFinder.java new file mode 100644 index 0000000000..e0a04554cd --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/PrimeFinder.java @@ -0,0 +1,158 @@ +// Copyright (c) 1999 CERN - European Organization for Nuclear Research. + +// Permission to use, copy, modify, distribute and sell this software +// and its documentation for any purpose is hereby granted without fee, +// provided that the above copyright notice appear in all copies and +// that both that copyright notice and this permission notice appear in +// supporting documentation. CERN makes no representations about the +// suitability of this software for any purpose. It is provided "as is" +// without expressed or implied warranty. +package gnu.trove.impl; + +import java.util.Arrays; + +/* + * Modified for Trove to use the java.util.Arrays sort/search + * algorithms instead of those provided with colt. + */ + +/** + * Used to keep hash table capacities prime numbers. + * Not of interest for users; only for implementors of hashtables. + * + *

Choosing prime numbers as hash table capacities is a good idea + * to keep them working fast, particularly under hash table + * expansions. + * + *

However, JDK 1.2, JGL 3.1 and many other toolkits do nothing to + * keep capacities prime. This class provides efficient means to + * choose prime capacities. + * + *

Choosing a prime is O(log 300) (binary search in a list + * of 300 ints). Memory requirements: 1 KB static memory. + * + * @author wolfgang.hoschek@cern.ch + * @version 1.0, 09/24/99 + */ +public final class PrimeFinder { + /** + * The largest prime this class can generate; currently equal to + * Integer.MAX_VALUE. + */ + public static final int largestPrime = Integer.MAX_VALUE; //yes, it is prime. + + /** + * The prime number list consists of 11 chunks. + * + * Each chunk contains prime numbers. + * + * A chunk starts with a prime P1. The next element is a prime + * P2. P2 is the smallest prime for which holds: P2 >= 2*P1. + * + * The next element is P3, for which the same holds with respect + * to P2, and so on. + * + * Chunks are chosen such that for any desired capacity >= 1000 + * the list includes a prime number <= desired capacity * 1.11. + * + * Therefore, primes can be retrieved which are quite close to any + * desired capacity, which in turn avoids wasting memory. + * + * For example, the list includes + * 1039,1117,1201,1277,1361,1439,1523,1597,1759,1907,2081. + * + * So if you need a prime >= 1040, you will find a prime <= + * 1040*1.11=1154. + * + * Chunks are chosen such that they are optimized for a hashtable + * growthfactor of 2.0; + * + * If your hashtable has such a growthfactor then, after initially + * "rounding to a prime" upon hashtable construction, it will + * later expand to prime capacities such that there exist no + * better primes. + * + * In total these are about 32*10=320 numbers -> 1 KB of static + * memory needed. + * + * If you are stingy, then delete every second or fourth chunk. + */ + + private static final int[] primeCapacities = { + //chunk #0 + largestPrime, + + //chunk #1 + 5,11,23,47,97,197,397,797,1597,3203,6421,12853,25717,51437,102877,205759, + 411527,823117,1646237,3292489,6584983,13169977,26339969,52679969,105359939, + 210719881,421439783,842879579,1685759167, + + //chunk #2 + 433,877,1759,3527,7057,14143,28289,56591,113189,226379,452759,905551,1811107, + 3622219,7244441,14488931,28977863,57955739,115911563,231823147,463646329,927292699, + 1854585413, + + //chunk #3 + 953,1907,3821,7643,15287,30577,61169,122347,244703,489407,978821,1957651,3915341, + 7830701,15661423,31322867,62645741,125291483,250582987,501165979,1002331963, + 2004663929, + + //chunk #4 + 1039,2081,4177,8363,16729,33461,66923,133853,267713,535481,1070981,2141977,4283963, + 8567929,17135863,34271747,68543509,137087021,274174111,548348231,1096696463, + + //chunk #5 + 31,67,137,277,557,1117,2237,4481,8963,17929,35863,71741,143483,286973,573953, + 1147921,2295859,4591721,9183457,18366923,36733847,73467739,146935499,293871013, + 587742049,1175484103, + + //chunk #6 + 599,1201,2411,4831,9677,19373,38747,77509,155027,310081,620171,1240361,2480729, + 4961459,9922933,19845871,39691759,79383533,158767069,317534141,635068283,1270136683, + + //chunk #7 + 311,631,1277,2557,5119,10243,20507,41017,82037,164089,328213,656429,1312867, + 2625761,5251529,10503061,21006137,42012281,84024581,168049163,336098327,672196673, + 1344393353, + + //chunk #8 + 3,7,17,37,79,163,331,673,1361,2729,5471,10949,21911,43853,87719,175447,350899, + 701819,1403641,2807303,5614657,11229331,22458671,44917381,89834777,179669557, + 359339171,718678369,1437356741, + + //chunk #9 + 43,89,179,359,719,1439,2879,5779,11579,23159,46327,92657,185323,370661,741337, + 1482707,2965421,5930887,11861791,23723597,47447201,94894427,189788857,379577741, + 759155483,1518310967, + + //chunk #10 + 379,761,1523,3049,6101,12203,24407,48817,97649,195311,390647,781301,1562611, + 3125257,6250537,12501169,25002389,50004791,100009607,200019221,400038451,800076929, + 1600153859 + }; + + static { //initializer + // The above prime numbers are formatted for human readability. + // To find numbers fast, we sort them once and for all. + + Arrays.sort(primeCapacities); + } + + /** + * Returns a prime number which is >= desiredCapacity + * and very close to desiredCapacity (within 11% if + * desiredCapacity >= 1000). + * + * @param desiredCapacity the capacity desired by the user. + * @return the capacity which should be used for a hashtable. + */ + public static final int nextPrime(int desiredCapacity) { + int i = Arrays.binarySearch(primeCapacities, desiredCapacity); + if (i<0) { + // desired capacity not found, choose next prime greater + // than desired capacity + i = -i -1; // remember the semantics of binarySearch... + } + return primeCapacities[i]; + } +} diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/TFloatHash.java b/DataExtractionOSM/src/gnu/trove/impl/hash/TFloatHash.java new file mode 100644 index 0000000000..5bbc2c88a5 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/TFloatHash.java @@ -0,0 +1,293 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.procedure.TFloatProcedure; +import gnu.trove.impl.HashFunctions; +import gnu.trove.impl.Constants; + +import java.util.Arrays; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * An open addressed hashing implementation for float primitives. + * + * Created: Sun Nov 4 08:56:06 2001 + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ + */ +abstract public class TFloatHash extends TPrimitiveHash { + + /** the set of floats */ + public transient float[] _set; + + /** + * value that represents null + * + * NOTE: should not be modified after the Hash is created, but is + * not final because of Externalization + * + */ + protected float no_entry_value; + + + /** + * Creates a new TFloatHash instance with the default + * capacity and load factor. + */ + public TFloatHash() { + super(); + no_entry_value = Constants.DEFAULT_FLOAT_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( float ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TFloatHash instance whose capacity + * is the next highest prime above initialCapacity + 1 + * unless that value is already prime. + * + * @param initialCapacity an int value + */ + public TFloatHash( int initialCapacity ) { + super( initialCapacity ); + no_entry_value = Constants.DEFAULT_FLOAT_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( float ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TFloatHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + */ + public TFloatHash( int initialCapacity, float loadFactor ) { + super(initialCapacity, loadFactor); + no_entry_value = Constants.DEFAULT_FLOAT_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( float ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TFloatHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + * @param no_entry_value value that represents null + */ + public TFloatHash( int initialCapacity, float loadFactor, float no_entry_value ) { + super(initialCapacity, loadFactor); + this.no_entry_value = no_entry_value; + //noinspection RedundantCast + if ( no_entry_value != ( float ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + public float getNoEntryValue() { + return no_entry_value; + } + + + /** + * initializes the hashtable to a prime capacity which is at least + * initialCapacity + 1. + * + * @param initialCapacity an int value + * @return the actual capacity chosen + */ + protected int setUp( int initialCapacity ) { + int capacity; + + capacity = super.setUp( initialCapacity ); + _set = new float[capacity]; + return capacity; + } + + + /** + * Searches the set for val + * + * @param val an float value + * @return a boolean value + */ + public boolean contains( float val ) { + return index(val) >= 0; + } + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TObjectProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + public boolean forEach( TFloatProcedure procedure ) { + byte[] states = _states; + float[] set = _set; + for ( int i = set.length; i-- > 0; ) { + if ( states[i] == FULL && ! procedure.execute( set[i] ) ) { + return false; + } + } + return true; + } + + + /** + * Releases the element currently stored at index. + * + * @param index an int value + */ + protected void removeAt( int index ) { + _set[index] = no_entry_value; + super.removeAt( index ); + } + + + /** + * Locates the index of val. + * + * @param val an float value + * @return the index of val or -1 if it isn't in the set. + */ + protected int index( float val ) { + int hash, probe, index, length; + + final byte[] states = _states; + final float[] set = _set; + length = states.length; + hash = HashFunctions.hash( val ) & 0x7fffffff; + index = hash % length; + + if ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ) { + // see Knuth, p. 529 + probe = 1 + ( hash % ( length - 2 ) ); + + do { + index -= probe; + if ( index < 0 ) { + index += length; + } + } while ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ); + } + + return states[index] == FREE ? -1 : index; + } + + + /** + * Locates the index at which val can be inserted. if + * there is already a value equal()ing val in the set, + * returns that value as a negative integer. + * + * @param val an float value + * @return an int value + */ + protected int insertionIndex( float val ) { + int hash, probe, index, length; + + final byte[] states = _states; + final float[] set = _set; + length = states.length; + hash = HashFunctions.hash( val ) & 0x7fffffff; + index = hash % length; + + if ( states[index] == FREE ) { + return index; // empty, all done + } else if ( states[index] == FULL && set[index] == val ) { + return -index -1; // already stored + } else { // already FULL or REMOVED, must probe + // compute the double hash + probe = 1 + ( hash % ( length - 2 ) ); + + // if the slot we landed on is FULL (but not removed), probe + // until we find an empty slot, a REMOVED slot, or an element + // equal to the one we are trying to insert. + // finding an empty slot means that the value is not present + // and that we should use that slot as the insertion point; + // finding a REMOVED slot means that we need to keep searching, + // however we want to remember the offset of that REMOVED slot + // so we can reuse it in case a "new" insertion (i.e. not an update) + // is possible. + // finding a matching value means that we've found that our desired + // key is already in the table + + if ( states[index] != REMOVED ) { + // starting at the natural offset, probe until we find an + // offset that isn't full. + do { + index -= probe; + if (index < 0) { + index += length; + } + } while ( states[index] == FULL && set[index] != val ); + } + + // if the index we found was removed: continue probing until we + // locate a free location or an element which equal()s the + // one we have. + if ( states[index] == REMOVED) { + int firstRemoved = index; + while ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ) { + index -= probe; + if (index < 0) { + index += length; + } + } + return states[index] == FULL ? -index -1 : firstRemoved; + } + // if it's full, the key is already stored + return states[index] == FULL ? -index -1 : index; + } + } +} // TFloatHash diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/THash.java b/DataExtractionOSM/src/gnu/trove/impl/hash/THash.java new file mode 100644 index 0000000000..79bc903f17 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/THash.java @@ -0,0 +1,428 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.impl.Constants; +import gnu.trove.impl.HashFunctions; +import gnu.trove.impl.PrimeFinder; + +import java.io.Externalizable; +import java.io.ObjectOutput; +import java.io.IOException; +import java.io.ObjectInput; + + + +/** + * Base class for hashtables that use open addressing to resolve + * collisions. + * + * Created: Wed Nov 28 21:11:16 2001 + * + * @author Eric D. Friedman + * @author Rob Eden (auto-compaction) + * @author Jeff Randall + * + * @version $Id: THash.java,v 1.1.2.4 2010/03/02 00:55:34 robeden Exp $ + */ +abstract public class THash implements Externalizable { + + static final long serialVersionUID = -1792948471915530295L; + + /** the load above which rehashing occurs. */ + protected static final float DEFAULT_LOAD_FACTOR = Constants.DEFAULT_LOAD_FACTOR; + + /** + * the default initial capacity for the hash table. This is one + * less than a prime value because one is added to it when + * searching for a prime capacity to account for the free slot + * required by open addressing. Thus, the real default capacity is + * 11. + */ + protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY; + + + /** the current number of occupied slots in the hash. */ + protected transient int _size; + + /** the current number of free slots in the hash. */ + protected transient int _free; + + /** + * Determines how full the internal table can become before + * rehashing is required. This must be a value in the range: 0.0 < + * loadFactor < 1.0. The default value is 0.5, which is about as + * large as you can get in open addressing without hurting + * performance. Cf. Knuth, Volume 3., Chapter 6. + */ + protected float _loadFactor; + + /** + * The maximum number of elements allowed without allocating more + * space. + */ + protected int _maxSize; + + + /** The number of removes that should be performed before an auto-compaction occurs. */ + protected int _autoCompactRemovesRemaining; + + /** + * The auto-compaction factor for the table. + * + * @see #setAutoCompactionFactor + */ + protected float _autoCompactionFactor; + + /** @see #tempDisableAutoCompaction */ + protected transient boolean _autoCompactTemporaryDisable = false; + + + /** + * Creates a new THash instance with the default + * capacity and load factor. + */ + public THash() { + this( DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR ); + } + + + /** + * Creates a new THash instance with a prime capacity + * at or near the specified capacity and with the default load + * factor. + * + * @param initialCapacity an int value + */ + public THash( int initialCapacity ) { + this( initialCapacity, DEFAULT_LOAD_FACTOR ); + } + + + /** + * Creates a new THash instance with a prime capacity + * at or near the minimum needed to hold initialCapacity + * elements with load factor loadFactor without triggering + * a rehash. + * + * @param initialCapacity an int value + * @param loadFactor a float value + */ + public THash( int initialCapacity, float loadFactor ) { + super(); + _loadFactor = loadFactor; + + // Through testing, the load factor (especially the default load factor) has been + // found to be a pretty good starting auto-compaction factor. + _autoCompactionFactor = loadFactor; + + setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) ); + } + + + /** + * Tells whether this set is currently holding any elements. + * + * @return a boolean value + */ + public boolean isEmpty() { + return 0 == _size; + } + + + /** + * Returns the number of distinct elements in this collection. + * + * @return an int value + */ + public int size() { + return _size; + } + + + /** @return the current physical capacity of the hash table. */ + abstract public int capacity(); + + + /** + * Ensure that this hashtable has sufficient capacity to hold + * desiredCapacity additional elements without + * requiring a rehash. This is a tuning method you can call + * before doing a large insert. + * + * @param desiredCapacity an int value + */ + public void ensureCapacity( int desiredCapacity ) { + if ( desiredCapacity > ( _maxSize - size() ) ) { + rehash( PrimeFinder.nextPrime( HashFunctions.fastCeil( + ( desiredCapacity + size() ) / _loadFactor ) + 1 ) ); + computeMaxSize( capacity() ); + } + } + + + /** + * Compresses the hashtable to the minimum prime size (as defined + * by PrimeFinder) that will hold all of the elements currently in + * the table. If you have done a lot of remove + * operations and plan to do a lot of queries or insertions or + * iteration, it is a good idea to invoke this method. Doing so + * will accomplish two things: + *

+ *

    + *
  1. You'll free memory allocated to the table but no + * longer needed because of the remove()s.
  2. + *

    + *

  3. You'll get better query/insert/iterator performance + * because there won't be any REMOVED slots to skip + * over when probing for indices in the table.
  4. + *
+ */ + public void compact() { + // need at least one free spot for open addressing + rehash( PrimeFinder.nextPrime( HashFunctions.fastCeil( size() / _loadFactor ) + 1 ) ); + computeMaxSize( capacity() ); + + // If auto-compaction is enabled, re-determine the compaction interval + if ( _autoCompactionFactor != 0 ) { + computeNextAutoCompactionAmount( size() ); + } + } + + + /** + * The auto-compaction factor controls whether and when a table performs a + * {@link #compact} automatically after a certain number of remove operations. + * If the value is non-zero, the number of removes that need to occur for + * auto-compaction is the size of table at the time of the previous compaction + * (or the initial capacity) multiplied by this factor. + *

+ * Setting this value to zero will disable auto-compaction. + * + * @param factor a float that indicates the auto-compaction factor + */ + public void setAutoCompactionFactor( float factor ) { + if ( factor < 0 ) { + throw new IllegalArgumentException( "Factor must be >= 0: " + factor ); + } + + _autoCompactionFactor = factor; + } + + + /** + * @see #setAutoCompactionFactor + * + * @return a <float that represents the auto-compaction factor. + */ + public float getAutoCompactionFactor() { + return _autoCompactionFactor; + } + + + /** + * This simply calls {@link #compact compact}. It is included for + * symmetry with other collection classes. Note that the name of this + * method is somewhat misleading (which is why we prefer + * compact) as the load factor may require capacity above + * and beyond the size of this collection. + * + * @see #compact + */ + public final void trimToSize() { + compact(); + } + + + /** + * Delete the record at index. Reduces the size of the + * collection by one. + * + * @param index an int value + */ + protected void removeAt( int index ) { + _size--; + + // If auto-compaction is enabled, see if we need to compact + if ( _autoCompactionFactor != 0 ) { + _autoCompactRemovesRemaining--; + + if ( !_autoCompactTemporaryDisable && _autoCompactRemovesRemaining <= 0 ) { + // Do the compact + // NOTE: this will cause the next compaction interval to be calculated + compact(); + } + } + } + + + /** Empties the collection. */ + public void clear() { + _size = 0; + _free = capacity(); + } + + + /** + * initializes the hashtable to a prime capacity which is at least + * initialCapacity + 1. + * + * @param initialCapacity an int value + * @return the actual capacity chosen + */ + protected int setUp( int initialCapacity ) { + int capacity; + + capacity = PrimeFinder.nextPrime( initialCapacity ); + computeMaxSize( capacity ); + computeNextAutoCompactionAmount( initialCapacity ); + + return capacity; + } + + + /** + * Rehashes the set. + * + * @param newCapacity an int value + */ + protected abstract void rehash( int newCapacity ); + + + /** + * Temporarily disables auto-compaction. MUST be followed by calling + * {@link #reenableAutoCompaction}. + */ + public void tempDisableAutoCompaction() { + _autoCompactTemporaryDisable = true; + } + + + /** + * Re-enable auto-compaction after it was disabled via + * {@link #tempDisableAutoCompaction()}. + * + * @param check_for_compaction True if compaction should be performed if needed + * before returning. If false, no compaction will be + * performed. + */ + public void reenableAutoCompaction( boolean check_for_compaction ) { + _autoCompactTemporaryDisable = false; + + if ( check_for_compaction && _autoCompactRemovesRemaining <= 0 && + _autoCompactionFactor != 0 ) { + + // Do the compact + // NOTE: this will cause the next compaction interval to be calculated + compact(); + } + } + + + /** + * Computes the values of maxSize. There will always be at least + * one free slot required. + * + * @param capacity an int value + */ + protected void computeMaxSize( int capacity ) { + // need at least one free slot for open addressing + _maxSize = Math.min( capacity - 1, (int) ( capacity * _loadFactor ) ); + _free = capacity - _size; // reset the free element count + } + + + /** + * Computes the number of removes that need to happen before the next auto-compaction + * will occur. + * + * @param size an int that sets the auto-compaction limit. + */ + protected void computeNextAutoCompactionAmount( int size ) { + if ( _autoCompactionFactor != 0 ) { + // NOTE: doing the round ourselves has been found to be faster than using + // Math.round. + _autoCompactRemovesRemaining = + (int) ( ( size * _autoCompactionFactor ) + 0.5f ); + } + } + + + /** + * After an insert, this hook is called to adjust the size/free + * values of the set and to perform rehashing if necessary. + * + * @param usedFreeSlot the slot + */ + protected final void postInsertHook( boolean usedFreeSlot ) { + if ( usedFreeSlot ) { + _free--; + } + + // rehash whenever we exhaust the available space in the table + if ( ++_size > _maxSize || _free == 0 ) { + // choose a new capacity suited to the new state of the table + // if we've grown beyond our maximum size, double capacity; + // if we've exhausted the free spots, rehash to the same capacity, + // which will free up any stale removed slots for reuse. + int newCapacity = _size > _maxSize ? PrimeFinder.nextPrime( capacity() << 1 ) : capacity(); + rehash( newCapacity ); + computeMaxSize( capacity() ); + } + } + + + protected int calculateGrownCapacity() { + return capacity() << 1; + } + + + public void writeExternal( ObjectOutput out ) throws IOException { + // VERSION + out.writeByte( 0 ); + + // LOAD FACTOR + out.writeFloat( _loadFactor ); + + // AUTO COMPACTION LOAD FACTOR + out.writeFloat( _autoCompactionFactor ); + } + + + public void readExternal( ObjectInput in ) + throws IOException, ClassNotFoundException { + + // VERSION + in.readByte(); + + // LOAD FACTOR + float old_factor = _loadFactor; + _loadFactor = in.readFloat(); + + // AUTO COMPACTION LOAD FACTOR + _autoCompactionFactor = in.readFloat(); + + // If we change the laod factor from the default, re-setup + if ( old_factor != _loadFactor ) { + setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); + } + } +}// THash \ No newline at end of file diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/THashIterator.java b/DataExtractionOSM/src/gnu/trove/impl/hash/THashIterator.java new file mode 100644 index 0000000000..3dbe3fa852 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/THashIterator.java @@ -0,0 +1,177 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.iterator.TIterator; + +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NoSuchElementException; + + + +/** + * Implements all iterator functions for the hashed object set. + * Subclasses may override objectAtIndex to vary the object + * returned by calls to next() (e.g. for values, and Map.Entry + * objects). + *

+ *

Note that iteration is fastest if you forego the calls to + * hasNext in favor of checking the size of the structure + * yourself and then call next() that many times: + *

+ *

+ * Iterator i = collection.iterator();
+ * for (int size = collection.size(); size-- > 0;) {
+ *   Object o = i.next();
+ * }
+ * 
+ *

+ *

You may, of course, use the hasNext(), next() idiom too if + * you aren't in a performance critical spot.

+ */ +public abstract class THashIterator implements TIterator, Iterator { + + + private final TObjectHash _object_hash; + + /** the data structure this iterator traverses */ + protected final THash _hash; + + /** + * the number of elements this iterator believes are in the + * data structure it accesses. + */ + protected int _expectedSize; + + /** the index used for iteration. */ + protected int _index; + + + /** + * Create an instance of THashIterator over the values of the TObjectHash + * + * @param hash the object + */ + protected THashIterator( TObjectHash hash ) { + _hash = hash; + _expectedSize = _hash.size(); + _index = _hash.capacity(); + _object_hash = hash; + } + + + /** + * Moves the iterator to the next Object and returns it. + * + * @return an Object value + * @throws ConcurrentModificationException + * if the structure + * was changed using a method that isn't on this iterator. + * @throws NoSuchElementException if this is called on an + * exhausted iterator. + */ + public V next() { + moveToNextIndex(); + return objectAtIndex( _index ); + } + + + /** + * Returns true if the iterator can be advanced past its current + * location. + * + * @return a boolean value + */ + public boolean hasNext() { + return nextIndex() >= 0; + } + + + /** + * Removes the last entry returned by the iterator. + * Invoking this method more than once for a single entry + * will leave the underlying data structure in a confused + * state. + */ + public void remove() { + if ( _expectedSize != _hash.size() ) { + throw new ConcurrentModificationException(); + } + + // Disable auto compaction during the remove. This is a workaround for bug 1642768. + try { + _hash.tempDisableAutoCompaction(); + _hash.removeAt( _index ); + } + finally { + _hash.reenableAutoCompaction( false ); + } + + _expectedSize--; + } + + + /** + * Sets the internal index so that the `next' object + * can be returned. + */ + protected final void moveToNextIndex() { + // doing the assignment && < 0 in one line shaves + // 3 opcodes... + if ( ( _index = nextIndex() ) < 0 ) { + throw new NoSuchElementException(); + } + } + + + /** + * Returns the index of the next value in the data structure + * or a negative value if the iterator is exhausted. + * + * @return an int value + * @throws ConcurrentModificationException + * if the underlying + * collection's size has been modified since the iterator was + * created. + */ + protected final int nextIndex() { + if ( _expectedSize != _hash.size() ) { + throw new ConcurrentModificationException(); + } + + Object[] set = _object_hash._set; + int i = _index; + while ( i-- > 0 && ( set[i] == TObjectHash.FREE || set[i] == TObjectHash.REMOVED ) ) { + ; + } + return i; + } + + + /** + * Returns the object at the specified index. Subclasses should + * implement this to return the appropriate object for the given + * index. + * + * @param index the index of the value to return. + * @return an Object value + */ + abstract protected V objectAtIndex( int index ); +} // THashIterator diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/THashPrimitiveIterator.java b/DataExtractionOSM/src/gnu/trove/impl/hash/THashPrimitiveIterator.java new file mode 100644 index 0000000000..658d840415 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/THashPrimitiveIterator.java @@ -0,0 +1,143 @@ +// //////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// //////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.iterator.TPrimitiveIterator; + +import java.util.ConcurrentModificationException; +import java.util.NoSuchElementException; + + +/** + * Implements all iterator functions for the hashed object set. + * Subclasses may override objectAtIndex to vary the object + * returned by calls to next() (e.g. for values, and Map.Entry + * objects). + *

+ *

Note that iteration is fastest if you forego the calls to + * hasNext in favor of checking the size of the structure + * yourself and then call next() that many times: + *

+ *

+ * Iterator i = collection.iterator();
+ * for (int size = collection.size(); size-- > 0;) {
+ *   Object o = i.next();
+ * }
+ * 
+ *

+ *

You may, of course, use the hasNext(), next() idiom too if + * you aren't in a performance critical spot.

+ */ +public abstract class THashPrimitiveIterator implements TPrimitiveIterator { + + /** the data structure this iterator traverses */ + protected final TPrimitiveHash _hash; + /** + * the number of elements this iterator believes are in the + * data structure it accesses. + */ + protected int _expectedSize; + /** the index used for iteration. */ + protected int _index; + + + /** + * Creates a TPrimitiveIterator for the specified collection. + * + * @param hash the TPrimitiveHash we want to iterate over. + */ + public THashPrimitiveIterator( TPrimitiveHash hash ) { + _hash = hash; + _expectedSize = _hash.size(); + _index = _hash.capacity(); + } + + + /** + * Returns the index of the next value in the data structure + * or a negative value if the iterator is exhausted. + * + * @return an int value + * @throws java.util.ConcurrentModificationException + * if the underlying collection's + * size has been modified since the iterator was created. + */ + protected final int nextIndex() { + if ( _expectedSize != _hash.size() ) { + throw new ConcurrentModificationException(); + } + + byte[] states = _hash._states; + int i = _index; + while ( i-- > 0 && ( states[i] != TPrimitiveHash.FULL ) ) { + ; + } + return i; + } + + + /** + * Returns true if the iterator can be advanced past its current + * location. + * + * @return a boolean value + */ + public boolean hasNext() { + return nextIndex() >= 0; + } + + + /** + * Removes the last entry returned by the iterator. + * Invoking this method more than once for a single entry + * will leave the underlying data structure in a confused + * state. + */ + public void remove() { + if (_expectedSize != _hash.size()) { + throw new ConcurrentModificationException(); + } + + // Disable auto compaction during the remove. This is a workaround for bug 1642768. + try { + _hash.tempDisableAutoCompaction(); + _hash.removeAt(_index); + } + finally { + _hash.reenableAutoCompaction( false ); + } + + _expectedSize--; + } + + + /** + * Sets the internal index so that the `next' object + * can be returned. + */ + protected final void moveToNextIndex() { + // doing the assignment && < 0 in one line shaves + // 3 opcodes... + if ( ( _index = nextIndex() ) < 0 ) { + throw new NoSuchElementException(); + } + } + + +} // TPrimitiveIterator \ No newline at end of file diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/TIntHash.java b/DataExtractionOSM/src/gnu/trove/impl/hash/TIntHash.java new file mode 100644 index 0000000000..04c8df74be --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/TIntHash.java @@ -0,0 +1,293 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.procedure.TIntProcedure; +import gnu.trove.impl.HashFunctions; +import gnu.trove.impl.Constants; + +import java.util.Arrays; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * An open addressed hashing implementation for int primitives. + * + * Created: Sun Nov 4 08:56:06 2001 + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ + */ +abstract public class TIntHash extends TPrimitiveHash { + + /** the set of ints */ + public transient int[] _set; + + /** + * value that represents null + * + * NOTE: should not be modified after the Hash is created, but is + * not final because of Externalization + * + */ + protected int no_entry_value; + + + /** + * Creates a new TIntHash instance with the default + * capacity and load factor. + */ + public TIntHash() { + super(); + no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TIntHash instance whose capacity + * is the next highest prime above initialCapacity + 1 + * unless that value is already prime. + * + * @param initialCapacity an int value + */ + public TIntHash( int initialCapacity ) { + super( initialCapacity ); + no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TIntHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + */ + public TIntHash( int initialCapacity, float loadFactor ) { + super(initialCapacity, loadFactor); + no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TIntHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + * @param no_entry_value value that represents null + */ + public TIntHash( int initialCapacity, float loadFactor, int no_entry_value ) { + super(initialCapacity, loadFactor); + this.no_entry_value = no_entry_value; + //noinspection RedundantCast + if ( no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + public int getNoEntryValue() { + return no_entry_value; + } + + + /** + * initializes the hashtable to a prime capacity which is at least + * initialCapacity + 1. + * + * @param initialCapacity an int value + * @return the actual capacity chosen + */ + protected int setUp( int initialCapacity ) { + int capacity; + + capacity = super.setUp( initialCapacity ); + _set = new int[capacity]; + return capacity; + } + + + /** + * Searches the set for val + * + * @param val an int value + * @return a boolean value + */ + public boolean contains( int val ) { + return index(val) >= 0; + } + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TObjectProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + public boolean forEach( TIntProcedure procedure ) { + byte[] states = _states; + int[] set = _set; + for ( int i = set.length; i-- > 0; ) { + if ( states[i] == FULL && ! procedure.execute( set[i] ) ) { + return false; + } + } + return true; + } + + + /** + * Releases the element currently stored at index. + * + * @param index an int value + */ + protected void removeAt( int index ) { + _set[index] = no_entry_value; + super.removeAt( index ); + } + + + /** + * Locates the index of val. + * + * @param val an int value + * @return the index of val or -1 if it isn't in the set. + */ + protected int index( int val ) { + int hash, probe, index, length; + + final byte[] states = _states; + final int[] set = _set; + length = states.length; + hash = HashFunctions.hash( val ) & 0x7fffffff; + index = hash % length; + + if ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ) { + // see Knuth, p. 529 + probe = 1 + ( hash % ( length - 2 ) ); + + do { + index -= probe; + if ( index < 0 ) { + index += length; + } + } while ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ); + } + + return states[index] == FREE ? -1 : index; + } + + + /** + * Locates the index at which val can be inserted. if + * there is already a value equal()ing val in the set, + * returns that value as a negative integer. + * + * @param val an int value + * @return an int value + */ + protected int insertionIndex( int val ) { + int hash, probe, index, length; + + final byte[] states = _states; + final int[] set = _set; + length = states.length; + hash = HashFunctions.hash( val ) & 0x7fffffff; + index = hash % length; + + if ( states[index] == FREE ) { + return index; // empty, all done + } else if ( states[index] == FULL && set[index] == val ) { + return -index -1; // already stored + } else { // already FULL or REMOVED, must probe + // compute the double hash + probe = 1 + ( hash % ( length - 2 ) ); + + // if the slot we landed on is FULL (but not removed), probe + // until we find an empty slot, a REMOVED slot, or an element + // equal to the one we are trying to insert. + // finding an empty slot means that the value is not present + // and that we should use that slot as the insertion point; + // finding a REMOVED slot means that we need to keep searching, + // however we want to remember the offset of that REMOVED slot + // so we can reuse it in case a "new" insertion (i.e. not an update) + // is possible. + // finding a matching value means that we've found that our desired + // key is already in the table + + if ( states[index] != REMOVED ) { + // starting at the natural offset, probe until we find an + // offset that isn't full. + do { + index -= probe; + if (index < 0) { + index += length; + } + } while ( states[index] == FULL && set[index] != val ); + } + + // if the index we found was removed: continue probing until we + // locate a free location or an element which equal()s the + // one we have. + if ( states[index] == REMOVED) { + int firstRemoved = index; + while ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ) { + index -= probe; + if (index < 0) { + index += length; + } + } + return states[index] == FULL ? -index -1 : firstRemoved; + } + // if it's full, the key is already stored + return states[index] == FULL ? -index -1 : index; + } + } +} // TIntHash diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/TLongHash.java b/DataExtractionOSM/src/gnu/trove/impl/hash/TLongHash.java new file mode 100644 index 0000000000..ce94453874 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/TLongHash.java @@ -0,0 +1,293 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.procedure.TLongProcedure; +import gnu.trove.impl.HashFunctions; +import gnu.trove.impl.Constants; + +import java.util.Arrays; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * An open addressed hashing implementation for long primitives. + * + * Created: Sun Nov 4 08:56:06 2001 + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ + */ +abstract public class TLongHash extends TPrimitiveHash { + + /** the set of longs */ + public transient long[] _set; + + /** + * value that represents null + * + * NOTE: should not be modified after the Hash is created, but is + * not final because of Externalization + * + */ + protected long no_entry_value; + + + /** + * Creates a new TLongHash instance with the default + * capacity and load factor. + */ + public TLongHash() { + super(); + no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TLongHash instance whose capacity + * is the next highest prime above initialCapacity + 1 + * unless that value is already prime. + * + * @param initialCapacity an int value + */ + public TLongHash( int initialCapacity ) { + super( initialCapacity ); + no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TLongHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + */ + public TLongHash( int initialCapacity, float loadFactor ) { + super(initialCapacity, loadFactor); + no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE; + //noinspection RedundantCast + if ( no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TLongHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + * @param no_entry_value value that represents null + */ + public TLongHash( int initialCapacity, float loadFactor, long no_entry_value ) { + super(initialCapacity, loadFactor); + this.no_entry_value = no_entry_value; + //noinspection RedundantCast + if ( no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + public long getNoEntryValue() { + return no_entry_value; + } + + + /** + * initializes the hashtable to a prime capacity which is at least + * initialCapacity + 1. + * + * @param initialCapacity an int value + * @return the actual capacity chosen + */ + protected int setUp( int initialCapacity ) { + int capacity; + + capacity = super.setUp( initialCapacity ); + _set = new long[capacity]; + return capacity; + } + + + /** + * Searches the set for val + * + * @param val an long value + * @return a boolean value + */ + public boolean contains( long val ) { + return index(val) >= 0; + } + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TObjectProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + public boolean forEach( TLongProcedure procedure ) { + byte[] states = _states; + long[] set = _set; + for ( int i = set.length; i-- > 0; ) { + if ( states[i] == FULL && ! procedure.execute( set[i] ) ) { + return false; + } + } + return true; + } + + + /** + * Releases the element currently stored at index. + * + * @param index an int value + */ + protected void removeAt( int index ) { + _set[index] = no_entry_value; + super.removeAt( index ); + } + + + /** + * Locates the index of val. + * + * @param val an long value + * @return the index of val or -1 if it isn't in the set. + */ + protected int index( long val ) { + int hash, probe, index, length; + + final byte[] states = _states; + final long[] set = _set; + length = states.length; + hash = HashFunctions.hash( val ) & 0x7fffffff; + index = hash % length; + + if ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ) { + // see Knuth, p. 529 + probe = 1 + ( hash % ( length - 2 ) ); + + do { + index -= probe; + if ( index < 0 ) { + index += length; + } + } while ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ); + } + + return states[index] == FREE ? -1 : index; + } + + + /** + * Locates the index at which val can be inserted. if + * there is already a value equal()ing val in the set, + * returns that value as a negative integer. + * + * @param val an long value + * @return an int value + */ + protected int insertionIndex( long val ) { + int hash, probe, index, length; + + final byte[] states = _states; + final long[] set = _set; + length = states.length; + hash = HashFunctions.hash( val ) & 0x7fffffff; + index = hash % length; + + if ( states[index] == FREE ) { + return index; // empty, all done + } else if ( states[index] == FULL && set[index] == val ) { + return -index -1; // already stored + } else { // already FULL or REMOVED, must probe + // compute the double hash + probe = 1 + ( hash % ( length - 2 ) ); + + // if the slot we landed on is FULL (but not removed), probe + // until we find an empty slot, a REMOVED slot, or an element + // equal to the one we are trying to insert. + // finding an empty slot means that the value is not present + // and that we should use that slot as the insertion point; + // finding a REMOVED slot means that we need to keep searching, + // however we want to remember the offset of that REMOVED slot + // so we can reuse it in case a "new" insertion (i.e. not an update) + // is possible. + // finding a matching value means that we've found that our desired + // key is already in the table + + if ( states[index] != REMOVED ) { + // starting at the natural offset, probe until we find an + // offset that isn't full. + do { + index -= probe; + if (index < 0) { + index += length; + } + } while ( states[index] == FULL && set[index] != val ); + } + + // if the index we found was removed: continue probing until we + // locate a free location or an element which equal()s the + // one we have. + if ( states[index] == REMOVED) { + int firstRemoved = index; + while ( states[index] != FREE && + ( states[index] == REMOVED || set[index] != val ) ) { + index -= probe; + if (index < 0) { + index += length; + } + } + return states[index] == FULL ? -index -1 : firstRemoved; + } + // if it's full, the key is already stored + return states[index] == FULL ? -index -1 : index; + } + } +} // TLongHash diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/TObjectHash.java b/DataExtractionOSM/src/gnu/trove/impl/hash/TObjectHash.java new file mode 100644 index 0000000000..4ba44c30d8 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/TObjectHash.java @@ -0,0 +1,312 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.impl.HashFunctions; +import gnu.trove.procedure.TObjectProcedure; + +import java.util.Arrays; +import java.io.ObjectOutput; +import java.io.IOException; +import java.io.ObjectInput; + + + +/** + * An open addressed hashing implementation for Object types. + *

+ * Created: Sun Nov 4 08:56:06 2001 + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + * @version $Id: TObjectHash.java,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ + */ +abstract public class TObjectHash extends THash { + + static final long serialVersionUID = -3461112548087185871L; + + + /** the set of Objects */ + public transient Object[] _set; + + public static final Object REMOVED = new Object(), FREE = new Object(); + + + /** + * Creates a new TObjectHash instance with the + * default capacity and load factor. + */ + public TObjectHash() { + super(); + } + + + /** + * Creates a new TObjectHash instance whose capacity + * is the next highest prime above initialCapacity + 1 + * unless that value is already prime. + * + * @param initialCapacity an int value + */ + public TObjectHash( int initialCapacity ) { + super( initialCapacity ); + } + + + /** + * Creates a new TObjectHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + */ + public TObjectHash( int initialCapacity, float loadFactor ) { + super( initialCapacity, loadFactor ); + } + + + public int capacity() { + return _set.length; + } + + + protected void removeAt( int index ) { + _set[index] = REMOVED; + super.removeAt( index ); + } + + + /** + * initializes the Object set of this hash table. + * + * @param initialCapacity an int value + * @return an int value + */ + public int setUp( int initialCapacity ) { + int capacity; + + capacity = super.setUp( initialCapacity ); + _set = new Object[capacity]; + Arrays.fill( _set, FREE ); + return capacity; + } + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TObjectProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + @SuppressWarnings({"unchecked"}) + public boolean forEach( TObjectProcedure procedure ) { + Object[] set = _set; + for ( int i = set.length; i-- > 0; ) { + if ( set[i] != FREE + && set[i] != REMOVED + && !procedure.execute( (T) set[i] ) ) { + return false; + } + } + return true; + } + + + /** + * Searches the set for obj + * + * @param obj an Object value + * @return a boolean value + */ + @SuppressWarnings({"unchecked"}) + public boolean contains( Object obj ) { + return index( obj ) >= 0; + } + + + /** + * Locates the index of obj. + * + * @param obj an Object value + * @return the index of obj or -1 if it isn't in the set. + */ + protected int index( Object obj ) { + + final Object[] set = _set; + final int length = set.length; + final int hash = HashFunctions.hash( obj ) & 0x7fffffff; + int index = hash % length; + Object cur = set[index]; + + if ( cur == obj ) { + return index; + } + + if ( cur == FREE ) { + return -1; + } + + // NOTE: here it has to be REMOVED or FULL (some user-given value) + if ( cur == REMOVED || !cur.equals( obj ) ) { + // see Knuth, p. 529 + final int probe = 1 + ( hash % ( length - 2 ) ); + + do { + index -= probe; + if ( index < 0 ) { + index += length; + } + cur = set[index]; + } while ( cur != FREE + && ( cur == REMOVED || !cur.equals( obj ) ) ); + } + + return cur == FREE ? -1 : index; + } + + + /** + * Locates the index at which obj can be inserted. if + * there is already a value equal()ing obj in the set, + * returns that value's index as -index - 1. + * + * @param obj an Object value + * @return the index of a FREE slot at which obj can be inserted + * or, if obj is already stored in the hash, the negative value of + * that index, minus 1: -index -1. + */ + protected int insertionIndex( T obj ) { + + final Object[] set = _set; + final int length = set.length; + final int hash = HashFunctions.hash( obj ) & 0x7fffffff; + int index = hash % length; + Object cur = set[index]; + + if ( cur == FREE ) { + return index; // empty, all done + } else if ( cur == obj || ( cur != REMOVED && cur.equals( obj ) ) ) { + return -index - 1; // already stored + } else { // already FULL or REMOVED, must probe + // compute the double hash + final int probe = 1 + ( hash % ( length - 2 ) ); + + // if the slot we landed on is FULL (but not removed), probe + // until we find an empty slot, a REMOVED slot, or an element + // equal to the one we are trying to insert. + // finding an empty slot means that the value is not present + // and that we should use that slot as the insertion point; + // finding a REMOVED slot means that we need to keep searching, + // however we want to remember the offset of that REMOVED slot + // so we can reuse it in case a "new" insertion (i.e. not an update) + // is possible. + // finding a matching value means that we've found that our desired + // key is already in the table + if ( cur != REMOVED ) { + // starting at the natural offset, probe until we find an + // offset that isn't full. + do { + index -= probe; + if ( index < 0 ) { + index += length; + } + cur = set[index]; + } while ( cur != FREE + && cur != REMOVED + && cur != obj + && !cur.equals( obj ) ); + } + + // if the index we found was removed: continue probing until we + // locate a free location or an element which equal()s the + // one we have. + if ( cur == REMOVED ) { + int firstRemoved = index; + while ( cur != FREE + && ( cur == REMOVED || cur != obj || !cur.equals( obj ) ) ) { + index -= probe; + if ( index < 0 ) { + index += length; + } + cur = set[index]; + } + // NOTE: cur cannot == REMOVED in this block + return ( cur != FREE ) ? -index - 1 : firstRemoved; + } + // if it's full, the key is already stored + // NOTE: cur cannot equal REMOVE here (would have retuned already (see above) + return ( cur != FREE ) ? -index - 1 : index; + } + } + + + /** + * Convenience methods for subclasses to use in throwing exceptions about + * badly behaved user objects employed as keys. We have to throw an + * IllegalArgumentException with a rather verbose message telling the + * user that they need to fix their object implementation to conform + * to the general contract for java.lang.Object. + * + * @param o1 the first of the equal elements with unequal hash codes. + * @param o2 the second of the equal elements with unequal hash codes. + * @throws IllegalArgumentException the whole point of this method. + */ + protected final void throwObjectContractViolation( Object o1, Object o2 ) + throws IllegalArgumentException { + throw new IllegalArgumentException( "Equal objects must have equal hashcodes. " + + "During rehashing, Trove discovered that " + + "the following two objects claim to be " + + "equal (as in java.lang.Object.equals()) " + + "but their hashCodes (or those calculated by " + + "your TObjectHashingStrategy) are not equal." + + "This violates the general contract of " + + "java.lang.Object.hashCode(). See bullet point two " + + "in that method's documentation. " + + "object #1 =" + o1 + + "; object #2 =" + o2 ); + } + + + @Override + public void writeExternal( ObjectOutput out ) throws IOException { + + // VERSION + out.writeByte( 0 ); + + // SUPER + super.writeExternal( out ); + } + + + @Override + public void readExternal( ObjectInput in ) + throws IOException, ClassNotFoundException { + + // VERSION + in.readByte(); + + // SUPER + super.readExternal( in ); + } +} // TObjectHash diff --git a/DataExtractionOSM/src/gnu/trove/impl/hash/TPrimitiveHash.java b/DataExtractionOSM/src/gnu/trove/impl/hash/TPrimitiveHash.java new file mode 100644 index 0000000000..34749598f0 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/impl/hash/TPrimitiveHash.java @@ -0,0 +1,135 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.impl.hash; + +import gnu.trove.impl.HashFunctions; + + + +/** + * The base class for hashtables of primitive values. Since there is + * no notion of object equality for primitives, it isn't possible to + * use a `REMOVED' object to track deletions in an open-addressed table. + * So, we have to resort to using a parallel `bookkeeping' array of bytes, + * in which flags can be set to indicate that a particular slot in the + * hash table is FREE, FULL, or REMOVED. + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: TPrimitiveHash.java,v 1.1.2.6 2010/03/01 23:39:07 robeden Exp $ + */ +abstract public class TPrimitiveHash extends THash { + + /** + * flags indicating whether each position in the hash is + * FREE, FULL, or REMOVED + */ + public transient byte[] _states; + + /* constants used for state flags */ + + /** flag indicating that a slot in the hashtable is available */ + public static final byte FREE = 0; + + /** flag indicating that a slot in the hashtable is occupied */ + public static final byte FULL = 1; + + /** + * flag indicating that the value of a slot in the hashtable + * was deleted + */ + public static final byte REMOVED = 2; + + + /** + * Creates a new THash instance with the default + * capacity and load factor. + */ + public TPrimitiveHash() { + super(); + } + + + /** + * Creates a new TPrimitiveHash instance with a prime + * capacity at or near the specified capacity and with the default + * load factor. + * + * @param initialCapacity an int value + */ + public TPrimitiveHash( int initialCapacity ) { + this( initialCapacity, DEFAULT_LOAD_FACTOR ); + } + + + /** + * Creates a new TPrimitiveHash instance with a prime + * capacity at or near the minimum needed to hold + * initialCapacity elements with load factor + * loadFactor without triggering a rehash. + * + * @param initialCapacity an int value + * @param loadFactor a float value + */ + public TPrimitiveHash( int initialCapacity, float loadFactor ) { + super(); + initialCapacity = Math.max( 1, initialCapacity ); + _loadFactor = loadFactor; + setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) ); + } + + + /** + * Returns the capacity of the hash table. This is the true + * physical capacity, without adjusting for the load factor. + * + * @return the physical capacity of the hash table. + */ + public int capacity() { + return _states.length; + } + + + /** + * Delete the record at index. + * + * @param index an int value + */ + protected void removeAt( int index ) { + _states[index] = REMOVED; + super.removeAt( index ); + } + + + /** + * initializes the hashtable to a prime capacity which is at least + * initialCapacity + 1. + * + * @param initialCapacity an int value + * @return the actual capacity chosen + */ + protected int setUp( int initialCapacity ) { + int capacity; + + capacity = super.setUp( initialCapacity ); + _states = new byte[capacity]; + return capacity; + } +} // TPrimitiveHash \ No newline at end of file diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TAdvancingIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TAdvancingIterator.java new file mode 100644 index 0000000000..7ba661bee6 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TAdvancingIterator.java @@ -0,0 +1,31 @@ +// //////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// //////////////////////////////////////////////////////////////////////////// +package gnu.trove.iterator; + +/** + * Common interface for iterators that operate via the "advance" method for moving the + * cursor to the next element. + */ +public interface TAdvancingIterator extends TIterator { + /** + * Moves the iterator forward to the next entry. + * + * @throws java.util.NoSuchElementException if the iterator is already exhausted + */ + public void advance(); +} diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TFloatIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TFloatIterator.java new file mode 100644 index 0000000000..79acefcb73 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TFloatIterator.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.iterator; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Iterator for float collections. + */ +public interface TFloatIterator extends TIterator { + /** + * Advances the iterator to the next element in the underlying collection + * and returns it. + * + * @return the next float in the collection + * @exception NoSuchElementException if the iterator is already exhausted + */ + public float next(); +} diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TFloatObjectIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TFloatObjectIterator.java new file mode 100644 index 0000000000..c31483cec3 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TFloatObjectIterator.java @@ -0,0 +1,125 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.iterator; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Iterator for maps of type float and Object. + *

+ * The iterator semantics for Trove's primitive maps is slightly different + * from those defined in java.util.Iterator, but still well within + * the scope of the pattern, as defined by Gamma, et al. + *

+ * This iterator does not implicitly advance to the next entry when + * the value at the current position is retrieved. Rather, you must explicitly + * ask the iterator to advance() and then retrieve either the key(), + * the value() or both. This is done so that you have the option, but not + * the obligation, to retrieve keys and/or values as your application requires, and + * without introducing wrapper objects that would carry both. As the iteration is + * stateful, access to the key/value parts of the current map entry happens in + * constant time. + *

+ * In practice, the iterator is akin to a "search finger" that you move from + * position to position. Read or write operations affect the current entry only and + * do not assume responsibility for moving the finger. + *

+ * Here are some sample scenarios for this class of iterator: + *

+ *

+ * // accessing keys/values through an iterator:
+ * for ( TFloatObjectIterator it = map.iterator(); it.hasNext(); ) {
+ *   it.advance();
+ *   if ( satisfiesCondition( it.key() ) ) {
+ *     doSomethingWithValue( it.value() );
+ *   }
+ * }
+ * 
+ *

+ *

+ * // modifying values in-place through iteration:
+ * for ( TFloatObjectIterator it = map.iterator(); it.hasNext(); ) {
+ *   it.advance();
+ *   if ( satisfiesCondition( it.key() ) ) {
+ *     it.setValue( newValueForKey( it.key() ) );
+ *   }
+ * }
+ * 
+ *

+ *

+ * // deleting entries during iteration:
+ * for ( TFloatObjectIterator it = map.iterator(); it.hasNext(); ) {
+ *   it.advance();
+ *   if ( satisfiesCondition( it.key() ) ) {
+ *     it.remove();
+ *   }
+ * }
+ * 
+ *

+ *

+ * // faster iteration by avoiding hasNext():
+ * TFloatObjectIterator iterator = map.iterator();
+ * for ( int i = map.size(); i-- > 0; ) {
+ *   iterator.advance();
+ *   doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
+ * }
+ * 
+ * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + * @version $Id: _E_ObjectIterator.template,v 1.1.2.1 2009/09/15 02:38:31 upholderoftruth Exp $ + */ +public interface TFloatObjectIterator extends TAdvancingIterator { + + /** + * Provides access to the key of the mapping at the iterator's position. + * Note that you must advance() the iterator at least once + * before invoking this method. + * + * @return the key of the entry at the iterator's current position. + */ + public float key(); + + + /** + * Provides access to the value of the mapping at the iterator's position. + * Note that you must advance() the iterator at least once + * before invoking this method. + * + * @return the value of the entry at the iterator's current position. + */ + public V value(); + + + /** + * Replace the value of the mapping at the iterator's position with the + * specified value. Note that you must advance() the iterator at + * least once before invoking this method. + * + * @param val the value to set in the current entry + * @return the old value of the entry. + */ + public V setValue( V val ); +} diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TIntIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TIntIterator.java new file mode 100644 index 0000000000..3e1fdd2f8f --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TIntIterator.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.iterator; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Iterator for int collections. + */ +public interface TIntIterator extends TIterator { + /** + * Advances the iterator to the next element in the underlying collection + * and returns it. + * + * @return the next int in the collection + * @exception NoSuchElementException if the iterator is already exhausted + */ + public int next(); +} diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TIterator.java new file mode 100644 index 0000000000..9f6dfd57e2 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TIterator.java @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// +package gnu.trove.iterator; + +/** + * Common interface for all iterators used in Trove. + */ +public interface TIterator { + /** + * Returns true if the iterator can be advanced past its current location. + * + * @return a boolean value + */ + public boolean hasNext(); + + /** + * Removes the last entry returned by the iterator. The result of invoking this method + * more than once for a single entry is undefined and can leave the underlying data + * structure in a confused state. + */ + public void remove(); +} diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TLongIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TLongIterator.java new file mode 100644 index 0000000000..2798501573 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TLongIterator.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.iterator; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Iterator for long collections. + */ +public interface TLongIterator extends TIterator { + /** + * Advances the iterator to the next element in the underlying collection + * and returns it. + * + * @return the next long in the collection + * @exception NoSuchElementException if the iterator is already exhausted + */ + public long next(); +} diff --git a/DataExtractionOSM/src/gnu/trove/iterator/TPrimitiveIterator.java b/DataExtractionOSM/src/gnu/trove/iterator/TPrimitiveIterator.java new file mode 100644 index 0000000000..bb815145aa --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/iterator/TPrimitiveIterator.java @@ -0,0 +1,61 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.iterator; + +/** + * Implements all iterator functions for the hashed object set. + * Subclasses may override objectAtIndex to vary the object + * returned by calls to next() (e.g. for values, and Map.Entry + * objects). + *

+ *

Note that iteration is fastest if you forego the calls to + * hasNext in favor of checking the size of the structure + * yourself and then call next() that many times: + *

+ *

+ * Iterator i = collection.iterator();
+ * for (int size = collection.size(); size-- > 0;) {
+ *   Object o = i.next();
+ * }
+ * 
+ *

+ *

You may, of course, use the hasNext(), next() idiom too if + * you aren't in a performance critical spot.

+ */ +public interface TPrimitiveIterator extends TIterator { + /** + * Returns true if the iterator can be advanced past its current + * location. + * + * @return a boolean value + */ + public boolean hasNext(); + + + /** + * Removes the last entry returned by the iterator. + * Invoking this method more than once for a single entry + * will leave the underlying data structure in a confused + * state. + */ + public void remove(); + +} // TPrimitiveIterator diff --git a/DataExtractionOSM/src/gnu/trove/list/TIntList.java b/DataExtractionOSM/src/gnu/trove/list/TIntList.java new file mode 100644 index 0000000000..cf916595d6 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/list/TIntList.java @@ -0,0 +1,508 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.list; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +import gnu.trove.function.*; +import gnu.trove.procedure.*; +import gnu.trove.TIntCollection; + +import java.io.Serializable; +import java.util.Random; + + + +/** + * Interface for Trove list implementations. + */ +public interface TIntList extends TIntCollection, Serializable { + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + public int getNoEntryValue(); + + + /** + * Returns the number of values in the list. + * + * @return the number of values in the list. + */ + public int size(); + + + /** + * Tests whether this list contains any values. + * + * @return true if the list is empty. + */ + public boolean isEmpty(); + + + /** + * Adds val to the end of the list, growing as needed. + * + * @param val an int value + * @return true if the list was modified by the add operation + */ + public boolean add(int val); + + + /** + * Adds the values in the array vals to the end of the + * list, in order. + * + * @param vals an int[] value + */ + public void add( int[] vals ); + + + /** + * Adds a subset of the values in the array vals to the + * end of the list, in order. + * + * @param vals an int[] value + * @param offset the offset at which to start copying + * @param length the number of values to copy. + */ + public void add( int[] vals, int offset, int length ); + + + /** + * Inserts value into the list at offset. All + * values including and to the right of offset are shifted + * to the right. + * + * @param offset an int value + * @param value an int value + */ + public void insert( int offset, int value ); + + + /** + * Inserts the array of values into the list at + * offset. All values including and to the right of + * offset are shifted to the right. + * + * @param offset an int value + * @param values an int[] value + */ + public void insert( int offset, int[] values ); + + + /** + * Inserts a slice of the array of values into the list + * at offset. All values including and to the right of + * offset are shifted to the right. + * + * @param offset an int value + * @param values an int[] value + * @param valOffset the offset in the values array at which to + * start copying. + * @param len the number of values to copy from the values array + */ + public void insert( int offset, int[] values, int valOffset, int len ); + + + /** + * Returns the value at the specified offset. + * + * @param offset an int value + * @return an int value + */ + public int get( int offset ); + + + /** + * Sets the value at the specified offset. + * + * @param offset an int value + * @param val an int value + * + * @return The value previously at the given index. + */ + public int set( int offset, int val ); + + + /** + * Replace the values in the list starting at offset with + * the contents of the values array. + * + * @param offset the first offset to replace + * @param values the source of the new values + */ + public void set( int offset, int[] values ); + + + /** + * Replace the values in the list starting at offset with + * length values from the values array, starting + * at valOffset. + * + * @param offset the first offset to replace + * @param values the source of the new values + * @param valOffset the first value to copy from the values array + * @param length the number of values to copy + */ + public void set( int offset, int[] values, int valOffset, int length ); + + + /** + * Sets the value at the specified offset and returns the + * previously stored value. + * + * @param offset an int value + * @param val an int value + * @return the value previously stored at offset. + */ + public int replace( int offset, int val ); + + + /** + * Flushes the internal state of the list, resetting the capacity + * to the default. + */ + public void clear(); + + + /** + * Removes value from the list. + * + * @param value an int value + * @return true if the list was modified by the remove operation. + */ + public boolean remove( int value ); + + + /** + * Removes value at a given offset from the list. + * + * @param offset an int value that represents + * the offset to the element to be removed + * @return an int that is the value removed. + */ + public int removeAt( int offset ); + + + /** + * Removes length values from the list, starting at + * offset + * + * @param offset an int value + * @param length an int value + */ + public void remove( int offset, int length ); + + + /** + * Transform each value in the list using the specified function. + * + * @param function a TIntFunction value + */ + public void transformValues( TIntFunction function ); + + + /** + * Reverse the order of the elements in the list. + */ + public void reverse(); + + + /** + * Reverse the order of the elements in the range of the list. + * + * @param from the inclusive index at which to start reversing + * @param to the exclusive index at which to stop reversing + */ + public void reverse( int from, int to ); + + + /** + * Shuffle the elements of the list using the specified random + * number generator. + * + * @param rand a Random value + */ + public void shuffle( Random rand ); + + + /** + * Returns a sublist of this list. + * + * @param begin low endpoint (inclusive) of the subList. + * @param end high endpoint (exclusive) of the subList. + * @return sublist of this list from begin, inclusive to end, exclusive. + * @throws IndexOutOfBoundsException - endpoint out of range + * @throws IllegalArgumentException - endpoints out of order (end > begin) + */ + public TIntList subList( int begin, int end ); + + + /** + * Copies the contents of the list into a native array. + * + * @return an int[] value + */ + public int[] toArray(); + + + /** + * Copies a slice of the list into a native array. + * + * @param offset the offset at which to start copying + * @param len the number of values to copy. + * @return an int[] value + */ + public int[] toArray( int offset, int len ); + + + /** + * Copies a slice of the list into a native array. + * + *

If the list fits in the specified array with room to spare (i.e., + * the array has more elements than the list), the element in the array + * immediately following the end of the list is set to + * {@link #getNoEntryValue()}. + * (This is useful in determining the length of the list only if + * the caller knows that the list does not contain any "null" elements.) + * + *

NOTE: Trove does not allocate a new array if the array passed in is + * not large enough to hold all of the data elements. It will instead fill + * the array passed in. + * + * @param dest the array to copy into. + * @return the array passed in. + */ + public int[] toArray( int[] dest ); + + + /** + * Copies a slice of the list into a native array. + * + * @param dest the array to copy into. + * @param offset the offset where the first value should be copied + * @param len the number of values to copy. + * @return the array passed in. + */ + public int[] toArray( int[] dest, int offset, int len ); + + + /** + * Copies a slice of the list into a native array. + * + * @param dest the array to copy into. + * @param source_pos the offset of the first value to copy + * @param dest_pos the offset where the first value should be copied + * @param len the number of values to copy. + * @return the array passed in. + */ + public int[] toArray( int[] dest, int source_pos, int dest_pos, int len ); + + + /** + * Applies the procedure to each value in the list in ascending + * (front to back) order. + * + * @param procedure a TIntProcedure value + * @return true if the procedure did not terminate prematurely. + */ + public boolean forEach( TIntProcedure procedure ); + + + /** + * Applies the procedure to each value in the list in descending + * (back to front) order. + * + * @param procedure a TIntProcedure value + * @return true if the procedure did not terminate prematurely. + */ + public boolean forEachDescending( TIntProcedure procedure ); + + + /** + * Sort the values in the list (ascending) using the Sun quicksort + * implementation. + * + * @see java.util.Arrays#sort + */ + public void sort(); + + + /** + * Sort a slice of the list (ascending) using the Sun quicksort + * implementation. + * + * @param fromIndex the index at which to start sorting (inclusive) + * @param toIndex the index at which to stop sorting (exclusive) + * @see java.util.Arrays#sort + */ + public void sort( int fromIndex, int toIndex ); + + + /** + * Fills every slot in the list with the specified value. + * + * @param val the value to use when filling + */ + public void fill( int val ); + + + /** + * Fills a range in the list with the specified value. + * + * @param fromIndex the offset at which to start filling (inclusive) + * @param toIndex the offset at which to stop filling (exclusive) + * @param val the value to use when filling + */ + public void fill( int fromIndex, int toIndex, int val ); + + + /** + * Performs a binary search for value in the entire list. + * Note that you must @{link #sort sort} the list before + * doing a search. + * + * @param value the value to search for + * @return the absolute offset in the list of the value, or its + * negative insertion point into the sorted list. + */ + public int binarySearch( int value ); + + + /** + * Performs a binary search for value in the specified + * range. Note that you must @{link #sort sort} the list + * or the range before doing a search. + * + * @param value the value to search for + * @param fromIndex the lower boundary of the range (inclusive) + * @param toIndex the upper boundary of the range (exclusive) + * @return the absolute offset in the list of the value, or its + * negative insertion point into the sorted list. + */ + public int binarySearch( int value, int fromIndex, int toIndex ); + + + /** + * Searches the list front to back for the index of + * value. + * + * @param value an int value + * @return the first offset of the value, or -1 if it is not in + * the list. + * @see #binarySearch for faster searches on sorted lists + */ + public int indexOf( int value ); + + + /** + * Searches the list front to back for the index of + * value, starting at offset. + * + * @param offset the offset at which to start the linear search + * (inclusive) + * @param value an int value + * @return the first offset of the value, or -1 if it is not in + * the list. + * @see #binarySearch for faster searches on sorted lists + */ + public int indexOf( int offset, int value ); + + + /** + * Searches the list back to front for the last index of + * value. + * + * @param value an int value + * @return the last offset of the value, or -1 if it is not in + * the list. + * @see #binarySearch for faster searches on sorted lists + */ + public int lastIndexOf( int value ); + + + /** + * Searches the list back to front for the last index of + * value, starting at offset. + * + * @param offset the offset at which to start the linear search + * (exclusive) + * @param value an int value + * @return the last offset of the value, or -1 if it is not in + * the list. + * @see #binarySearch for faster searches on sorted lists + */ + public int lastIndexOf( int offset, int value ); + + + /** + * Searches the list for value + * + * @param value an int value + * @return true if value is in the list. + */ + public boolean contains( int value ); + + + /** + * Searches the list for values satisfying condition in + * the manner of the *nix grep utility. + * + * @param condition a condition to apply to each element in the list + * @return a list of values which match the condition. + */ + public TIntList grep( TIntProcedure condition ); + + + /** + * Searches the list for values which do not satisfy + * condition. This is akin to *nix grep -v. + * + * @param condition a condition to apply to each element in the list + * @return a list of values which do not match the condition. + */ + public TIntList inverseGrep( TIntProcedure condition ); + + + /** + * Finds the maximum value in the list. + * + * @return the largest value in the list. + * @exception IllegalStateException if the list is empty + */ + public int max(); + + + /** + * Finds the minimum value in the list. + * + * @return the smallest value in the list. + * @exception IllegalStateException if the list is empty + */ + public int min(); +} diff --git a/DataExtractionOSM/src/gnu/trove/list/array/TIntArrayList.java b/DataExtractionOSM/src/gnu/trove/list/array/TIntArrayList.java new file mode 100644 index 0000000000..7bb77b38d9 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/list/array/TIntArrayList.java @@ -0,0 +1,1016 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.list.array; + +import gnu.trove.function.TIntFunction; +import gnu.trove.list.TIntList; +import gnu.trove.procedure.TIntProcedure; +import gnu.trove.iterator.TIntIterator; +import gnu.trove.TIntCollection; +import gnu.trove.impl.*; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.util.*; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * A resizable, array-backed list of int primitives. + */ +public class TIntArrayList implements TIntList, Externalizable { + static final long serialVersionUID = 1L; + + /** the data of the list */ + protected int[] _data; + + /** the index after the last entry in the list */ + protected int _pos; + + /** the default capacity for new lists */ + protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY; + + /** the int value that represents null */ + protected int no_entry_value; + + + /** + * Creates a new TIntArrayList instance with the + * default capacity. + */ + @SuppressWarnings({"RedundantCast"}) + public TIntArrayList() { + this( DEFAULT_CAPACITY, ( int ) 0 ); + } + + + /** + * Creates a new TIntArrayList instance with the + * specified capacity. + * + * @param capacity an int value + */ + @SuppressWarnings({"RedundantCast"}) + public TIntArrayList( int capacity ) { + this( capacity, ( int ) 0 ); + } + + + /** + * Creates a new TIntArrayList instance with the + * specified capacity. + * + * @param capacity an int value + * @param no_entry_value an int value that represents null. + */ + public TIntArrayList( int capacity, int no_entry_value ) { + _data = new int[ capacity ]; + _pos = 0; + this.no_entry_value = no_entry_value; + } + + /** + * Creates a new TIntArrayList instance that contains + * a copy of the collection passed to us. + * + * @param collection the collection to copy + */ + public TIntArrayList ( TIntCollection collection ) { + this( collection.size() ); + addAll( collection ); + } + + + /** + * Creates a new TIntArrayList instance whose + * capacity is the length of values array and whose + * initial contents are the specified values. + * + * @param values an int[] value + */ + public TIntArrayList( int[] values ) { + this( values.length ); + add( values ); + } + + + /** {@inheritDoc} */ + public int getNoEntryValue() { + return no_entry_value; + } + + + // sizing + + /** + * Grow the internal array as needed to accommodate the specified number of elements. + * The size of the array bytes on each resize unless capacity requires more than twice + * the current capacity. + */ + public void ensureCapacity( int capacity ) { + if ( capacity > _data.length ) { + int newCap = Math.max( _data.length << 1, capacity ); + int[] tmp = new int[ newCap ]; + System.arraycopy( _data, 0, tmp, 0, _data.length ); + _data = tmp; + } + } + + + /** {@inheritDoc} */ + public int size() { + return _pos; + } + + + /** {@inheritDoc} */ + public boolean isEmpty() { + return _pos == 0; + } + + + /** + * Sheds any excess capacity above and beyond the current size of the list. + */ + public void trimToSize() { + if ( _data.length > size() ) { + int[] tmp = new int[ size() ]; + toArray( tmp, 0, tmp.length ); + _data = tmp; + } + } + + + // modifying + + /** {@inheritDoc} */ + public boolean add( int val ) { + ensureCapacity( _pos + 1 ); + _data[ _pos++ ] = val; + return true; + } + + + /** {@inheritDoc} */ + public void add( int[] vals ) { + add( vals, 0, vals.length ); + } + + + /** {@inheritDoc} */ + public void add( int[] vals, int offset, int length ) { + ensureCapacity( _pos + length ); + System.arraycopy( vals, offset, _data, _pos, length ); + _pos += length; + } + + + /** {@inheritDoc} */ + public void insert( int offset, int value ) { + if ( offset == _pos ) { + add( value ); + return; + } + ensureCapacity( _pos + 1 ); + // shift right + System.arraycopy( _data, offset, _data, offset + 1, _pos - offset ); + // insert + _data[ offset ] = value; + _pos++; + } + + + /** {@inheritDoc} */ + public void insert( int offset, int[] values ) { + insert( offset, values, 0, values.length ); + } + + + /** {@inheritDoc} */ + public void insert( int offset, int[] values, int valOffset, int len ) { + if ( offset == _pos ) { + add( values, valOffset, len ); + return; + } + + ensureCapacity( _pos + len ); + // shift right + System.arraycopy( _data, offset, _data, offset + len, _pos - offset ); + // insert + System.arraycopy( values, valOffset, _data, offset, len ); + _pos += len; + } + + + /** {@inheritDoc} */ + public int get( int offset ) { + if ( offset >= _pos ) { + throw new ArrayIndexOutOfBoundsException( offset ); + } + return _data[ offset ]; + } + + + /** + * Returns the value at the specified offset without doing any bounds checking. + */ + public int getQuick( int offset ) { + return _data[ offset ]; + } + + + /** {@inheritDoc} */ + public int set( int offset, int val ) { + if ( offset >= _pos ) { + throw new ArrayIndexOutOfBoundsException( offset ); + } + + int prev_val = _data[ offset ]; + _data[ offset ] = val; + return prev_val; + } + + + /** {@inheritDoc} */ + public int replace( int offset, int val ) { + if ( offset >= _pos ) { + throw new ArrayIndexOutOfBoundsException( offset ); + } + int old = _data[ offset ]; + _data[ offset ] = val; + return old; + } + + + /** {@inheritDoc} */ + public void set( int offset, int[] values ) { + set( offset, values, 0, values.length ); + } + + + /** {@inheritDoc} */ + public void set( int offset, int[] values, int valOffset, int length ) { + if ( offset < 0 || offset + length > _pos ) { + throw new ArrayIndexOutOfBoundsException( offset ); + } + System.arraycopy( values, valOffset, _data, offset, length ); + } + + + /** + * Sets the value at the specified offset without doing any bounds checking. + */ + public void setQuick( int offset, int val ) { + _data[ offset ] = val; + } + + + /** {@inheritDoc} */ + public void clear() { + clear( DEFAULT_CAPACITY ); + } + + + /** + * Flushes the internal state of the list, setting the capacity of the empty list to + * capacity. + */ + public void clear( int capacity ) { + _data = new int[ capacity ]; + _pos = 0; + } + + + /** + * Sets the size of the list to 0, but does not change its capacity. This method can + * be used as an alternative to the {@link #clear()} method if you want to recycle a + * list without allocating new backing arrays. + */ + public void reset() { + _pos = 0; + Arrays.fill( _data, no_entry_value ); + } + + + /** + * Sets the size of the list to 0, but does not change its capacity. This method can + * be used as an alternative to the {@link #clear()} method if you want to recycle a + * list without allocating new backing arrays. This method differs from + * {@link #reset()} in that it does not clear the old values in the backing array. + * Thus, it is possible for getQuick to return stale data if this method is used and + * the caller is careless about bounds checking. + */ + public void resetQuick() { + _pos = 0; + } + + + /** {@inheritDoc} */ + public boolean remove( int value ) { + for ( int index = 0; index < _pos; index++ ) { + if ( value == _data[index] ) { + remove( index, 1 ); + return true; + } + } + return false; + } + + + /** {@inheritDoc} */ + public int removeAt( int offset ) { + int old = get( offset ); + remove( offset, 1 ); + return old; + } + + + /** {@inheritDoc} */ + public void remove( int offset, int length ) { + if ( offset < 0 || offset >= _pos ) { + throw new ArrayIndexOutOfBoundsException(offset); + } + + if ( offset == 0 ) { + // data at the front + System.arraycopy( _data, length, _data, 0, _pos - length ); + } + else if ( _pos - length == offset ) { + // no copy to make, decrementing pos "deletes" values at + // the end + } + else { + // data in the middle + System.arraycopy( _data, offset + length, _data, offset, + _pos - ( offset + length ) ); + } + _pos -= length; + // no need to clear old values beyond _pos, because this is a + // primitive collection and 0 takes as much room as any other + // value + } + + + /** {@inheritDoc} */ + public TIntIterator iterator() { + return new TIntArrayIterator( 0 ); + } + + + /** {@inheritDoc} */ + public boolean containsAll( Collection collection ) { + for ( Object element : collection ) { + if ( element instanceof Integer ) { + int c = ( ( Integer ) element ).intValue(); + if ( ! contains( c ) ) { + return false; + } + } else { + return false; + } + + } + return true; + } + + + /** {@inheritDoc} */ + public boolean containsAll( TIntCollection collection ) { + if ( this == collection ) { + return true; + } + TIntIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + int element = iter.next(); + if ( ! contains( element ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean containsAll( int[] array ) { + for ( int i = array.length; i-- > 0; ) { + if ( ! contains( array[i] ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean addAll( Collection collection ) { + boolean changed = false; + for ( Integer element : collection ) { + int e = element.intValue(); + if ( add( e ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean addAll( TIntCollection collection ) { + boolean changed = false; + TIntIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + int element = iter.next(); + if ( add( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean addAll( int[] array ) { + boolean changed = false; + for ( int element : array ) { + if ( add( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"SuspiciousMethodCalls"}) + public boolean retainAll( Collection collection ) { + boolean modified = false; + TIntIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + + /** {@inheritDoc} */ + public boolean retainAll( TIntCollection collection ) { + if ( this == collection ) { + return false; + } + boolean modified = false; + TIntIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( iter.next() ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + + /** {@inheritDoc} */ + public boolean retainAll( int[] array ) { + boolean changed = false; + Arrays.sort( array ); + int[] data = _data; + + for ( int i = data.length; i-- > 0; ) { + if ( Arrays.binarySearch( array, data[i] ) < 0 ) { + remove( i, 1 ); + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( Collection collection ) { + boolean changed = false; + for ( Object element : collection ) { + if ( element instanceof Integer ) { + int c = ( ( Integer ) element ).intValue(); + if ( remove( c ) ) { + changed = true; + } + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( TIntCollection collection ) { + if ( collection == this ) { + clear(); + return true; + } + boolean changed = false; + TIntIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + int element = iter.next(); + if ( remove( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( int[] array ) { + boolean changed = false; + for ( int i = array.length; i-- > 0; ) { + if ( remove(array[i]) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public void transformValues( TIntFunction function ) { + for ( int i = _pos; i-- > 0; ) { + _data[ i ] = function.execute( _data[ i ] ); + } + } + + + /** {@inheritDoc} */ + public void reverse() { + reverse( 0, _pos ); + } + + + /** {@inheritDoc} */ + public void reverse( int from, int to ) { + if ( from == to ) { + return; // nothing to do + } + if ( from > to ) { + throw new IllegalArgumentException( "from cannot be greater than to" ); + } + for ( int i = from, j = to - 1; i < j; i++, j-- ) { + swap( i, j ); + } + } + + + /** {@inheritDoc} */ + public void shuffle( Random rand ) { + for ( int i = _pos; i-- > 1; ) { + swap( i, rand.nextInt( i ) ); + } + } + + + /** + * Swap the values at offsets i and j. + * + * @param i an offset into the data array + * @param j an offset into the data array + */ + private void swap( int i, int j ) { + int tmp = _data[ i ]; + _data[ i ] = _data[ j ]; + _data[ j ] = tmp; + } + + + // copying + + /** {@inheritDoc} */ + public TIntList subList( int begin, int end ) { + if ( end < begin ) { + throw new IllegalArgumentException( "end index " + end + + " greater than begin index " + begin ); + } + if ( begin < 0 ) { + throw new IndexOutOfBoundsException( "begin index can not be < 0" ); + } + if ( end > _data.length ) { + throw new IndexOutOfBoundsException( "end index < " + _data.length ); + } + TIntArrayList list = new TIntArrayList( end - begin ); + for ( int i = begin; i < end; i++ ) { + list.add( _data[ i ] ); + } + return list; + } + + + /** {@inheritDoc} */ + public int[] toArray() { + return toArray( 0, _pos ); + } + + + /** {@inheritDoc} */ + public int[] toArray( int offset, int len ) { + int[] rv = new int[ len ]; + toArray( rv, offset, len ); + return rv; + } + + + /** {@inheritDoc} */ + public int[] toArray( int[] dest ) { + int len = dest.length; + if ( dest.length > _pos ) { + len = _pos; + dest[len] = no_entry_value; + } + toArray( dest, 0, len ); + return dest; + } + + + /** {@inheritDoc} */ + public int[] toArray( int[] dest, int offset, int len ) { + if ( len == 0 ) { + return dest; // nothing to copy + } + if ( offset < 0 || offset >= _pos ) { + throw new ArrayIndexOutOfBoundsException( offset ); + } + System.arraycopy( _data, offset, dest, 0, len ); + return dest; + } + + + /** {@inheritDoc} */ + public int[] toArray( int[] dest, int source_pos, int dest_pos, int len ) { + if ( len == 0 ) { + return dest; // nothing to copy + } + if ( source_pos < 0 || source_pos >= _pos ) { + throw new ArrayIndexOutOfBoundsException( source_pos ); + } + System.arraycopy( _data, source_pos, dest, dest_pos, len ); + return dest; + } + + + // comparing + + /** {@inheritDoc} */ + @Override + public boolean equals( Object other ) { + if ( other == this ) { + return true; + } + else if ( other instanceof TIntArrayList ) { + TIntArrayList that = ( TIntArrayList )other; + if ( that.size() != this.size() ) return false; + else { + for ( int i = _pos; i-- > 0; ) { + if ( this._data[ i ] != that._data[ i ] ) { + return false; + } + } + return true; + } + } + else return false; + } + + + /** {@inheritDoc} */ + @Override + public int hashCode() { + int h = 0; + for ( int i = _pos; i-- > 0; ) { + h += HashFunctions.hash( _data[ i ] ); + } + return h; + } + + + // procedures + + /** {@inheritDoc} */ + public boolean forEach( TIntProcedure procedure ) { + for ( int i = 0; i < _pos; i++ ) { + if ( !procedure.execute( _data[ i ] ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean forEachDescending( TIntProcedure procedure ) { + for ( int i = _pos; i-- > 0; ) { + if ( !procedure.execute( _data[ i ] ) ) { + return false; + } + } + return true; + } + + + // sorting + + /** {@inheritDoc} */ + public void sort() { + Arrays.sort( _data, 0, _pos ); + } + + + /** {@inheritDoc} */ + public void sort( int fromIndex, int toIndex ) { + Arrays.sort( _data, fromIndex, toIndex ); + } + + + // filling + + /** {@inheritDoc} */ + public void fill( int val ) { + Arrays.fill( _data, 0, _pos, val ); + } + + + /** {@inheritDoc} */ + public void fill( int fromIndex, int toIndex, int val ) { + if ( toIndex > _pos ) { + ensureCapacity( toIndex ); + _pos = toIndex; + } + Arrays.fill( _data, fromIndex, toIndex, val ); + } + + + // searching + + /** {@inheritDoc} */ + public int binarySearch( int value ) { + return binarySearch( value, 0, _pos ); + } + + + /** {@inheritDoc} */ + public int binarySearch(int value, int fromIndex, int toIndex) { + if ( fromIndex < 0 ) { + throw new ArrayIndexOutOfBoundsException( fromIndex ); + } + if ( toIndex > _pos ) { + throw new ArrayIndexOutOfBoundsException( toIndex ); + } + + int low = fromIndex; + int high = toIndex - 1; + + while ( low <= high ) { + int mid = ( low + high ) >>> 1; + int midVal = _data[ mid ]; + + if ( midVal < value ) { + low = mid + 1; + } + else if ( midVal > value ) { + high = mid - 1; + } + else { + return mid; // value found + } + } + return -( low + 1 ); // value not found. + } + + + /** {@inheritDoc} */ + public int indexOf( int value ) { + return indexOf( 0, value ); + } + + + /** {@inheritDoc} */ + public int indexOf( int offset, int value ) { + for ( int i = offset; i < _pos; i++ ) { + if ( _data[ i ] == value ) { + return i; + } + } + return -1; + } + + + /** {@inheritDoc} */ + public int lastIndexOf( int value ) { + return lastIndexOf( _pos, value ); + } + + + /** {@inheritDoc} */ + public int lastIndexOf( int offset, int value ) { + for ( int i = offset; i-- > 0; ) { + if ( _data[ i ] == value ) { + return i; + } + } + return -1; + } + + + /** {@inheritDoc} */ + public boolean contains( int value ) { + return lastIndexOf( value ) >= 0; + } + + + /** {@inheritDoc} */ + public TIntList grep( TIntProcedure condition ) { + TIntArrayList list = new TIntArrayList(); + for ( int i = 0; i < _pos; i++ ) { + if ( condition.execute( _data[ i ] ) ) { + list.add( _data[ i ] ); + } + } + return list; + } + + + /** {@inheritDoc} */ + public TIntList inverseGrep( TIntProcedure condition ) { + TIntArrayList list = new TIntArrayList(); + for ( int i = 0; i < _pos; i++ ) { + if ( !condition.execute( _data[ i ] ) ) { + list.add( _data[ i ] ); + } + } + return list; + } + + + /** {@inheritDoc} */ + public int max() { + if ( size() == 0 ) { + throw new IllegalStateException("cannot find maximum of an empty list"); + } + int max = Integer.MIN_VALUE; + for ( int i = 0; i < _pos; i++ ) { + if ( _data[ i ] > max ) { + max = _data[ i ]; + } + } + return max; + } + + + /** {@inheritDoc} */ + public int min() { + if ( size() == 0 ) { + throw new IllegalStateException( "cannot find minimum of an empty list" ); + } + int min = Integer.MAX_VALUE; + for ( int i = 0; i < _pos; i++ ) { + if ( _data[i] < min ) { + min = _data[i]; + } + } + return min; + } + + + // stringification + + /** {@inheritDoc} */ + @Override + public String toString() { + final StringBuilder buf = new StringBuilder( "{" ); + for ( int i = 0, end = _pos - 1; i < end; i++ ) { + buf.append( _data[ i ] ); + buf.append( ", " ); + } + if ( size() > 0 ) { + buf.append( _data[ _pos - 1 ] ); + } + buf.append( "}" ); + return buf.toString(); + } + + + /** TIntArrayList iterator */ + class TIntArrayIterator implements TIntIterator { + + /** Index of element to be returned by subsequent call to next. */ + private int cursor = 0; + + /** + * Index of element returned by most recent call to next or + * previous. Reset to -1 if this element is deleted by a call + * to remove. + */ + int lastRet = -1; + + + TIntArrayIterator( int index ) { + cursor = index; + } + + + /** {@inheritDoc} */ + public boolean hasNext() { + return cursor < size(); + } + + + /** {@inheritDoc} */ + public int next() { + try { + int next = get( cursor ); + lastRet = cursor++; + return next; + } catch ( IndexOutOfBoundsException e ) { + throw new NoSuchElementException(); + } + } + + + /** {@inheritDoc} */ + public void remove() { + if ( lastRet == -1 ) + throw new IllegalStateException(); + + try { + TIntArrayList.this.remove( lastRet, 1); + if ( lastRet < cursor ) + cursor--; + lastRet = -1; + } catch ( IndexOutOfBoundsException e ) { + throw new ConcurrentModificationException(); + } + } + } + + + public void writeExternal( ObjectOutput out ) throws IOException { + // VERSION + out.writeByte( 0 ); + + // POSITION + out.writeInt( _pos ); + + // NO_ENTRY_VALUE + out.writeInt( no_entry_value ); + + // ENTRIES + int len = _data.length; + out.writeInt( len ); + for( int i = 0; i < len; i++ ) { + out.writeInt( _data[ i ] ); + } + } + + + public void readExternal( ObjectInput in ) + throws IOException, ClassNotFoundException { + + // VERSION + in.readByte(); + + // POSITION + _pos = in.readInt(); + + // NO_ENTRY_VALUE + no_entry_value = in.readInt(); + + // ENTRIES + int len = in.readInt(); + _data = new int[ len ]; + for( int i = 0; i < len; i++ ) { + _data[ i ] = in.readInt(); + } + } +} // TIntArrayList diff --git a/DataExtractionOSM/src/gnu/trove/map/TFloatObjectMap.java b/DataExtractionOSM/src/gnu/trove/map/TFloatObjectMap.java new file mode 100644 index 0000000000..32b8665db3 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/map/TFloatObjectMap.java @@ -0,0 +1,425 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.map; + +import gnu.trove.iterator.TFloatObjectIterator; +import gnu.trove.procedure.TFloatProcedure; +import gnu.trove.procedure.TObjectProcedure; +import gnu.trove.procedure.TFloatObjectProcedure; +import gnu.trove.function.TObjectFunction; +import gnu.trove.set.TFloatSet; + +import java.util.Collection; +import java.util.Map; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for a primitive map of float keys and Object values. + */ +public interface TFloatObjectMap { + +// Query Operations + + /** + * Returns the value that represents null in the {@link #keySet()}. + * The default value is generally zero, but can be changed during + * construction of the collection. + * + * @return the value that represents a null value in this collection. + */ + float getNoEntryKey(); + + + /** + * Returns the number of key-value mappings in this map. If the + * map contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of key-value mappings in this map + */ + int size(); + + + /** + * Returns true if this map contains no key-value mappings. + * + * @return true if this map contains no key-value mappings + */ + boolean isEmpty(); + + + /** + * Returns true if this map contains a mapping for the specified + * key. More formally, returns true if and only if + * this map contains a mapping for a key k such that + * key.equals(k). (There can be at most one such mapping.) + * + * @param key key whose presence in this map is to be tested + * @return true if this map contains a mapping for the specified + * key + * @throws ClassCastException if the key is of an inappropriate type for + * this map (optional) + * @throws NullPointerException if the specified key is null and this map + * does not permit null keys (optional) + */ + boolean containsKey( float key ); + + + /** + * Returns true if this map maps one or more keys to the + * specified value. More formally, returns true if and only if + * this map contains at least one mapping to a value v such that + * (value==null ? v==null : value.equals(v)). This operation + * will probably require time linear in the map size for most + * implementations of the Map interface. + * + * @param value value whose presence in this map is to be tested + * @return true if this map maps one or more keys to the + * specified value + * @throws ClassCastException if the value is of an inappropriate type for + * this map (optional) + * @throws NullPointerException if the specified value is null and this + * map does not permit null values (optional) + */ + boolean containsValue( Object value ); + + + /** + * Returns the value to which the specified key is mapped, + * or {@code null} if this map contains no mapping for the key. + * + *

More formally, if this map contains a mapping from a key + * {@code k} to a value {@code v} such that {@code (key==null ? k==null : + * key.equals(k))}, then this method returns {@code v}; otherwise + * it returns {@code null}. (There can be at most one such mapping.) + * + *

If this map permits null values, then a return value of + * {@code null} does not necessarily indicate that the map + * contains no mapping for the key; it's also possible that the map + * explicitly maps the key to {@code null}. The {@link #containsKey + * containsKey} operation may be used to distinguish these two cases. + * + * @param key the key whose associated value is to be returned + * @return the float value to which the specified key is mapped, or + * {@code null} if this map contains no mapping for the key + * @throws ClassCastException if the key is of an inappropriate type for + * this map (optional) + * @throws NullPointerException if the specified key is null and this map + * does not permit null keys (optional) + */ + V get( float key ); + + + // Modification Operations + + /** + * Associates the specified value with the specified key in this map + * (optional operation). If the map previously contained a mapping for + * the key, the old value is replaced by the specified value. (A map + * m is said to contain a mapping for a key k if and only + * if {@link #containsKey(float) m.containsKey(k)} would return + * true.) + * + * @param key key with which the specified value is to be associated + * @param value an float value value to be associated with the specified key + * @return the previous value associated with key, or + * no_entry_value if there was no mapping for key. + * (A no_entry_value return can also indicate that the map + * previously associated null with key, + * if the implementation supports null values.) + * @throws UnsupportedOperationException if the put operation + * is not supported by this map + * @throws ClassCastException if the class of the specified key or value + * prevents it from being stored in this map + * @throws NullPointerException if the specified key or value is null + * and this map does not permit null keys or values + * @throws IllegalArgumentException if some property of the specified key + * or value prevents it from being stored in this map + * @see #getNoEntryKey() + */ + V put( float key, V value); + + + /** + * Inserts a key/value pair into the map if the specified key is not already + * associated with a value. + * + * @param key key with which the specified value is to be associated + * @param value an float value to be associated with the specified key + * + * @return the previous value associated with key, or null + * if none was found. + */ + V putIfAbsent( float key, V value ); + + + /** + * Removes the mapping for a key from this map if it is present + * (optional operation). More formally, if this map contains a mapping + * from key k to value v such that + * key.equals(k), that mapping + * is removed. (The map can contain at most one such mapping.) + * + *

Returns the value to which this map previously associated the key, + * or null if the map contained no mapping for the key. + * + *

If this map permits null values, then a return value of + * null does not necessarily indicate that the map + * contained no mapping for the key; it's also possible that the map + * explicitly mapped the key to null. + * + *

The map will not contain a mapping for the specified key once the + * call returns. + * + * @param key key whose mapping is to be removed from the map + * @return the previous float value associated with key, or + * null if there was no mapping for key. + * @throws UnsupportedOperationException if the remove operation + * is not supported by this map + * @throws ClassCastException if the key is of an inappropriate type for + * this map (optional) + * @throws NullPointerException if the specified key is null and this + * map does not permit null keys (optional) + */ + V remove( float key ); + + + // Bulk Operations + + /** + * Copies all of the mappings from the specified map to this map + * (optional operation). The effect of this call is equivalent to that + * of calling {@link #put(float,Object) put(k, v)} on this map once + * for each mapping from key k to value v in the + * specified map. The behavior of this operation is undefined if the + * specified map is modified while the operation is in progress. + * + * @param m mappings to be stored in this map + * @throws UnsupportedOperationException if the putAll operation + * is not supported by this map + * @throws ClassCastException if the class of a key or value in the + * specified map prevents it from being stored in this map + * @throws NullPointerException if the specified map is null, or if + * this map does not permit null keys or values, and the + * specified map contains null keys or values + * @throws IllegalArgumentException if some property of a key or value in + * the specified map prevents it from being stored in this map + */ + void putAll( Map m); + + + /** + * Put all the entries from the given map into this map. + * + * @param map The map from which entries will be obtained to put into this map. + */ + void putAll( TFloatObjectMap map ); + + + /** + * Removes all of the mappings from this map (optional operation). + * The map will be empty after this call returns. + * + * @throws UnsupportedOperationException if the clear operation + * is not supported by this map + */ + void clear(); + + + // Views + + /** + * Returns a {@link TFloatSet} view of the keys contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. If the map is modified + * while an iteration over the set is in progress (except through + * the iterator's own remove operation), the results of + * the iteration are undefined. The set supports element removal, + * which removes the corresponding mapping from the map, via the + * Iterator.remove, Set.remove, + * removeAll, retainAll, and clear + * operations. It does not support the add or addAll + * operations. + * + * @return a set view of the keys contained in this map + */ + TFloatSet keySet(); + + + /** + * Returns a copy of the keys of the map as an array. + * Changes to the array of keys will not be reflected in the map + * nor vice-versa. + * + * @return a copy of the keys of the map as an array. + */ + float[] keys(); + + + /** + * Returns a copy of the keys of the map as an array. + * Changes to the array of keys will not be reflected in the map + * nor vice-versa. + * + * @param array the array into which the elements of the list are to be stored, + * if it is big enough; otherwise, a new array of the same type is + * allocated for this purpose. + * @return the keys of the map as an array. + */ + float[] keys( float[] array ); + + + + /** + * Returns a {@link Collection} view of the values contained in this map. + * The collection is backed by the map, so changes to the map are + * reflected in the collection, and vice-versa. If the map is + * modified while an iteration over the collection is in progress + * (except through the iterator's own remove operation), + * the results of the iteration are undefined. The collection + * supports element removal, which removes the corresponding + * mapping from the map, via the Iterator.remove, + * Collection.remove, removeAll, + * retainAll and clear operations. It does not + * support the add or addAll operations. + * + * @return a collection view of the values contained in this map + */ + Collection valueCollection(); + + + /** + * Returns the values of the map as an array of float values. + * Changes to the array of values will not be reflected in the map + * nor vice-versa. + * + * @return the values of the map as an array of float values. + */ + V[] values(); + + + /** + * Returns the values of the map using an existing array. + * Changes to the array of values will not be reflected in the map + * nor vice-versa. + * + * @param array the array into which the elements of the list are to be stored, + * if it is big enough; otherwise, a new array of the same type is + * allocated for this purpose. + * @return the values of the map as an array of float values. + */ + T[] values( T[] array ); + + + /** + * Returns a TFloatObjectIterator with access to this map's keys and values. + * + * @return a TFloatObjectIterator with access to this map's keys and values. + */ + public TFloatObjectIterator iterator(); + + + /** + * Executes procedure for each key in the map. + * + * @param procedure a TObjectProcedure value + * @return false if the loop over the keys terminated because + * the procedure returned false for some key. + */ + public boolean forEachKey( TFloatProcedure procedure ); + + + /** + * Executes procedure for each value in the map. + * + * @param procedure a TObjectProcedure value + * @return false if the loop over the values terminated because + * the procedure returned false for some value. + */ + public boolean forEachValue( TObjectProcedure procedure ); + + + /** + * Executes procedure for each key/value entry in the + * map. + * + * @param procedure a TFloatObjectProcedure value + * @return false if the loop over the entries terminated because + * the procedure returned false for some entry. + */ + public boolean forEachEntry( TFloatObjectProcedure procedure ); + + + /** + * Transform the values in this map using function. + * + * @param function a TObjectFunction value + */ + public void transformValues( TObjectFunction function ); + + + /** + * Retains only those entries in the map for which the procedure + * returns a true value. + * + * @param procedure determines which entries to keep + * @return true if the map was modified. + */ + public boolean retainEntries( TFloatObjectProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this map for equality. Returns + * true if the given object is also a map and the two maps + * represent the same mappings. More formally, two maps m1 and + * m2 represent the same mappings if + * m1.entrySet().equals(m2.entrySet()). This ensures that the + * equals method works properly across different implementations + * of the Map interface. + * + * @param o object to be compared for equality with this map + * @return true if the specified object is equal to this map + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this map. The hash code of a map is + * defined to be the sum of the hash codes of each entry in the map's + * entrySet() view. This ensures that m1.equals(m2) + * implies that m1.hashCode()==m2.hashCode() for any two maps + * m1 and m2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this map + + * @see Object#equals(Object) + * @see #equals(Object) + */ + int hashCode(); +} diff --git a/DataExtractionOSM/src/gnu/trove/map/hash/TFloatObjectHashMap.java b/DataExtractionOSM/src/gnu/trove/map/hash/TFloatObjectHashMap.java new file mode 100644 index 0000000000..51a6eacc35 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/map/hash/TFloatObjectHashMap.java @@ -0,0 +1,1025 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.map.hash; + +import gnu.trove.map.TFloatObjectMap; +import gnu.trove.impl.Constants; +import gnu.trove.impl.HashFunctions; +import gnu.trove.impl.hash.*; +import gnu.trove.procedure.TFloatObjectProcedure; +import gnu.trove.procedure.TFloatProcedure; +import gnu.trove.procedure.TObjectProcedure; +import gnu.trove.iterator.TFloatIterator; +import gnu.trove.iterator.TFloatObjectIterator; +import gnu.trove.iterator.TPrimitiveIterator; +import gnu.trove.function.TObjectFunction; +import gnu.trove.set.TFloatSet; +import gnu.trove.TFloatCollection; + +import java.io.*; +import java.util.*; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * An open addressed Map implementation for float keys and Object values. + * + * Created: Sun Nov 4 08:52:45 2001 + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + */ +public class TFloatObjectHashMap extends TFloatHash implements + TFloatObjectMap, Externalizable { + + static final long serialVersionUID = 1L; + + private final TFloatObjectProcedure PUT_ALL_PROC = new TFloatObjectProcedure() { + public boolean execute( float key, V value) { + put( key, value ); + return true; + } + }; + + /** the values of the map */ + protected transient V[] _values; + + /** the value that represents null in the key set. */ + protected float no_entry_key; + + + /** + * Creates a new TFloatObjectHashMap instance with the default + * capacity and load factor. + */ + public TFloatObjectHashMap() { + super(); + } + + + /** + * Creates a new TFloatObjectHashMap instance with a prime + * capacity equal to or greater than initialCapacity and + * with the default load factor. + * + * @param initialCapacity an int value + */ + public TFloatObjectHashMap( int initialCapacity ) { + super( initialCapacity ); + no_entry_key = Constants.DEFAULT_FLOAT_NO_ENTRY_VALUE; + } + + + /** + * Creates a new TFloatObjectHashMap instance with a prime + * capacity equal to or greater than initialCapacity and + * with the specified load factor. + * + * @param initialCapacity an int value + * @param loadFactor a float value + */ + public TFloatObjectHashMap( int initialCapacity, float loadFactor ) { + super( initialCapacity, loadFactor ); + no_entry_key = Constants.DEFAULT_FLOAT_NO_ENTRY_VALUE; + } + + + /** + * Creates a new TFloatObjectHashMap instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param loadFactor used to calculate the threshold over which + * rehashing takes place. + * @param noEntryKey the value used to represent null in the key set. + */ + public TFloatObjectHashMap( int initialCapacity, float loadFactor, float noEntryKey ) { + super( initialCapacity, loadFactor ); + this.no_entry_value = noEntryKey; + } + + + /** + * Creates a new TFloatObjectHashMap that contains the entries + * in the map passed to it. + * + * @param map the TFloatObjectMap to be copied. + */ + public TFloatObjectHashMap( TFloatObjectMap map ) { + this( map.size(), 0.5f, map.getNoEntryKey() ); + putAll( map ); + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + protected int setUp( int initialCapacity ) { + int capacity; + + capacity = super.setUp( initialCapacity ); + _values = ( V[] ) new Object[capacity]; + return capacity; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + protected void rehash( int newCapacity ) { + int oldCapacity = _set.length; + + float oldKeys[] = _set; + V oldVals[] = _values; + byte oldStates[] = _states; + + _set = new float[newCapacity]; + _values = (V[]) new Object[newCapacity]; + _states = new byte[newCapacity]; + + for ( int i = oldCapacity; i-- > 0; ) { + if( oldStates[i] == FULL ) { + float o = oldKeys[i]; + int index = insertionIndex(o); + _set[index] = o; + _values[index] = oldVals[i]; + _states[index] = FULL; + } + } + } + + + // Query Operations + + /** {@inheritDoc} */ + public float getNoEntryKey() { + return no_entry_key; + } + + + /** {@inheritDoc} */ + public boolean containsKey( float key ) { + return contains( key ); + } + + + /** {@inheritDoc} */ + public boolean containsValue( Object val ) { + byte[] states = _states; + V[] vals = _values; + + // special case null values so that we don't have to + // perform null checks before every call to equals() + if ( null == val ) { + for ( int i = vals.length; i-- > 0; ) { + if ( states[i] == FULL && val == vals[i] ) { + return true; + } + } + } else { + for ( int i = vals.length; i-- > 0; ) { + if ( states[i] == FULL && + ( val == vals[i] || val.equals( vals[i] ) ) ) { + return true; + } + } + } // end of else + return false; + } + + + /** {@inheritDoc} */ + public V get( float key ) { + int index = index( key ); + return index < 0 ? null : _values[index]; + } + + + // Modification Operations + + /** {@inheritDoc} */ + public V put( float key, V value ) { + int index = insertionIndex( key ); + return doPut( key, value, index ); + } + + + /** {@inheritDoc} */ + public V putIfAbsent( float key, V value ) { + int index = insertionIndex( key ); + if ( index < 0 ) + return _values[-index - 1]; + return doPut( key, value, index ); + } + + + @SuppressWarnings({"unchecked"}) + private V doPut( float key, V value, int index ) { + byte previousState; + V previous = null; + boolean isNewMapping = true; + if ( index < 0 ) { + index = -index -1; + previous = _values[index]; + isNewMapping = false; + } + previousState = _states[index]; + _set[index] = key; + _states[index] = FULL; + _values[index] = value; + if (isNewMapping) { + postInsertHook( previousState == FREE ); + } + + return previous; + } + + + /** {@inheritDoc} */ + public V remove( float key ) { + V prev = null; + int index = index( key ); + if ( index >= 0 ) { + prev = _values[index]; + removeAt( index ); // clear key,state; adjust size + } + return prev; + } + + + /** {@inheritDoc} */ + protected void removeAt( int index ) { + _values[index] = null; + super.removeAt( index ); // clear key, state; adjust size + } + + + // Bulk Operations + + /** {@inheritDoc} */ + public void putAll( Map map ) { + Set> set = map.entrySet(); + for ( Map.Entry entry : set ) { + put( entry.getKey(), entry.getValue() ); + } + } + + + /** {@inheritDoc} */ + public void putAll( TFloatObjectMap map ){ + map.forEachEntry( PUT_ALL_PROC ); + } + + + /** {@inheritDoc} */ + public void clear() { + super.clear(); + Arrays.fill( _set, 0, _set.length, no_entry_key ); + Arrays.fill( _states, 0, _states.length, FREE ); + Arrays.fill( _values, 0, _values.length, null ); + } + + + // Views + + /** {@inheritDoc} */ + public TFloatSet keySet() { + return new KeyView(); + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + public float[] keys() { + float[] keys = new float[size()]; + float[] k = _set; + byte[] states = _states; + + for ( int i = k.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + keys[j++] = k[i]; + } + } + return keys; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + public float[] keys( float[] dest ) { + if ( dest.length < _size ) { + dest = new float[_size]; + } + + float[] k = _set; + byte[] states = _states; + + for ( int i = k.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + dest[j++] = k[i]; + } + } + return dest; + } + + + /** {@inheritDoc} */ + public Collection valueCollection() { + return new ValueView(); + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + public V[] values() { + V[] vals = ( V[] ) new Object[size()]; + V[] v = _values; + byte[] states = _states; + + for ( int i = v.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + vals[j++] = v[i]; + } + } + return vals; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + public T[] values( T[] dest ) { + if ( dest.length < _size ) { + dest = ( T[] ) java.lang.reflect.Array.newInstance( + dest.getClass().getComponentType(), _size); + } + + V[] v = _values; + byte[] states = _states; + + for ( int i = v.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + dest[j++] = ( T ) v[i]; + } + } + return dest; + } + + + /** {@inheritDoc} */ + public TFloatObjectIterator iterator() { + return new TFloatObjectHashIterator( this ); + } + + + /** {@inheritDoc} */ + public boolean forEachKey( TFloatProcedure procedure ) { + return forEach( procedure ); + } + + + /** {@inheritDoc} */ + public boolean forEachValue( TObjectProcedure procedure ) { + byte[] states = _states; + V[] values = _values; + for ( int i = values.length; i-- > 0; ) { + if ( states[i] == FULL && ! procedure.execute( values[i] ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + public boolean forEachEntry( TFloatObjectProcedure procedure ) { + byte[] states = _states; + float[] keys = _set; + V[] values = _values; + for (int i = keys.length; i-- > 0;) { + if (states[i] == FULL && ! procedure.execute(keys[i],values[i])) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"unchecked"}) + public boolean retainEntries( TFloatObjectProcedure procedure ) { + boolean modified = false; + byte[] states = _states; + float[] keys = _set; + V[] values = _values; + + // Temporarily disable compaction. This is a fix for bug #1738760 + tempDisableAutoCompaction(); + try { + for ( int i = keys.length; i-- > 0; ) { + if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { + removeAt( i ); + modified = true; + } + } + } + finally { + reenableAutoCompaction( true ); + } + + return modified; + } + + + /** {@inheritDoc} */ + public void transformValues( TObjectFunction function ) { + byte[] states = _states; + V[] values = _values; + for ( int i = values.length; i-- > 0; ) { + if ( states[i] == FULL ) { + values[i] = function.execute( values[i] ); + } + } + } + + + // Comparison and hashing + + /** {@inheritDoc} */ + public boolean equals( Object other ) { + if ( ! ( other instanceof TFloatObjectMap ) ) { + return false; + } + TFloatObjectMap that = ( TFloatObjectMap ) other; + if ( that.size() != this.size() ) { + return false; + } + try { + TFloatObjectIterator iter = this.iterator(); + while ( iter.hasNext() ) { + iter.advance(); + float key = iter.key(); + Object value = iter.value(); + if ( value == null ) { + if ( !( that.get( key ) == null && that.containsKey( key ) ) ) { + return false; + } + } else { + if ( !value.equals( that.get( key ) ) ) { + return false; + } + } + } + } catch ( ClassCastException ex ) { + // unused. + } + return true; + } + + + /** {@inheritDoc} */ + public int hashCode() { + int hashcode = 0; + V[] values = _values; + byte[] states = _states; + for ( int i = values.length; i-- > 0; ) { + if ( states[i] == FULL ) { + hashcode += HashFunctions.hash( _set[i] ) ^ + ( values[i] == null ? 0 : values[i].hashCode() ); + } + } + return hashcode; + } + + + class KeyView implements TFloatSet { + + /** {@inheritDoc} */ + public float getNoEntryValue() { + return no_entry_key; + } + + /** {@inheritDoc} */ + public int size() { + return _size; + } + + /** {@inheritDoc} */ + public boolean isEmpty() { + return _size == 0; + } + + /** {@inheritDoc} */ + public boolean contains( float entry ) { + return TFloatObjectHashMap.this.containsKey( entry ); + } + + /** {@inheritDoc} */ + public TFloatIterator iterator() { + return new TFloatHashIterator( TFloatObjectHashMap.this ); + } + + /** {@inheritDoc} */ + public float[] toArray() { + return keys(); + } + + /** {@inheritDoc} */ + public float[] toArray( float[] dest ) { + return keys( dest ); + } + + /** {@inheritDoc} */ + public boolean add( float entry ) { + throw new UnsupportedOperationException(); + } + + /** {@inheritDoc} */ + public boolean remove( float entry ) { + return null != TFloatObjectHashMap.this.remove( entry ); + } + + /** {@inheritDoc} */ + public boolean containsAll( Collection collection ) { + for ( Object element : collection ) { + if ( ! TFloatObjectHashMap.this.containsKey( ( ( Float ) element ).floatValue() ) ) { + return false; + } + } + return true; + } + + /** {@inheritDoc} */ + public boolean containsAll( TFloatCollection collection ) { + if ( collection == this ) { + return true; + } + TFloatIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + if ( ! TFloatObjectHashMap.this.containsKey( iter.next() ) ) { + return false; + } + } + return true; + } + + /** {@inheritDoc} */ + public boolean containsAll( float[] array ) { + for ( float element : array ) { + if ( ! TFloatObjectHashMap.this.containsKey( element ) ) { + return false; + } + } + return true; + } + + /** {@inheritDoc} */ + public boolean addAll( Collection collection ) { + throw new UnsupportedOperationException(); + } + + /** {@inheritDoc} */ + public boolean addAll( TFloatCollection collection ) { + throw new UnsupportedOperationException(); + } + + /** {@inheritDoc} */ + public boolean addAll( float[] array ) { + throw new UnsupportedOperationException(); + } + + /** {@inheritDoc} */ + public boolean retainAll( Collection collection ) { + boolean modified = false; + TFloatIterator iter = iterator(); + while ( iter.hasNext() ) { + //noinspection SuspiciousMethodCalls + if ( ! collection.contains( Float.valueOf ( iter.next() ) ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + /** {@inheritDoc} */ + public boolean retainAll( TFloatCollection collection ) { + if ( this == collection ) { + return false; + } + boolean modified = false; + TFloatIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( iter.next() ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + /** {@inheritDoc} */ + public boolean retainAll( float[] array ) { + boolean changed = false; + Arrays.sort( array ); + float[] set = _set; + byte[] states = _states; + + for ( int i = set.length; i-- > 0; ) { + if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { + removeAt( i ); + changed = true; + } + } + return changed; + } + + /** {@inheritDoc} */ + public boolean removeAll( Collection collection ) { + boolean changed = false; + for ( Object element : collection ) { + if ( element instanceof Float ) { + float c = ( ( Float ) element ).floatValue(); + if ( remove( c ) ) { + changed = true; + } + } + } + return changed; + } + + /** {@inheritDoc} */ + public boolean removeAll( TFloatCollection collection ) { + if ( collection == this ) { + clear(); + return true; + } + boolean changed = false; + TFloatIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + float element = iter.next(); + if ( remove( element ) ) { + changed = true; + } + } + return changed; + } + + /** {@inheritDoc} */ + public boolean removeAll( float[] array ) { + boolean changed = false; + for ( int i = array.length; i-- > 0; ) { + if ( remove(array[i]) ) { + changed = true; + } + } + return changed; + } + + /** {@inheritDoc} */ + public void clear() { + TFloatObjectHashMap.this.clear(); + } + + /** {@inheritDoc} */ + public boolean forEach( TFloatProcedure procedure ) { + return TFloatObjectHashMap.this.forEachKey( procedure ); + } + + /** {@inheritDoc) */ + public boolean equals( Object other ) { + if (! ( other instanceof TFloatSet ) ) { + return false; + } + final TFloatSet that = ( TFloatSet ) other; + if ( that.size() != this.size() ) { + return false; + } + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + if ( ! that.contains( _set[i] ) ) { + return false; + } + } + } + return true; + } + + /** {@inheritDoc} */ + public int hashCode() { + int hashcode = 0; + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + hashcode += HashFunctions.hash( _set[i] ); + } + } + return hashcode; + } + + /** {@inheritDoc} */ + public String toString() { + final StringBuilder buf = new StringBuilder("{"); + boolean first = true; + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + if ( first ) first = false; + else buf.append( "," ); + buf.append( _set[i] ); + } + } + return buf.toString(); + } + + + class TFloatHashIterator extends THashPrimitiveIterator implements TFloatIterator { + + /** the collection on which the iterator operates */ + private final TFloatHash _hash; + + /** {@inheritDoc} */ + public TFloatHashIterator( TFloatHash hash ) { + super( hash ); + this._hash = hash; + } + + /** {@inheritDoc} */ + public float next() { + moveToNextIndex(); + return _hash._set[_index]; + } + } + } + + + /** a view onto the values of the map. */ + protected class ValueView extends MapBackedView { + + @SuppressWarnings({"unchecked"}) + public Iterator iterator() { + return new TFloatObjectValueHashIterator( TFloatObjectHashMap.this ) { + protected V objectAtIndex( int index ) { + return _values[index]; + } + }; + } + + public boolean containsElement( V value ) { + return containsValue( value ); + } + + public boolean removeElement( V value ) { + V[] values = _values; + byte[] states = _states; + + for ( int i = values.length; i-- > 0; ) { + if ( states[i] == FULL ) { + if ( value == values[i] || + ( null != values[i] && values[i].equals( value ) ) ) { + removeAt( i ); + return true; + } + } + } + return false; + } + + class TFloatObjectValueHashIterator extends THashPrimitiveIterator implements Iterator { + + protected final TFloatObjectHashMap _map; + + public TFloatObjectValueHashIterator( TFloatObjectHashMap map ) { + super( map ); + _map = map; + } + + @SuppressWarnings("unchecked") + protected V objectAtIndex( int index ) { + byte[] states = _states; + Object value = _map._values[index]; + if ( states[index] != FULL ) { + return null; + } + return ( V ) value; + } + + /** {@inheritDoc} */ + @SuppressWarnings("unchecked") + public V next() { + moveToNextIndex(); + return ( V ) _map._values[_index]; + } + } + } + + + private abstract class MapBackedView extends AbstractSet + implements Set, Iterable { + + public abstract Iterator iterator(); + + public abstract boolean removeElement( E key ); + + public abstract boolean containsElement( E key ); + + @SuppressWarnings({"unchecked"}) + public boolean contains( Object key ) { + return containsElement( (E) key ); + } + + @SuppressWarnings({"unchecked"}) + public boolean remove( Object o ) { + return removeElement( (E) o ); + } + + public void clear() { + TFloatObjectHashMap.this.clear(); + } + + public boolean add( E obj ) { + throw new UnsupportedOperationException(); + } + + public int size() { + return TFloatObjectHashMap.this.size(); + } + + public Object[] toArray() { + Object[] result = new Object[size()]; + Iterator e = iterator(); + for ( int i = 0; e.hasNext(); i++ ) { + result[i] = e.next(); + } + return result; + } + + @SuppressWarnings({"unchecked"}) + public T[] toArray( T[] a ) { + int size = size(); + if ( a.length < size ) { + a = (T[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); + } + + Iterator it = iterator(); + Object[] result = a; + for ( int i = 0; i < size; i++ ) { + result[i] = it.next(); + } + + if ( a.length > size ) { + a[size] = null; + } + + return a; + } + + public boolean isEmpty() { + return TFloatObjectHashMap.this.isEmpty(); + } + + public boolean addAll( Collection collection ) { + throw new UnsupportedOperationException(); + } + + @SuppressWarnings({"SuspiciousMethodCalls"}) + public boolean retainAll( Collection collection ) { + boolean changed = false; + Iterator i = iterator(); + while ( i.hasNext() ) { + if ( !collection.contains( i.next() ) ) { + i.remove(); + changed = true; + } + } + return changed; + } + } + + + class TFloatObjectHashIterator extends THashPrimitiveIterator + implements TFloatObjectIterator { + + /** the collection being iterated over */ + private final TFloatObjectHashMap _map; + + /** + * Creates an iterator over the specified map + * + * @param map map to iterate over. + */ + public TFloatObjectHashIterator( TFloatObjectHashMap map ) { + super( map ); + this._map = map; + } + + /** {@inheritDoc} */ + public void advance() { + moveToNextIndex(); + } + + /** {@inheritDoc} */ + public float key() { + return _map._set[_index]; + } + + /** {@inheritDoc} */ + public V value() { + return _map._values[_index]; + } + + /** {@inheritDoc} */ + public V setValue( V val ) { + V old = value(); + _map._values[_index] = val; + return old; + } + } + + + public void writeExternal( ObjectOutput out ) throws IOException { + // VERSION + out.writeByte( 0 ); + + // SUPER + super.writeExternal( out ); + + // NO_ENTRY_KEY + out.writeFloat( no_entry_key ); + + // NUMBER OF ENTRIES + out.writeInt( _size ); + + // ENTRIES + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + out.writeFloat( _set[i] ); + out.writeObject( _values[i] ); + } + } + } + + + @SuppressWarnings({"unchecked"}) + public void readExternal( ObjectInput in ) + throws IOException, ClassNotFoundException { + + // VERSION + in.readByte(); + + // SUPER + super.readExternal( in ); + + // NO_ENTRY_KEY + no_entry_key = in.readFloat(); + + // NUMBER OF ENTRIES + int size = in.readInt(); + setUp( size ); + + // ENTRIES + while (size-- > 0) { + float key = in.readFloat(); + V val = (V) in.readObject(); + put(key, val); + } + } + + + public String toString() { + final StringBuilder buf = new StringBuilder("{"); + forEachEntry(new TFloatObjectProcedure() { + private boolean first = true; + public boolean execute(float key, Object value) { + if ( first ) first = false; + else buf.append( "," ); + + buf.append(key); + buf.append("="); + buf.append(value); + return true; + } + }); + buf.append("}"); + return buf.toString(); + } +} // TFloatObjectHashMap diff --git a/DataExtractionOSM/src/gnu/trove/procedure/TFloatObjectProcedure.java b/DataExtractionOSM/src/gnu/trove/procedure/TFloatObjectProcedure.java new file mode 100644 index 0000000000..379fd47ad8 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/procedure/TFloatObjectProcedure.java @@ -0,0 +1,42 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.procedure; + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for procedures that take two parameters of type float and Object. + */ +public interface TFloatObjectProcedure { + + /** + * Executes this procedure. A false return value indicates that + * the application executing this procedure should not invoke this + * procedure again. + * + * @param a a float value + * @param b an Object value + * @return true if additional invocations of the procedure are + * allowed. + */ + public boolean execute( float a, T b ); +} diff --git a/DataExtractionOSM/src/gnu/trove/procedure/TFloatProcedure.java b/DataExtractionOSM/src/gnu/trove/procedure/TFloatProcedure.java new file mode 100644 index 0000000000..8bcdd8203b --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/procedure/TFloatProcedure.java @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.procedure; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for procedures with one float parameter. + */ +public interface TFloatProcedure { + /** + * Executes this procedure. A false return value indicates that + * the application executing this procedure should not invoke this + * procedure again. + * + * @param value a value of type float + * @return true if additional invocations of the procedure are + * allowed. + */ + public boolean execute( float value ); +} diff --git a/DataExtractionOSM/src/gnu/trove/procedure/TIntProcedure.java b/DataExtractionOSM/src/gnu/trove/procedure/TIntProcedure.java new file mode 100644 index 0000000000..5b1a6447b0 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/procedure/TIntProcedure.java @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.procedure; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for procedures with one int parameter. + */ +public interface TIntProcedure { + /** + * Executes this procedure. A false return value indicates that + * the application executing this procedure should not invoke this + * procedure again. + * + * @param value a value of type int + * @return true if additional invocations of the procedure are + * allowed. + */ + public boolean execute( int value ); +} diff --git a/DataExtractionOSM/src/gnu/trove/procedure/TLongProcedure.java b/DataExtractionOSM/src/gnu/trove/procedure/TLongProcedure.java new file mode 100644 index 0000000000..6b169f01d7 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/procedure/TLongProcedure.java @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.procedure; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * Interface for procedures with one long parameter. + */ +public interface TLongProcedure { + /** + * Executes this procedure. A false return value indicates that + * the application executing this procedure should not invoke this + * procedure again. + * + * @param value a value of type long + * @return true if additional invocations of the procedure are + * allowed. + */ + public boolean execute( long value ); +} diff --git a/DataExtractionOSM/src/gnu/trove/procedure/TObjectProcedure.java b/DataExtractionOSM/src/gnu/trove/procedure/TObjectProcedure.java new file mode 100644 index 0000000000..fe9c9c33e7 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/procedure/TObjectProcedure.java @@ -0,0 +1,42 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + + +package gnu.trove.procedure; + +/** + * Interface for procedures with one Object parameter. + * + * Created: Mon Nov 5 21:45:49 2001 + * + * @author Eric D. Friedman + * @version $Id: TObjectProcedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $ + */ + +public interface TObjectProcedure { + /** + * Executes this procedure. A false return value indicates that + * the application executing this procedure should not invoke this + * procedure again. + * + * @param object an Object value + * @return true if additional invocations of the procedure are + * allowed. + */ + public boolean execute(T object); +}// TObjectProcedure diff --git a/DataExtractionOSM/src/gnu/trove/set/TFloatSet.java b/DataExtractionOSM/src/gnu/trove/set/TFloatSet.java new file mode 100644 index 0000000000..a11655b624 --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/set/TFloatSet.java @@ -0,0 +1,320 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.set; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + +import gnu.trove.iterator.TFloatIterator; +import gnu.trove.procedure.TFloatProcedure; +import gnu.trove.TFloatCollection; + +import java.util.Collection; +import java.util.Set; +import java.io.Serializable; + +/** + * An implementation of the Set interface that uses an + * open-addressed hash table to store its contents. + * + * Created: Sat Nov 3 10:38:17 2001 + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $ + */ + +public interface TFloatSet extends TFloatCollection, Serializable { + + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + float getNoEntryValue(); + + + /** + * Returns the number of elements in this set (its cardinality). If this + * set contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this set (its cardinality) + */ + int size(); + + + /** + * Returns true if this set contains no elements. + * + * @return true if this set contains no elements + */ + boolean isEmpty(); + + + /** + * Returns true if this set contains the specified element. + * + * @param entry an float value + * @return true if the set contains the specified element. + */ + boolean contains( float entry ); + + + /** + * Creates an iterator over the values of the set. The iterator + * supports element deletion. + * + * @return an TFloatIterator value + */ + TFloatIterator iterator(); + + + /** + * Returns an array containing all of the elements in this set. + * If this set makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the + * elements in the same order. + * + *

The returned array will be "safe" in that no references to it + * are maintained by this set. (In other words, this method must + * allocate a new array even if this set is backed by an array). + * The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this set + */ + float[] toArray(); + + + /** + * Returns an array containing elements in this set. + * + *

If this set fits in the specified array with room to spare + * (i.e., the array has more elements than this set), the element in + * the array immediately following the end of the set is set to + * {@link #getNoEntryValue()}. (This is useful in determining + * the length of this set only if the caller knows that this + * set does not contain any elements representing null.) + * + *

If the native array is smaller than the set size, + * the array will be filled with elements in Iterator order + * until it is full and exclude the remainder. + * + *

If this set makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the elements + * in the same order. + * + * @param dest the array into which the elements of this set are to be + * stored. + * @return an float[] containing all the elements in this set + * @throws NullPointerException if the specified array is null + */ + float[] toArray( float[] dest ); + + + /** + * Inserts a value into the set. + * + * @param entry a float value + * @return true if the set was modified by the add operation + */ + boolean add( float entry ); + + + /** + * Removes entry from the set. + * + * @param entry an float value + * @return true if the set was modified by the remove operation. + */ + boolean remove( float entry ); + + + /** + * Tests the set to determine if all of the elements in + * collection are present. + * + * @param collection a Collection value + * @return true if all elements were present in the set. + */ + boolean containsAll( Collection collection ); + + + /** + * Tests the set to determine if all of the elements in + * TFloatCollection are present. + * + * @param collection a TFloatCollection value + * @return true if all elements were present in the set. + */ + boolean containsAll( TFloatCollection collection ); + + + /** + * Tests the set to determine if all of the elements in + * array are present. + * + * @param array as array of float primitives. + * @return true if all elements were present in the set. + */ + boolean containsAll( float[] array ); + + + /** + * Adds all of the elements in collection to the set. + * + * @param collection a Collection value + * @return true if the set was modified by the add all operation. + */ + boolean addAll( Collection collection ); + + + /** + * Adds all of the elements in the TFloatCollection to the set. + * + * @param collection a TFloatCollection value + * @return true if the set was modified by the add all operation. + */ + boolean addAll( TFloatCollection collection ); + + + /** + * Adds all of the elements in the array to the set. + * + * @param array a array of float primitives. + * @return true if the set was modified by the add all operation. + */ + boolean addAll( float[] array ); + + + /** + * Removes any values in the set which are not contained in + * collection. + * + * @param collection a Collection value + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( Collection collection ); + + + /** + * Removes any values in the set which are not contained in + * TFloatCollection. + * + * @param collection a TFloatCollection value + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( TFloatCollection collection ); + + + /** + * Removes any values in the set which are not contained in + * array. + * + * @param array an array of float primitives. + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( float[] array ); + + + /** + * Removes all of the elements in collection from the set. + * + * @param collection a Collection value + * @return true if the set was modified by the remove all operation. + */ + boolean removeAll( Collection collection ); + + + /** + * Removes all of the elements in TFloatCollection from the set. + * + * @param collection a TFloatCollection value + * @return true if the set was modified by the remove all operation. + */ + boolean removeAll( TFloatCollection collection ); + + + /** + * Removes all of the elements in array from the set. + * + * @param array an array of float primitives. + * @return true if the set was modified by the remove all operation. + */ + public boolean removeAll( float[] array ); + + + /** + * Empties the set. + */ + void clear(); + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TFloatProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + boolean forEach( TFloatProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this set for equality. Returns + * true if the specified object is also a set, the two sets + * have the same size, and every member of the specified set is + * contained in this set (or equivalently, every member of this set is + * contained in the specified set). This definition ensures that the + * equals method works properly across different implementations of the + * set interface. + * + * @param o object to be compared for equality with this set + * @return true if the specified object is equal to this set + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this set. The hash code of a set is + * defined to be the sum of the hash codes of the elements in the set. + * This ensures that s1.equals(s2) implies that + * s1.hashCode()==s2.hashCode() for any two sets s1 + * and s2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this set + * @see Object#equals(Object) + * @see Set#equals(Object) + */ + int hashCode(); + + +} // THashSet diff --git a/DataExtractionOSM/src/gnu/trove/set/TIntSet.java b/DataExtractionOSM/src/gnu/trove/set/TIntSet.java new file mode 100644 index 0000000000..64645d090a --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/set/TIntSet.java @@ -0,0 +1,320 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.set; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + +import gnu.trove.iterator.TIntIterator; +import gnu.trove.procedure.TIntProcedure; +import gnu.trove.TIntCollection; + +import java.util.Collection; +import java.util.Set; +import java.io.Serializable; + +/** + * An implementation of the Set interface that uses an + * open-addressed hash table to store its contents. + * + * Created: Sat Nov 3 10:38:17 2001 + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $ + */ + +public interface TIntSet extends TIntCollection, Serializable { + + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + int getNoEntryValue(); + + + /** + * Returns the number of elements in this set (its cardinality). If this + * set contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this set (its cardinality) + */ + int size(); + + + /** + * Returns true if this set contains no elements. + * + * @return true if this set contains no elements + */ + boolean isEmpty(); + + + /** + * Returns true if this set contains the specified element. + * + * @param entry an int value + * @return true if the set contains the specified element. + */ + boolean contains( int entry ); + + + /** + * Creates an iterator over the values of the set. The iterator + * supports element deletion. + * + * @return an TIntIterator value + */ + TIntIterator iterator(); + + + /** + * Returns an array containing all of the elements in this set. + * If this set makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the + * elements in the same order. + * + *

The returned array will be "safe" in that no references to it + * are maintained by this set. (In other words, this method must + * allocate a new array even if this set is backed by an array). + * The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this set + */ + int[] toArray(); + + + /** + * Returns an array containing elements in this set. + * + *

If this set fits in the specified array with room to spare + * (i.e., the array has more elements than this set), the element in + * the array immediately following the end of the set is set to + * {@link #getNoEntryValue()}. (This is useful in determining + * the length of this set only if the caller knows that this + * set does not contain any elements representing null.) + * + *

If the native array is smaller than the set size, + * the array will be filled with elements in Iterator order + * until it is full and exclude the remainder. + * + *

If this set makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the elements + * in the same order. + * + * @param dest the array into which the elements of this set are to be + * stored. + * @return an int[] containing all the elements in this set + * @throws NullPointerException if the specified array is null + */ + int[] toArray( int[] dest ); + + + /** + * Inserts a value into the set. + * + * @param entry a int value + * @return true if the set was modified by the add operation + */ + boolean add( int entry ); + + + /** + * Removes entry from the set. + * + * @param entry an int value + * @return true if the set was modified by the remove operation. + */ + boolean remove( int entry ); + + + /** + * Tests the set to determine if all of the elements in + * collection are present. + * + * @param collection a Collection value + * @return true if all elements were present in the set. + */ + boolean containsAll( Collection collection ); + + + /** + * Tests the set to determine if all of the elements in + * TIntCollection are present. + * + * @param collection a TIntCollection value + * @return true if all elements were present in the set. + */ + boolean containsAll( TIntCollection collection ); + + + /** + * Tests the set to determine if all of the elements in + * array are present. + * + * @param array as array of int primitives. + * @return true if all elements were present in the set. + */ + boolean containsAll( int[] array ); + + + /** + * Adds all of the elements in collection to the set. + * + * @param collection a Collection value + * @return true if the set was modified by the add all operation. + */ + boolean addAll( Collection collection ); + + + /** + * Adds all of the elements in the TIntCollection to the set. + * + * @param collection a TIntCollection value + * @return true if the set was modified by the add all operation. + */ + boolean addAll( TIntCollection collection ); + + + /** + * Adds all of the elements in the array to the set. + * + * @param array a array of int primitives. + * @return true if the set was modified by the add all operation. + */ + boolean addAll( int[] array ); + + + /** + * Removes any values in the set which are not contained in + * collection. + * + * @param collection a Collection value + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( Collection collection ); + + + /** + * Removes any values in the set which are not contained in + * TIntCollection. + * + * @param collection a TIntCollection value + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( TIntCollection collection ); + + + /** + * Removes any values in the set which are not contained in + * array. + * + * @param array an array of int primitives. + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( int[] array ); + + + /** + * Removes all of the elements in collection from the set. + * + * @param collection a Collection value + * @return true if the set was modified by the remove all operation. + */ + boolean removeAll( Collection collection ); + + + /** + * Removes all of the elements in TIntCollection from the set. + * + * @param collection a TIntCollection value + * @return true if the set was modified by the remove all operation. + */ + boolean removeAll( TIntCollection collection ); + + + /** + * Removes all of the elements in array from the set. + * + * @param array an array of int primitives. + * @return true if the set was modified by the remove all operation. + */ + public boolean removeAll( int[] array ); + + + /** + * Empties the set. + */ + void clear(); + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TIntProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + boolean forEach( TIntProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this set for equality. Returns + * true if the specified object is also a set, the two sets + * have the same size, and every member of the specified set is + * contained in this set (or equivalently, every member of this set is + * contained in the specified set). This definition ensures that the + * equals method works properly across different implementations of the + * set interface. + * + * @param o object to be compared for equality with this set + * @return true if the specified object is equal to this set + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this set. The hash code of a set is + * defined to be the sum of the hash codes of the elements in the set. + * This ensures that s1.equals(s2) implies that + * s1.hashCode()==s2.hashCode() for any two sets s1 + * and s2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this set + * @see Object#equals(Object) + * @see Set#equals(Object) + */ + int hashCode(); + + +} // THashSet diff --git a/DataExtractionOSM/src/gnu/trove/set/TLongSet.java b/DataExtractionOSM/src/gnu/trove/set/TLongSet.java new file mode 100644 index 0000000000..fa62253fed --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/set/TLongSet.java @@ -0,0 +1,320 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.set; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + +import gnu.trove.iterator.TLongIterator; +import gnu.trove.procedure.TLongProcedure; +import gnu.trove.TLongCollection; + +import java.util.Collection; +import java.util.Set; +import java.io.Serializable; + +/** + * An implementation of the Set interface that uses an + * open-addressed hash table to store its contents. + * + * Created: Sat Nov 3 10:38:17 2001 + * + * @author Eric D. Friedman, Rob Eden, Jeff Randall + * @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $ + */ + +public interface TLongSet extends TLongCollection, Serializable { + + + /** + * Returns the value that is used to represent null. The default + * value is generally zero, but can be changed during construction + * of the collection. + * + * @return the value that represents null + */ + long getNoEntryValue(); + + + /** + * Returns the number of elements in this set (its cardinality). If this + * set contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this set (its cardinality) + */ + int size(); + + + /** + * Returns true if this set contains no elements. + * + * @return true if this set contains no elements + */ + boolean isEmpty(); + + + /** + * Returns true if this set contains the specified element. + * + * @param entry an long value + * @return true if the set contains the specified element. + */ + boolean contains( long entry ); + + + /** + * Creates an iterator over the values of the set. The iterator + * supports element deletion. + * + * @return an TLongIterator value + */ + TLongIterator iterator(); + + + /** + * Returns an array containing all of the elements in this set. + * If this set makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the + * elements in the same order. + * + *

The returned array will be "safe" in that no references to it + * are maintained by this set. (In other words, this method must + * allocate a new array even if this set is backed by an array). + * The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this set + */ + long[] toArray(); + + + /** + * Returns an array containing elements in this set. + * + *

If this set fits in the specified array with room to spare + * (i.e., the array has more elements than this set), the element in + * the array immediately following the end of the set is set to + * {@link #getNoEntryValue()}. (This is useful in determining + * the length of this set only if the caller knows that this + * set does not contain any elements representing null.) + * + *

If the native array is smaller than the set size, + * the array will be filled with elements in Iterator order + * until it is full and exclude the remainder. + * + *

If this set makes any guarantees as to what order its elements + * are returned by its iterator, this method must return the elements + * in the same order. + * + * @param dest the array into which the elements of this set are to be + * stored. + * @return an long[] containing all the elements in this set + * @throws NullPointerException if the specified array is null + */ + long[] toArray( long[] dest ); + + + /** + * Inserts a value into the set. + * + * @param entry a long value + * @return true if the set was modified by the add operation + */ + boolean add( long entry ); + + + /** + * Removes entry from the set. + * + * @param entry an long value + * @return true if the set was modified by the remove operation. + */ + boolean remove( long entry ); + + + /** + * Tests the set to determine if all of the elements in + * collection are present. + * + * @param collection a Collection value + * @return true if all elements were present in the set. + */ + boolean containsAll( Collection collection ); + + + /** + * Tests the set to determine if all of the elements in + * TLongCollection are present. + * + * @param collection a TLongCollection value + * @return true if all elements were present in the set. + */ + boolean containsAll( TLongCollection collection ); + + + /** + * Tests the set to determine if all of the elements in + * array are present. + * + * @param array as array of long primitives. + * @return true if all elements were present in the set. + */ + boolean containsAll( long[] array ); + + + /** + * Adds all of the elements in collection to the set. + * + * @param collection a Collection value + * @return true if the set was modified by the add all operation. + */ + boolean addAll( Collection collection ); + + + /** + * Adds all of the elements in the TLongCollection to the set. + * + * @param collection a TLongCollection value + * @return true if the set was modified by the add all operation. + */ + boolean addAll( TLongCollection collection ); + + + /** + * Adds all of the elements in the array to the set. + * + * @param array a array of long primitives. + * @return true if the set was modified by the add all operation. + */ + boolean addAll( long[] array ); + + + /** + * Removes any values in the set which are not contained in + * collection. + * + * @param collection a Collection value + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( Collection collection ); + + + /** + * Removes any values in the set which are not contained in + * TLongCollection. + * + * @param collection a TLongCollection value + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( TLongCollection collection ); + + + /** + * Removes any values in the set which are not contained in + * array. + * + * @param array an array of long primitives. + * @return true if the set was modified by the retain all operation + */ + boolean retainAll( long[] array ); + + + /** + * Removes all of the elements in collection from the set. + * + * @param collection a Collection value + * @return true if the set was modified by the remove all operation. + */ + boolean removeAll( Collection collection ); + + + /** + * Removes all of the elements in TLongCollection from the set. + * + * @param collection a TLongCollection value + * @return true if the set was modified by the remove all operation. + */ + boolean removeAll( TLongCollection collection ); + + + /** + * Removes all of the elements in array from the set. + * + * @param array an array of long primitives. + * @return true if the set was modified by the remove all operation. + */ + public boolean removeAll( long[] array ); + + + /** + * Empties the set. + */ + void clear(); + + + /** + * Executes procedure for each element in the set. + * + * @param procedure a TLongProcedure value + * @return false if the loop over the set terminated because + * the procedure returned false for some value. + */ + boolean forEach( TLongProcedure procedure ); + + + // Comparison and hashing + + /** + * Compares the specified object with this set for equality. Returns + * true if the specified object is also a set, the two sets + * have the same size, and every member of the specified set is + * contained in this set (or equivalently, every member of this set is + * contained in the specified set). This definition ensures that the + * equals method works properly across different implementations of the + * set interface. + * + * @param o object to be compared for equality with this set + * @return true if the specified object is equal to this set + */ + boolean equals( Object o ); + + + /** + * Returns the hash code value for this set. The hash code of a set is + * defined to be the sum of the hash codes of the elements in the set. + * This ensures that s1.equals(s2) implies that + * s1.hashCode()==s2.hashCode() for any two sets s1 + * and s2, as required by the general contract of + * {@link Object#hashCode}. + * + * @return the hash code value for this set + * @see Object#equals(Object) + * @see Set#equals(Object) + */ + int hashCode(); + + +} // THashSet diff --git a/DataExtractionOSM/src/gnu/trove/set/hash/TIntHashSet.java b/DataExtractionOSM/src/gnu/trove/set/hash/TIntHashSet.java new file mode 100644 index 0000000000..4346b6207a --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/set/hash/TIntHashSet.java @@ -0,0 +1,551 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.set.hash; + +import gnu.trove.set.TIntSet; +import gnu.trove.iterator.TIntIterator; +import gnu.trove.impl.*; +import gnu.trove.impl.hash.*; +import gnu.trove.TIntCollection; + +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.io.Externalizable; +import java.util.Arrays; +import java.util.Collection; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * An open addressed set implementation for int primitives. + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + */ + +public class TIntHashSet extends TIntHash implements TIntSet, Externalizable { + static final long serialVersionUID = 1L; + + + /** + * Creates a new TIntHashSet instance with the default + * capacity and load factor. + */ + public TIntHashSet() { + super(); + } + + + /** + * Creates a new TIntHashSet instance with a prime + * capacity equal to or greater than initialCapacity and + * with the default load factor. + * + * @param initialCapacity an int value + */ + public TIntHashSet( int initialCapacity ) { + super( initialCapacity ); + } + + + /** + * Creates a new TIntHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param load_factor used to calculate the threshold over which + * rehashing takes place. + */ + public TIntHashSet( int initialCapacity, float load_factor ) { + super( initialCapacity, load_factor ); + } + + + /** + * Creates a new TIntHashSet instance with a prime + * capacity equal to or greater than initial_capacity and + * with the specified load factor. + * + * @param initial_capacity an int value + * @param load_factor a float value + * @param no_entry_value a int value that represents null. + */ + public TIntHashSet( int initial_capacity, float load_factor, + int no_entry_value ) { + super( initial_capacity, load_factor, no_entry_value ); + //noinspection RedundantCast + if ( no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TIntHashSet instance that is a copy + * of the existing Collection. + * + * @param collection a Collection that will be duplicated. + */ + public TIntHashSet( Collection collection ) { + this( Math.max( collection.size(), DEFAULT_CAPACITY ) ); + addAll( collection ); + } + + + /** + * Creates a new TIntHashSet instance that is a copy + * of the existing set. + * + * @param collection a TIntSet that will be duplicated. + */ + public TIntHashSet( TIntCollection collection ) { + this( Math.max( collection.size(), DEFAULT_CAPACITY ) ); + if ( collection instanceof TIntHashSet ) { + TIntHashSet hashset = ( TIntHashSet ) collection; + this._loadFactor = hashset._loadFactor; + this.no_entry_value = hashset.no_entry_value; + //noinspection RedundantCast + if ( this.no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, this.no_entry_value ); + } + setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); + } + addAll( collection ); + } + + + /** + * Creates a new TIntHashSet instance containing the + * elements of array. + * + * @param array an array of int primitives + */ + public TIntHashSet( int[] array ) { + this( Math.max( array.length, DEFAULT_CAPACITY ) ); + addAll( array ); + } + + + /** {@inheritDoc} */ + public TIntIterator iterator() { + return new TIntHashIterator( this ); + } + + + /** {@inheritDoc} */ + public int[] toArray() { + int[] result = new int[ size() ]; + int[] set = _set; + byte[] states = _states; + + for ( int i = states.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + result[j++] = set[i]; + } + } + return result; + } + + + /** {@inheritDoc} */ + public int[] toArray( int[] dest ) { + int[] set = _set; + byte[] states = _states; + + for ( int i = states.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + dest[j++] = set[i]; + } + } + + if ( dest.length > _size ) { + dest[_size] = no_entry_value; + } + return dest; + } + + + /** {@inheritDoc} */ + public boolean add( int val ) { + int index = insertionIndex(val); + + if ( index < 0 ) { + return false; // already present in set, nothing to add + } + + byte previousState = _states[index]; + _set[index] = val; + _states[index] = FULL; + postInsertHook( previousState == FREE ); + + return true; // yes, we added something + } + + + /** {@inheritDoc} */ + public boolean remove( int val ) { + int index = index(val); + if ( index >= 0 ) { + removeAt( index ); + return true; + } + return false; + } + + + /** {@inheritDoc} */ + public boolean containsAll( Collection collection ) { + for ( Object element : collection ) { + if ( element instanceof Integer ) { + int c = ( ( Integer ) element ).intValue(); + if ( ! contains( c ) ) { + return false; + } + } else { + return false; + } + + } + return true; + } + + + /** {@inheritDoc} */ + public boolean containsAll( TIntCollection collection ) { + TIntIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + int element = iter.next(); + if ( ! contains( element ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean containsAll( int[] array ) { + for ( int i = array.length; i-- > 0; ) { + if ( ! contains( array[i] ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean addAll( Collection collection ) { + boolean changed = false; + for ( Integer element : collection ) { + int e = element.intValue(); + if ( add( e ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean addAll( TIntCollection collection ) { + boolean changed = false; + TIntIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + int element = iter.next(); + if ( add( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean addAll( int[] array ) { + boolean changed = false; + for ( int i = array.length; i-- > 0; ) { + if ( add( array[i] ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"SuspiciousMethodCalls"}) + public boolean retainAll( Collection collection ) { + boolean modified = false; + TIntIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + + /** {@inheritDoc} */ + public boolean retainAll( TIntCollection collection ) { + if ( this == collection ) { + return false; + } + boolean modified = false; + TIntIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( iter.next() ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + + /** {@inheritDoc} */ + public boolean retainAll( int[] array ) { + boolean changed = false; + Arrays.sort( array ); + int[] set = _set; + byte[] states = _states; + + for ( int i = set.length; i-- > 0; ) { + if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { + removeAt( i ); + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( Collection collection ) { + boolean changed = false; + for ( Object element : collection ) { + if ( element instanceof Integer ) { + int c = ( ( Integer ) element ).intValue(); + if ( remove( c ) ) { + changed = true; + } + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( TIntCollection collection ) { + boolean changed = false; + TIntIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + int element = iter.next(); + if ( remove( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( int[] array ) { + boolean changed = false; + for ( int i = array.length; i-- > 0; ) { + if ( remove(array[i]) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public void clear() { + super.clear(); + int[] set = _set; + byte[] states = _states; + + for ( int i = set.length; i-- > 0; ) { + set[i] = no_entry_value; + states[i] = FREE; + } + } + + + /** {@inheritDoc} */ + protected void rehash( int newCapacity ) { + int oldCapacity = _set.length; + + int oldSet[] = _set; + byte oldStates[] = _states; + + _set = new int[newCapacity]; + _states = new byte[newCapacity]; + + for ( int i = oldCapacity; i-- > 0; ) { + if( oldStates[i] == FULL ) { + int o = oldSet[i]; + int index = insertionIndex(o); + _set[index] = o; + _states[index] = FULL; + } + } + } + + + /** {@inheritDoc} */ + public boolean equals( Object other ) { + if ( ! ( other instanceof TIntSet ) ) { + return false; + } + TIntSet that = ( TIntSet ) other; + if ( that.size() != this.size() ) { + return false; + } + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + if ( ! that.contains( _set[i] ) ) { + return false; + } + } + } + return true; + } + + + /** {@inheritDoc} */ + public int hashCode() { + int hashcode = 0; + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + hashcode += HashFunctions.hash( _set[i] ); + } + } + return hashcode; + } + + + /** {@inheritDoc} */ + public String toString() { + StringBuilder buffy = new StringBuilder( _size * 2 + 2 ); + buffy.append("{"); + for ( int i = _states.length, j = 1; i-- > 0; ) { + if ( _states[i] == FULL ) { + buffy.append( _set[i] ); + if ( j++ < _size ) { + buffy.append( "," ); + } + } + } + buffy.append("}"); + return buffy.toString(); + } + + + class TIntHashIterator extends THashPrimitiveIterator implements TIntIterator { + + /** the collection on which the iterator operates */ + private final TIntHash _hash; + + /** {@inheritDoc} */ + public TIntHashIterator( TIntHash hash ) { + super( hash ); + this._hash = hash; + } + + /** {@inheritDoc} */ + public int next() { + moveToNextIndex(); + return _hash._set[_index]; + } + } + + + /** {@inheritDoc} */ + public void writeExternal( ObjectOutput out ) throws IOException { + + // VERSION + out.writeByte( 1 ); + + // SUPER + super.writeExternal( out ); + + // NUMBER OF ENTRIES + out.writeInt( _size ); + + // LOAD FACTOR -- Added version 1 + out.writeFloat( _loadFactor ); + + // NO ENTRY VALUE -- Added version 1 + out.writeInt( no_entry_value ); + + // ENTRIES + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + out.writeInt( _set[i] ); + } + } + } + + + /** {@inheritDoc} */ + public void readExternal( ObjectInput in ) + throws IOException, ClassNotFoundException { + + // VERSION + int version = in.readByte(); + + // SUPER + super.readExternal( in ); + + // NUMBER OF ENTRIES + int size = in.readInt(); + + if ( version >= 1 ) { + // LOAD FACTOR + _loadFactor = in.readFloat(); + + // NO ENTRY VALUE + no_entry_value = in.readInt(); + //noinspection RedundantCast + if ( no_entry_value != ( int ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + // ENTRIES + setUp( size ); + while ( size-- > 0 ) { + int val = in.readInt(); + add( val ); + } + } +} // TIntHashSet diff --git a/DataExtractionOSM/src/gnu/trove/set/hash/TLongHashSet.java b/DataExtractionOSM/src/gnu/trove/set/hash/TLongHashSet.java new file mode 100644 index 0000000000..ea5d953e5d --- /dev/null +++ b/DataExtractionOSM/src/gnu/trove/set/hash/TLongHashSet.java @@ -0,0 +1,551 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright (c) 2001, Eric D. Friedman All Rights Reserved. +// Copyright (c) 2009, Rob Eden All Rights Reserved. +// Copyright (c) 2009, Jeff Randall All Rights Reserved. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +/////////////////////////////////////////////////////////////////////////////// + +package gnu.trove.set.hash; + +import gnu.trove.set.TLongSet; +import gnu.trove.iterator.TLongIterator; +import gnu.trove.impl.*; +import gnu.trove.impl.hash.*; +import gnu.trove.TLongCollection; + +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.io.Externalizable; +import java.util.Arrays; +import java.util.Collection; + + +////////////////////////////////////////////////// +// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // +////////////////////////////////////////////////// + + +/** + * An open addressed set implementation for long primitives. + * + * @author Eric D. Friedman + * @author Rob Eden + * @author Jeff Randall + */ + +public class TLongHashSet extends TLongHash implements TLongSet, Externalizable { + static final long serialVersionUID = 1L; + + + /** + * Creates a new TLongHashSet instance with the default + * capacity and load factor. + */ + public TLongHashSet() { + super(); + } + + + /** + * Creates a new TLongHashSet instance with a prime + * capacity equal to or greater than initialCapacity and + * with the default load factor. + * + * @param initialCapacity an int value + */ + public TLongHashSet( int initialCapacity ) { + super( initialCapacity ); + } + + + /** + * Creates a new TIntHash instance with a prime + * value at or near the specified capacity and load factor. + * + * @param initialCapacity used to find a prime capacity for the table. + * @param load_factor used to calculate the threshold over which + * rehashing takes place. + */ + public TLongHashSet( int initialCapacity, float load_factor ) { + super( initialCapacity, load_factor ); + } + + + /** + * Creates a new TLongHashSet instance with a prime + * capacity equal to or greater than initial_capacity and + * with the specified load factor. + * + * @param initial_capacity an int value + * @param load_factor a float value + * @param no_entry_value a long value that represents null. + */ + public TLongHashSet( int initial_capacity, float load_factor, + long no_entry_value ) { + super( initial_capacity, load_factor, no_entry_value ); + //noinspection RedundantCast + if ( no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + + /** + * Creates a new TLongHashSet instance that is a copy + * of the existing Collection. + * + * @param collection a Collection that will be duplicated. + */ + public TLongHashSet( Collection collection ) { + this( Math.max( collection.size(), DEFAULT_CAPACITY ) ); + addAll( collection ); + } + + + /** + * Creates a new TLongHashSet instance that is a copy + * of the existing set. + * + * @param collection a TLongSet that will be duplicated. + */ + public TLongHashSet( TLongCollection collection ) { + this( Math.max( collection.size(), DEFAULT_CAPACITY ) ); + if ( collection instanceof TLongHashSet ) { + TLongHashSet hashset = ( TLongHashSet ) collection; + this._loadFactor = hashset._loadFactor; + this.no_entry_value = hashset.no_entry_value; + //noinspection RedundantCast + if ( this.no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, this.no_entry_value ); + } + setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); + } + addAll( collection ); + } + + + /** + * Creates a new TLongHashSet instance containing the + * elements of array. + * + * @param array an array of long primitives + */ + public TLongHashSet( long[] array ) { + this( Math.max( array.length, DEFAULT_CAPACITY ) ); + addAll( array ); + } + + + /** {@inheritDoc} */ + public TLongIterator iterator() { + return new TLongHashIterator( this ); + } + + + /** {@inheritDoc} */ + public long[] toArray() { + long[] result = new long[ size() ]; + long[] set = _set; + byte[] states = _states; + + for ( int i = states.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + result[j++] = set[i]; + } + } + return result; + } + + + /** {@inheritDoc} */ + public long[] toArray( long[] dest ) { + long[] set = _set; + byte[] states = _states; + + for ( int i = states.length, j = 0; i-- > 0; ) { + if ( states[i] == FULL ) { + dest[j++] = set[i]; + } + } + + if ( dest.length > _size ) { + dest[_size] = no_entry_value; + } + return dest; + } + + + /** {@inheritDoc} */ + public boolean add( long val ) { + int index = insertionIndex(val); + + if ( index < 0 ) { + return false; // already present in set, nothing to add + } + + byte previousState = _states[index]; + _set[index] = val; + _states[index] = FULL; + postInsertHook( previousState == FREE ); + + return true; // yes, we added something + } + + + /** {@inheritDoc} */ + public boolean remove( long val ) { + int index = index(val); + if ( index >= 0 ) { + removeAt( index ); + return true; + } + return false; + } + + + /** {@inheritDoc} */ + public boolean containsAll( Collection collection ) { + for ( Object element : collection ) { + if ( element instanceof Long ) { + long c = ( ( Long ) element ).longValue(); + if ( ! contains( c ) ) { + return false; + } + } else { + return false; + } + + } + return true; + } + + + /** {@inheritDoc} */ + public boolean containsAll( TLongCollection collection ) { + TLongIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + long element = iter.next(); + if ( ! contains( element ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean containsAll( long[] array ) { + for ( int i = array.length; i-- > 0; ) { + if ( ! contains( array[i] ) ) { + return false; + } + } + return true; + } + + + /** {@inheritDoc} */ + public boolean addAll( Collection collection ) { + boolean changed = false; + for ( Long element : collection ) { + long e = element.longValue(); + if ( add( e ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean addAll( TLongCollection collection ) { + boolean changed = false; + TLongIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + long element = iter.next(); + if ( add( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean addAll( long[] array ) { + boolean changed = false; + for ( int i = array.length; i-- > 0; ) { + if ( add( array[i] ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + @SuppressWarnings({"SuspiciousMethodCalls"}) + public boolean retainAll( Collection collection ) { + boolean modified = false; + TLongIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + + /** {@inheritDoc} */ + public boolean retainAll( TLongCollection collection ) { + if ( this == collection ) { + return false; + } + boolean modified = false; + TLongIterator iter = iterator(); + while ( iter.hasNext() ) { + if ( ! collection.contains( iter.next() ) ) { + iter.remove(); + modified = true; + } + } + return modified; + } + + + /** {@inheritDoc} */ + public boolean retainAll( long[] array ) { + boolean changed = false; + Arrays.sort( array ); + long[] set = _set; + byte[] states = _states; + + for ( int i = set.length; i-- > 0; ) { + if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { + removeAt( i ); + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( Collection collection ) { + boolean changed = false; + for ( Object element : collection ) { + if ( element instanceof Long ) { + long c = ( ( Long ) element ).longValue(); + if ( remove( c ) ) { + changed = true; + } + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( TLongCollection collection ) { + boolean changed = false; + TLongIterator iter = collection.iterator(); + while ( iter.hasNext() ) { + long element = iter.next(); + if ( remove( element ) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public boolean removeAll( long[] array ) { + boolean changed = false; + for ( int i = array.length; i-- > 0; ) { + if ( remove(array[i]) ) { + changed = true; + } + } + return changed; + } + + + /** {@inheritDoc} */ + public void clear() { + super.clear(); + long[] set = _set; + byte[] states = _states; + + for ( int i = set.length; i-- > 0; ) { + set[i] = no_entry_value; + states[i] = FREE; + } + } + + + /** {@inheritDoc} */ + protected void rehash( int newCapacity ) { + int oldCapacity = _set.length; + + long oldSet[] = _set; + byte oldStates[] = _states; + + _set = new long[newCapacity]; + _states = new byte[newCapacity]; + + for ( int i = oldCapacity; i-- > 0; ) { + if( oldStates[i] == FULL ) { + long o = oldSet[i]; + int index = insertionIndex(o); + _set[index] = o; + _states[index] = FULL; + } + } + } + + + /** {@inheritDoc} */ + public boolean equals( Object other ) { + if ( ! ( other instanceof TLongSet ) ) { + return false; + } + TLongSet that = ( TLongSet ) other; + if ( that.size() != this.size() ) { + return false; + } + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + if ( ! that.contains( _set[i] ) ) { + return false; + } + } + } + return true; + } + + + /** {@inheritDoc} */ + public int hashCode() { + int hashcode = 0; + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + hashcode += HashFunctions.hash( _set[i] ); + } + } + return hashcode; + } + + + /** {@inheritDoc} */ + public String toString() { + StringBuilder buffy = new StringBuilder( _size * 2 + 2 ); + buffy.append("{"); + for ( int i = _states.length, j = 1; i-- > 0; ) { + if ( _states[i] == FULL ) { + buffy.append( _set[i] ); + if ( j++ < _size ) { + buffy.append( "," ); + } + } + } + buffy.append("}"); + return buffy.toString(); + } + + + class TLongHashIterator extends THashPrimitiveIterator implements TLongIterator { + + /** the collection on which the iterator operates */ + private final TLongHash _hash; + + /** {@inheritDoc} */ + public TLongHashIterator( TLongHash hash ) { + super( hash ); + this._hash = hash; + } + + /** {@inheritDoc} */ + public long next() { + moveToNextIndex(); + return _hash._set[_index]; + } + } + + + /** {@inheritDoc} */ + public void writeExternal( ObjectOutput out ) throws IOException { + + // VERSION + out.writeByte( 1 ); + + // SUPER + super.writeExternal( out ); + + // NUMBER OF ENTRIES + out.writeInt( _size ); + + // LOAD FACTOR -- Added version 1 + out.writeFloat( _loadFactor ); + + // NO ENTRY VALUE -- Added version 1 + out.writeLong( no_entry_value ); + + // ENTRIES + for ( int i = _states.length; i-- > 0; ) { + if ( _states[i] == FULL ) { + out.writeLong( _set[i] ); + } + } + } + + + /** {@inheritDoc} */ + public void readExternal( ObjectInput in ) + throws IOException, ClassNotFoundException { + + // VERSION + int version = in.readByte(); + + // SUPER + super.readExternal( in ); + + // NUMBER OF ENTRIES + int size = in.readInt(); + + if ( version >= 1 ) { + // LOAD FACTOR + _loadFactor = in.readFloat(); + + // NO ENTRY VALUE + no_entry_value = in.readLong(); + //noinspection RedundantCast + if ( no_entry_value != ( long ) 0 ) { + Arrays.fill( _set, no_entry_value ); + } + } + + // ENTRIES + setUp( size ); + while ( size-- > 0 ) { + long val = in.readLong(); + add( val ); + } + } +} // TIntHashSet diff --git a/DataExtractionOSM/src/net/osmand/osm/BinaryMapRenderObject.java b/DataExtractionOSM/src/net/osmand/binary/BinaryMapDataObject.java similarity index 56% rename from DataExtractionOSM/src/net/osmand/osm/BinaryMapRenderObject.java rename to DataExtractionOSM/src/net/osmand/binary/BinaryMapDataObject.java index 136ca084a4..c35c7cb32e 100644 --- a/DataExtractionOSM/src/net/osmand/osm/BinaryMapRenderObject.java +++ b/DataExtractionOSM/src/net/osmand/binary/BinaryMapDataObject.java @@ -1,134 +1,107 @@ -package net.osmand.osm; +package net.osmand.binary; -import net.osmand.Algoritms; +import net.osmand.osm.MapRenderingTypes; -public class BinaryMapRenderObject { - private String name = null; - private int type; - private byte[] data = null; - private long id; - private float order = -1; - private boolean multitype = false; - private boolean highwayType = false; +public class BinaryMapDataObject { + int[] coordinates = null; + int[] types = null; - public BinaryMapRenderObject(long id){ - this.id = id; + int stringId = -1; + long id = 0; + + long[] restrictions = null; + int highwayAttributes = 0; + + String name; + + + public BinaryMapDataObject(){ } - public void setData(byte[] data) { - this.data = data; + protected void setStringId(int stringId) { + this.stringId = stringId; } + + protected void setCoordinates(int[] coordinates) { + this.coordinates = coordinates; + } + + protected int getStringId() { + return stringId; + } + public void setName(String name) { this.name = name; } - public void setType(int type) { - this.type = type; - multitype = (type & 1) > 0; - highwayType = isHighwayType(); - order = -1; - } - - public int getWholeType() { - return type; - } - - public long getId() { - return id; - } - - public boolean isMultitype() { - return multitype; - } - - public byte getMultiTypes(){ - return multitype ? data[0] : 0; - } - - public byte getRestrictions(){ - if(!highwayType){ - return 0; - } - if(multitype){ - return data[1]; - } - return data[0]; - } - - - - public int getAdditionalType(int k){ - return Algoritms.parseSmallIntFromBytes(data, highwayType ? k * 2 + 2 : k * 2 + 1); - } - - // do not cut type to 15 bits (16 bits needed for multipolygon) - public int getMainType(){ - return (type >> 1); - } - - private boolean isHighwayType(){ - int pr = type >> 1; - return (pr & 3) == MapRenderingTypes.POLYLINE_TYPE && MapRenderingTypes.getMainObjectType(pr) == MapRenderingTypes.HIGHWAY; - } - - public int getSecondType(){ - if(isHighwayType()){ - return 0; - } - return type >> 16; - } - - public byte getRestrictionType(int k){ - int offset = multitype ? data[0] * 2 + 2 : 1; - long l = Algoritms.parseLongFromBytes(data, offset); - return (byte) (l & 7); - } - - public long getRestriction(int k){ - int offset = multitype ? data[0] * 2 + 2 : 1; - long l = Algoritms.parseLongFromBytes(data, offset); - return (l & ~7l) | (id & 7l); - } - - - public int getPointsLength() { - if (data == null || data.length == 0) { - return 0; - } - return (data.length - getShiftCoordinates()) / 8; - } - public String getName() { return name; } - private int getShiftCoordinates(){ - int shift = 0; - if(multitype){ - shift = data[0] * 2 + 1; - if(highwayType){ - shift += data[1] * 8 + 1; - } - } else if(highwayType){ - shift = data[0] * 8 + 1; - } - return shift; + public int[] getTypes(){ + return types; } + public long getId() { + return id; + } + + protected void setId(long id) { + this.id = id; + } + + protected void setTypes(int[] types) { + this.types = types; + } + + + public int getHighwayAttributes() { + return highwayAttributes; + } + + protected void setHighwayAttributes(int highwayAttributes) { + this.highwayAttributes = highwayAttributes; + } + + public int getPointsLength(){ + if(coordinates == null){ + return 0; + } + return coordinates.length / 2; + } public int getPoint31YTile(int ind) { - return Algoritms.parseIntFromBytes(data, ind * 8 + getShiftCoordinates()); + return coordinates[2 * ind + 1]; } public int getPoint31XTile(int ind) { - return Algoritms.parseIntFromBytes(data, ind * 8 + 4 + getShiftCoordinates()); + return coordinates[2 * ind]; } - public float getMapOrder(){ - if (order == -1) { - order = getOrder(getMainType()); + public int getRestrictionCount(){ + if(restrictions == null){ + return 0; } - return order; + return restrictions.length; } + + + protected void setRestrictions(long[] restrictions) { + this.restrictions = restrictions; + } + + protected long[] getRestrictions() { + return restrictions; + } + + public byte getRestrictionType(int k){ + return (byte) (restrictions[k] & 7); + } + + public long getRestriction(int k){ + long l = restrictions[k]; + return (l & ~7l) | (id & 7l); + } + public static float getOrder(int wholeType) { float order = 0; @@ -233,6 +206,6 @@ public class BinaryMapRenderObject { return order; } - - + + } diff --git a/DataExtractionOSM/src/net/osmand/binary/BinaryMapIndexReader.java b/DataExtractionOSM/src/net/osmand/binary/BinaryMapIndexReader.java index a9f2eb6778..d56eb274ef 100644 --- a/DataExtractionOSM/src/net/osmand/binary/BinaryMapIndexReader.java +++ b/DataExtractionOSM/src/net/osmand/binary/BinaryMapIndexReader.java @@ -45,22 +45,6 @@ public class BinaryMapIndexReader { } - public class MapDataObject { - - - int[] coordinates = null; - int[] types = null; - - int stringId = -1; - long id = 0; - - long[] restrictions = null; - int highwayAttributes = 0; - - String name; - } - - public BinaryMapIndexReader(final RandomAccessFile raf) throws IOException { this.raf = raf; @@ -183,8 +167,8 @@ public class BinaryMapIndexReader { } } - public List searchMapIndex(MapRoot index, int sleft, int sright, int stop, int sbottom, - List searchResults) throws IOException { + public List searchMapIndex(MapRoot index, int sleft, int sright, int stop, int sbottom, + List searchResults) throws IOException { for(MapTree tree : index.trees){ codedIS.seek(tree.filePointer); int oldLimit = codedIS.pushLimit(tree.length); @@ -197,9 +181,9 @@ public class BinaryMapIndexReader { private void searchMapTreeBounds(MapTree tree, int pleft, int pright, int ptop, int pbottom, int sleft, int sright, int stop, int sbottom, - List searchResults, String indent) throws IOException { + List searchResults, String indent) throws IOException { int init = 0; - List results = null; + List results = null; while(true){ int tag = WireFormat.getTagFieldNumber(codedIS.readTag()); if(init == 0xf){ @@ -231,10 +215,10 @@ public class BinaryMapIndexReader { case OsmandOdb.MapTree.LEAFS_FIELD_NUMBER : int length = codedIS.readRawVarint32(); int oldLimit = codedIS.pushLimit(length); - MapDataObject mapObject = readMapDataObject(tree.left, tree.right, tree.top, tree.bottom, sleft, sright, stop, sbottom); + BinaryMapDataObject mapObject = readMapDataObject(tree.left, tree.right, tree.top, tree.bottom, sleft, sright, stop, sbottom); if(mapObject != null){ if(results == null){ - results = new ArrayList(); + results = new ArrayList(); } results.add(mapObject); searchResults.add(mapObject); @@ -255,7 +239,7 @@ public class BinaryMapIndexReader { case OsmandOdb.MapTree.BASEID_FIELD_NUMBER : tree.baseId = codedIS.readUInt64(); if (results != null) { - for (MapDataObject rs : results) { + for (BinaryMapDataObject rs : results) { rs.id += tree.baseId; if (rs.restrictions != null) { for (int i = 0; i < rs.restrictions.length; i++) { @@ -272,7 +256,7 @@ public class BinaryMapIndexReader { codedIS.popLimit(oldLimit); if (results != null) { - for (MapDataObject rs : results) { + for (BinaryMapDataObject rs : results) { if (rs.stringId != -1) { rs.name = tree.stringTable.get(rs.stringId); } @@ -286,7 +270,7 @@ public class BinaryMapIndexReader { } } List CACHE = new ArrayList(); - private MapDataObject readMapDataObject(int left, int right, int top, int bottom, int sleft, int sright, int stop, int sbottom) throws IOException { + private BinaryMapDataObject readMapDataObject(int left, int right, int top, int bottom, int sleft, int sright, int stop, int sbottom) throws IOException { int tag = WireFormat.getTagFieldNumber(codedIS.readTag()); if(OsmandOdb.MapData.COORDINATES_FIELD_NUMBER != tag) { throw new IllegalArgumentException(); @@ -314,7 +298,7 @@ public class BinaryMapIndexReader { return null; } - MapDataObject dataObject = new MapDataObject(); + BinaryMapDataObject dataObject = new BinaryMapDataObject(); dataObject.coordinates = new int[CACHE.size()]; for(int i=0; i())){ - if(obj.name != null){ - System.out.println(" " + obj.name); + for(BinaryMapDataObject obj : reader.searchMapIndex(b, sleft, sright, stop, sbottom, new ArrayList())){ + if(obj.getName() != null){ + System.out.println(" " + obj.getName()); } } } diff --git a/DataExtractionOSM/src/osmand_odb.proto b/DataExtractionOSM/src/osmand_odb.proto new file mode 100644 index 0000000000..d3d66ed277 --- /dev/null +++ b/DataExtractionOSM/src/osmand_odb.proto @@ -0,0 +1,67 @@ +option java_package = "net.osmand.binary"; +//protoc --java_out=../.. osmand_odb.proto + + +// +// STORAGE LAYER: Storing primitives. +// + +// IMPORTANT : These messages are not intented to be parsed by google engine (because of the size) + // The main difference that size of that messages is not var int and is always fixed int size +message OsmAndStructure { + required uint32 version = 1; + repeated OsmAndMapIndex mapIndex = 2; +} + +message OsmAndMapIndex { + repeated MapRootLevel levels = 1; +} + +message MapRootLevel { + required int32 maxZoom = 1; + required int32 minZoom = 2; + required int32 left = 3; + required int32 right = 4; + required int32 top = 5; + required int32 bottom = 6; + + repeated MapTree root = 7; + +} + +message MapTree { + required sint32 left = 1; // delta encoded + required sint32 right = 2; // delta encoded + required sint32 top = 3; // delta encoded + required sint32 bottom = 4; // delta encoded + + optional StringTable stringTable = 5; + optional uint64 baseId = 6; + + repeated MapTree subtrees = 7; + repeated MapData leafs = 8; + +} + +// These messages could be read directly +/** + String table, contains the common strings in each block. + */ +message StringTable { + repeated string s = 1; +} + + +/// Simple messages +message MapData { + required bytes coordinates = 1; // array of delta x,y sint32 could be read by codedinputstream + // first x delta to Tree.left, y to delta Tree.top (next delta to previous) + required bytes types = 2; // array of fixed int16 + + required sint64 id = 3; // delta encoded + optional uint32 stringId = 4; + + optional bytes restrictions = 5; // array of SInt64 delta encoded (to baseId !) + optional int32 highwayMeta = 6; +} + diff --git a/DataExtractionOSM/src/osmformat.proto b/DataExtractionOSM/src/osmformat.proto new file mode 100644 index 0000000000..48accfa5c7 --- /dev/null +++ b/DataExtractionOSM/src/osmformat.proto @@ -0,0 +1,207 @@ +option java_package = "crosby.binary"; + +/* OSM Binary file format + +This is the master schema file of the OSM binary file format. This +file is designed to support limited random-access and future +extendability. + +A binary OSM file consists of a sequence of FileBlocks (please see +fileformat.proto). The first fileblock contains a serialized instance +of HeaderBlock, followed by a sequence of PrimitiveBlock blocks that +contain the primitives. + +Each primitiveblock is designed to be independently parsable. It +contains a string table storing all strings in that block (keys and +values in tags, roles in relations, usernames, etc.) as well as +metadata containing the precision of coordinates or timestamps in that +block. + +A primitiveblock contains a sequence of primitive groups, each +containing primitives of the same type (nodes, densenodes, ways, +relations). Coordinates are stored in signed 64-bit integers. Lat&lon +are measured in units nanodegrees. The default of +granularity of 100 nanodegrees corresponds to about 1cm on the ground, +and a full lat or lon fits into 32 bits. + +Converting an integer to a lattitude or longitude uses the formula: +$OUT = IN * granularity / 10**9$. Many encoding schemes use delta +coding when representing nodes and relations. + +*/ + +////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////// + +/* Contains the file header. */ + +message HeaderBlock { + optional HeaderBBox bbox = 1; + /* Additional tags to aid in parsing this dataset */ + repeated string required_features = 4; + repeated string optional_features = 5; + + optional string writingprogram = 16; + optional string source = 17; // From the bbox field. +} + + +/** The bounding box field in the OSM header. BBOX, as used in the OSM +header. Units are always in nanodegrees -- they do not obey +granularity rules. */ + +message HeaderBBox { + required sint64 left = 1; + required sint64 right = 2; + required sint64 top = 3; + required sint64 bottom = 4; +} + + +/////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////// + + +message PrimitiveBlock { + required StringTable stringtable = 1; + repeated PrimitiveGroup primitivegroup = 2; + + // Granularity, units of nanodegrees, used to store coordinates in this block + optional int32 granularity = 17 [default=100]; + // Offset value between the output coordinates coordinates and the granularity grid in unites of nanodegrees. + optional int64 lat_offset = 19 [default=0]; + optional int64 lon_offset = 20 [default=0]; + +// Granularity of dates, normally represented in units of milliseconds since the 1970 epoch. + optional int32 date_granularity = 18 [default=1000]; + + + // Proposed extension: + //optional BBox bbox = 19; +} + +// Group of OSMPrimitives. All primitives in a group must be the same type. +message PrimitiveGroup { + repeated Node nodes = 1; + optional DenseNodes dense = 2; + repeated Way ways = 3; + repeated Relation relations = 4; + repeated ChangeSet changesets = 5; +} + + +/** String table, contains the common strings in each block. + + Note that we reserve index '0' as a delimiter, so the entry at that + index in the table is ALWAYS blank and unused. + + */ +message StringTable { + repeated bytes s = 1; +} + +/* Optional metadata that may be included into each primitive. */ +message Info { + optional int32 version = 1 [default = -1]; + optional int64 timestamp = 2; + optional int64 changeset = 3; + optional int32 uid = 4; + optional int32 user_sid = 5; // String IDs +} + +/** Optional metadata that may be included into each primitive. Special dense format used in DenseNodes. */ +message DenseInfo { + repeated int32 version = 1 [packed = true]; + repeated sint64 timestamp = 2 [packed = true]; // DELTA coded + repeated sint64 changeset = 3 [packed = true]; // DELTA coded + repeated sint32 uid = 4 [packed = true]; // DELTA coded + repeated sint32 user_sid = 5 [packed = true]; // String IDs for usernames. DELTA coded +} + + +// THIS IS STUB DESIGN FOR CHANGESETS. NOT USED RIGHT NOW. +// TODO: REMOVE THIS? +message ChangeSet { + required int64 id = 1; +// +// // Parallel arrays. +// repeated uint32 keys = 2 [packed = true]; // String IDs. +// repeated uint32 vals = 3 [packed = true]; // String IDs. +// +// optional Info info = 4; + +// optional int64 created_at = 8; +// optional int64 closetime_delta = 9; +// optional bool open = 10; +// optional HeaderBBox bbox = 11; +} + + +message Node { + required sint64 id = 1; + // Parallel arrays. + repeated uint32 keys = 2 [packed = true]; // String IDs. + repeated uint32 vals = 3 [packed = true]; // String IDs. + + optional Info info = 4; // May be omitted in omitmeta + + required sint64 lat = 8; + required sint64 lon = 9; +} + +/* Used to densly represent a sequence of nodes that do not have any tags. + +We represent these nodes columnwise as five columns: ID's, lats, and +lons, all delta coded. When metadata is not omitted, + +We encode keys & vals for all nodes as a single array of integers +containing key-stringid and val-stringid, using a stringid of 0 as a +delimiter between nodes. + + ( ( )* '0' )* + */ + +message DenseNodes { + repeated sint64 id = 1 [packed = true]; // DELTA coded + + //repeated Info info = 4; + optional DenseInfo denseinfo = 5; + + repeated sint64 lat = 8 [packed = true]; // DELTA coded + repeated sint64 lon = 9 [packed = true]; // DELTA coded + + // Special packing of keys and vals into one array. May be empty if all nodes in this block are tagless. + repeated int32 keys_vals = 10 [packed = true]; +} + + +message Way { + required int64 id = 1; + // Parallel arrays. + repeated uint32 keys = 2 [packed = true]; + repeated uint32 vals = 3 [packed = true]; + + optional Info info = 4; + + repeated sint64 refs = 8 [packed = true]; // DELTA coded +} + +message Relation { + enum MemberType { + NODE = 0; + WAY = 1; + RELATION = 2; + } + required int64 id = 1; + + // Parallel arrays. + repeated uint32 keys = 2 [packed = true]; + repeated uint32 vals = 3 [packed = true]; + + optional Info info = 4; + + // Parallel arrays + repeated int32 roles_sid = 8 [packed = true]; + repeated sint64 memids = 9 [packed = true]; // DELTA encoded + repeated MemberType types = 10 [packed = true]; +}