类com.google.protobuf.CodedOutputStream源码实例Demo

下面列出了怎么用com.google.protobuf.CodedOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: bazel   文件: StringLiteral.java

@Override
public void serialize(SerializationContext context, StringLiteral lit, CodedOutputStream out)
    throws SerializationException, IOException {
  // Enable de-duplication of strings during encoding.
  // The encoder does not intern and de-duplicate Strings by default,
  // though it does for all other objects;
  // see skyframe.serialization.strings.StringCodec.getStrategy.
  // If that were to change, we could delete StringLiteralCodec.
  // (One wonders why Identifier.name strings are not similarly de-duped,
  // as they are as numerous and more repetitive than string literals.)
  context.serializeWithAdHocMemoizationStrategy(
      lit.getValue(), MemoizationStrategy.MEMOIZE_AFTER, out);
  out.writeInt32NoTag(lit.startOffset);
  out.writeInt32NoTag(lit.endOffset);
  context.serialize(lit.locs, out);
}
 
源代码2 项目: bazel   文件: ImmutableMapCodec.java

static <K, V> void serializeEntries(
    SerializationContext context,
    Iterable<? extends Map.Entry<K, V>> entrySet,
    CodedOutputStream codedOut)
    throws IOException, SerializationException {
  for (Map.Entry<?, ?> entry : entrySet) {
    context.serialize(entry.getKey(), codedOut);
    try {
      context.serialize(entry.getValue(), codedOut);
    } catch (SerializationException | IOException e) {
      throw SerializationException.propagate(
          String.format(
              "Exception while serializing value of type %s for key '%s'",
              entry.getValue().getClass().getName(), entry.getKey()),
          e);
    }
  }
}
 
源代码3 项目: zetasketch   文件: State.java

public void writeTo(CodedOutputStream stream) throws IOException {
  // We use the NoTag write methods for consistency with the parsing functions and for
  // consistency with the variable-length writes where we can't use any convenience function.
  stream.writeUInt32NoTag(TYPE_TAG);
  stream.writeEnumNoTag(type.getNumber());

  stream.writeUInt32NoTag(NUM_VALUES_TAG);
  stream.writeInt64NoTag(numValues);

  if (encodingVersion != DEFAULT_ENCODING_VERSION) {
    stream.writeUInt32NoTag(ENCODING_VERSION_TAG);
    stream.writeInt32NoTag(encodingVersion);
  }

  if (!valueType.equals(DEFAULT_VALUE_TYPE)) {
    stream.writeUInt32NoTag(VALUE_TYPE_TAG);
    stream.writeEnumNoTag(valueType.getNumber());
  }

  stream.writeUInt32NoTag(HYPERLOGLOGPLUS_UNIQUE_STATE_TAG);
  stream.writeUInt32NoTag(getSerializedHllSize());
  writeHllTo(stream);
}
 
源代码4 项目: zetasketch   文件: State.java

public int getSerializedSize() {
  int size = 0;

  size += CodedOutputStream.computeUInt32SizeNoTag(TYPE_TAG);
  size += CodedOutputStream.computeEnumSizeNoTag(type.getNumber());

  size += CodedOutputStream.computeUInt32SizeNoTag(NUM_VALUES_TAG);
  size += CodedOutputStream.computeInt64SizeNoTag(numValues);

  if (encodingVersion != DEFAULT_ENCODING_VERSION) {
    size += CodedOutputStream.computeUInt32SizeNoTag(ENCODING_VERSION_TAG);
    size += CodedOutputStream.computeInt32SizeNoTag(encodingVersion);
  }

  if (!valueType.equals(DEFAULT_VALUE_TYPE)) {
    size += CodedOutputStream.computeUInt32SizeNoTag(VALUE_TYPE_TAG);
    size += CodedOutputStream.computeEnumSizeNoTag(valueType.getNumber());
  }

  int hllSize = getSerializedHllSize();
  size += CodedOutputStream.computeUInt32SizeNoTag(HYPERLOGLOGPLUS_UNIQUE_STATE_TAG);
  size += CodedOutputStream.computeUInt32SizeNoTag(hllSize);
  size += hllSize;

  return size;
}
 
源代码5 项目: zetasketch   文件: StateTest.java

@Test
public void parseUnknownField() throws IOException {
  // Create an aggregator state proto with an unknown field in the middle.
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  CodedOutputStream coded = CodedOutputStream.newInstance(stream);
  coded.writeInt32(AggregatorStateProto.NUM_VALUES_FIELD_NUMBER, 42);
  coded.writeString(999, "foobar");
  coded.writeInt32(AggregatorStateProto.ENCODING_VERSION_FIELD_NUMBER, 43);
  coded.flush();

  // Check that we can parse the proto, despite the unknown field.
  State state = new State();
  state.parse(CodedInputStream.newInstance(stream.toByteArray()));

  // Check that the fields before and after the unknown fields were correctly read.
  assertEquals(42, state.numValues);
  assertEquals(43, state.encodingVersion);
}
 
源代码6 项目: bazel   文件: SerializationContext.java

@Nullable
private ObjectCodecRegistry.CodecDescriptor recordAndGetDescriptorIfNotConstantMemoizedOrNull(
    @Nullable Object object, CodedOutputStream codedOut) throws IOException, NoCodecException {
  if (writeNullOrConstant(object, codedOut)) {
    return null;
  }
  if (serializer != null) {
    Integer memoizedIndex = serializer.getMemoizedIndex(object);
    if (memoizedIndex != null) {
      // Subtract 1 so it will be negative and not collide with null.
      codedOut.writeSInt32NoTag(-memoizedIndex - 1);
      return null;
    }
  }
  ObjectCodecRegistry.CodecDescriptor descriptor = registry.getCodecDescriptorForObject(object);
  codedOut.writeSInt32NoTag(descriptor.getTag());
  return descriptor;
}
 

@Test
public void serializeToBinary() {
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
  try {

    codedOutputStream.writeStringNoTag("jc");
    codedOutputStream.writeStringNoTag("dan");
    codedOutputStream.writeInt32NoTag(1);
    codedOutputStream.writeStringNoTag("abc");
    codedOutputStream.writeStringNoTag("");
    codedOutputStream.writeByteArrayNoTag(NumericUtil.hexToBytes("0f0f0f"));
    codedOutputStream.flush();
    ByteBuffer byteBuffer = ByteBuffer.allocate(100);

  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
源代码8 项目: brpc-java   文件: GzipCompress.java

@Override
public ByteBuf compressInput(Object proto, RpcMethodInfo rpcMethodInfo) throws IOException {
    int protoSize = rpcMethodInfo.getInputSerializedSize(proto);
    ByteBuf resBuf = Unpooled.buffer(protoSize);
    OutputStream outputStream = new ByteBufOutputStream(resBuf);
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);

    if (protoSize > CodedOutputStream.DEFAULT_BUFFER_SIZE) {
        protoSize = CodedOutputStream.DEFAULT_BUFFER_SIZE;
    }
    final CodedOutputStream codedOutputStream =
            CodedOutputStream.newInstance(gzipOutputStream, protoSize);
    rpcMethodInfo.inputWriteToStream(proto, codedOutputStream);
    gzipOutputStream.close();
    return resBuf;
}
 
源代码9 项目: bazel   文件: NestedSetCodecWithStore.java

@Override
public void serialize(SerializationContext context, NestedSet<?> obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  context.serialize(obj.getOrder(), codedOut);
  if (obj.isEmpty()) {
    // If the NestedSet is empty, it needs to be assigned to the EMPTY_CHILDREN constant on
    // deserialization.
    codedOut.writeEnumNoTag(NestedSetSize.EMPTY.ordinal());
  } else if (obj.isSingleton()) {
    // If the NestedSet is a singleton, we serialize directly as an optimization.
    codedOut.writeEnumNoTag(NestedSetSize.LEAF.ordinal());
    context.serialize(obj.getChildren(), codedOut);
  } else {
    codedOut.writeEnumNoTag(NestedSetSize.NONLEAF.ordinal());
    context.serialize(obj.getApproxDepth(), codedOut);
    FingerprintComputationResult fingerprintComputationResult =
        nestedSetStore.computeFingerprintAndStore((Object[]) obj.getChildren(), context);
    context.addFutureToBlockWritingOn(fingerprintComputationResult.writeStatus());
    codedOut.writeByteArrayNoTag(fingerprintComputationResult.fingerprint().toByteArray());
  }
  interner.put(new EqualsWrapper(obj), obj);
}
 

private HistoryEvent testProtoConversion(HistoryEvent event) throws IOException, TezException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  HistoryEvent deserializedEvent = null;
  CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(os);
  event.toProtoStream(codedOutputStream);
  codedOutputStream.flush();
  os.flush();
  os.close();
  deserializedEvent = ReflectionUtils.createClazzInstance(
      event.getClass().getName());
  LOG.info("Serialized event to byte array"
      + ", eventType=" + event.getEventType()
      + ", bufLen=" + os.toByteArray().length);
  deserializedEvent.fromProtoStream(
      CodedInputStream.newInstance(os.toByteArray()));
  return deserializedEvent;
}
 
源代码11 项目: jprotobuf   文件: CodedConstant.java

/**
 * Compute object size no tag.
 *
 * @param o the o
 * @return the int
 */
public static int computeObjectSizeNoTag(Object o) {
    int size = 0;
    if (o == null) {
        return size;
    }

    Class cls = o.getClass();
    Codec target = ProtobufProxy.create(cls);
    try {
        size = target.size(o);
        size = size + CodedOutputStream.computeRawVarint32Size(size);
        return size;
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
源代码12 项目: trekarta   文件: TrackManager.java

/**
 * Saves track properties by modifying only file tail.
 */
public void saveProperties(FileDataSource source) throws Exception {
    Track track = source.tracks.get(0);
    // Prepare new properties tail
    ByteBuffer buffer = ByteBuffer.allocate(getSerializedPropertiesSize(track));
    CodedOutputStream output = CodedOutputStream.newInstance(buffer);
    output.writeBytes(FIELD_NAME, ByteString.copyFromUtf8(track.name));
    output.writeUInt32(FIELD_COLOR, track.style.color);
    output.writeFloat(FIELD_WIDTH, track.style.width);
    output.flush();
    // Modify tail of file
    File file = new File(source.path);
    long createTime = file.lastModified();
    RandomAccessFile access = new RandomAccessFile(file, "rw");
    access.setLength(source.propertiesOffset + 1);
    access.seek(source.propertiesOffset);
    access.write(buffer.array());
    access.close();
    //noinspection ResultOfMethodCallIgnored
    file.setLastModified(createTime);
}
 
源代码13 项目: bazel   文件: MultimapCodec.java

@Override
public void serialize(
    SerializationContext context, Multimap<K, V> obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  if (obj instanceof ListMultimap) {
    codedOut.writeBoolNoTag(true);
  } else if (obj instanceof SetMultimap) {
    codedOut.writeBoolNoTag(false);
  } else {
    throw new SerializationException("Unexpected multimap type: " + obj.getClass());
  }
  codedOut.writeInt32NoTag(obj.asMap().size());
  for (Map.Entry<K, Collection<V>> entry : obj.asMap().entrySet()) {
    context.serialize(entry.getKey(), codedOut);
    context.serialize(entry.getValue(), codedOut);
  }
}
 
源代码14 项目: flink   文件: PhysicalWriterImpl.java

public PhysicalWriterImpl(FSDataOutputStream out, OrcFile.WriterOptions opts) throws IOException {
	if (opts.isEnforceBufferSize()) {
		this.bufferSize = opts.getBufferSize();
	} else {
		this.bufferSize = getEstimatedBufferSize(
			opts.getStripeSize(), opts.getSchema().getMaximumId() + 1, opts.getBufferSize());
	}

	this.out = out;
	this.blockOffset = 0;
	this.blockSize = opts.getBlockSize();
	this.maxPadding = (int) (opts.getPaddingTolerance() * (double) opts.getBufferSize());
	this.compress = opts.getCompress();
	this.codec = OrcCodecPool.getCodec(this.compress);
	this.streams  = new TreeMap<>();
	this.writer = new OutStream("metadata", this.bufferSize, this.codec, new DirectStream(this.out));
	this.shims = opts.getHadoopShims();
	this.addBlockPadding = opts.getBlockPadding();
	this.protobufWriter = CodedOutputStream.newInstance(this.writer);
	this.writeVariableLengthBlocks = opts.getWriteVariableLengthBlocks();
}
 

private void sendSaslMessage(ChannelHandlerContext ctx, byte[] payload,
    List<CipherOption> options) throws IOException {
  DataTransferEncryptorMessageProto.Builder builder =
      DataTransferEncryptorMessageProto.newBuilder();
  builder.setStatus(DataTransferEncryptorStatus.SUCCESS);
  if (payload != null) {
    BuilderPayloadSetter.wrapAndSetPayload(builder, payload);
  }
  if (options != null) {
    builder.addAllCipherOption(PBHelperClient.convertCipherOptions(options));
  }
  DataTransferEncryptorMessageProto proto = builder.build();
  int size = proto.getSerializedSize();
  size += CodedOutputStream.computeRawVarint32Size(size);
  ByteBuf buf = ctx.alloc().buffer(size);
  proto.writeDelimitedTo(new ByteBufOutputStream(buf));
  ctx.write(buf);
}
 
源代码16 项目: bazel   文件: Artifact.java

@Override
public void serialize(
    SerializationContext context, SpecialArtifact obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  context.serialize(obj.getRoot(), codedOut);
  context.serialize(obj.getGeneratingActionKey(), codedOut);
  context.serialize(obj.type, codedOut);
  context.serialize(obj.getRootRelativePath(), codedOut);
}
 
源代码17 项目: bazel   文件: SerializationContextTest.java

@Override
public void serialize(
    SerializationContext context, ImmutableList<Object> obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  context = context.getMemoizingContext();
  codedOut.writeInt32NoTag(obj.size());
  for (Object item : obj) {
    context.serialize(item, codedOut);
  }
}
 
源代码18 项目: zetasketch   文件: State.java

private void writeHllTo(CodedOutputStream stream) throws IOException {
  // We use the NoTag write methods for consistency with the parsing functions and for
  // consistency with the variable-length writes where we can't use any convenience function.
  if (sparseSize != DEFAULT_SPARSE_SIZE) {
    stream.writeUInt32NoTag(SPARSE_SIZE_TAG);
    stream.writeInt32NoTag(sparseSize);
  }

  if (precision != DEFAULT_PRECISION_OR_NUM_BUCKETS) {
    stream.writeUInt32NoTag(PRECISION_OR_NUM_BUCKETS_TAG);
    stream.writeInt32NoTag(precision);
  }

  if (sparsePrecision != DEFAULT_SPARSE_PRECISION_OR_NUM_BUCKETS) {
    stream.writeUInt32NoTag(SPARSE_PRECISION_OR_NUM_BUCKETS_TAG);
    stream.writeInt32NoTag(sparsePrecision);
  }

  // Static analysis can not verify that stream.writeUInt32NoTag does not null out this.data
  final ByteSlice data = this.data;
  if (data != null) {
    stream.writeUInt32NoTag(DATA_TAG);
    stream.writeUInt32NoTag(data.remaining());
    stream.writeLazy(data.byteBuffer());
  }

  // Static analysis can not verify that stream.writeUInt32NoTag does not null out this.sparseData
  final GrowingByteSlice sparseData = this.sparseData;
  if (sparseData != null) {
    stream.writeUInt32NoTag(SPARSE_DATA_TAG);
    stream.writeUInt32NoTag(sparseData.remaining());
    stream.writeLazy(sparseData.byteBuffer());
  }
}
 
源代码19 项目: zetasketch   文件: State.java

private int getSerializedHllSize() {
  int size = 0;

  if (sparseSize != DEFAULT_SPARSE_SIZE) {
    size += CodedOutputStream.computeUInt32SizeNoTag(SPARSE_SIZE_TAG);
    size += CodedOutputStream.computeInt32SizeNoTag(sparseSize);
  }

  if (precision != DEFAULT_PRECISION_OR_NUM_BUCKETS) {
    size += CodedOutputStream.computeUInt32SizeNoTag(PRECISION_OR_NUM_BUCKETS_TAG);
    size += CodedOutputStream.computeInt32SizeNoTag(precision);
  }

  if (sparsePrecision != DEFAULT_SPARSE_PRECISION_OR_NUM_BUCKETS) {
    size += CodedOutputStream.computeUInt32SizeNoTag(SPARSE_PRECISION_OR_NUM_BUCKETS_TAG);
    size += CodedOutputStream.computeInt32SizeNoTag(sparsePrecision);
  }

  if (data != null) {
    int dataLength = data.remaining();
    size += CodedOutputStream.computeUInt32SizeNoTag(DATA_TAG);
    size += CodedOutputStream.computeUInt32SizeNoTag(dataLength);
    size += dataLength;
  }

  if (sparseData != null) {
    int sparseDataLength = sparseData.remaining();
    size += CodedOutputStream.computeUInt32SizeNoTag(SPARSE_DATA_TAG);
    size += CodedOutputStream.computeUInt32SizeNoTag(sparseDataLength);
    size += sparseDataLength;
  }

  return size;
}
 

private static void equalsTest(p_test.p_testMsg msg) throws IOException {
    final Parser<p_test.p_testMsg> parser = msg.getParserForType();

    final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(buffer);
    writeTypeId(msg, codedOutputStream);
    msg.writeTo(codedOutputStream);
    System.out.println("encode result bytes = " + codedOutputStream.getTotalBytesWritten());

    final CodedInputStream inputStream = CodedInputStream.newInstance(buffer, 0, codedOutputStream.getTotalBytesWritten());
    final Class<?> type = readType(inputStream);
    final Object decodeMsg = parser.parseFrom(inputStream);
    System.out.println("codec equals result = " + msg.equals(decodeMsg));
}
 
源代码21 项目: blueflood   文件: BasicRollupSerDes.java

protected int sizeOf(BasicRollup basicRollup, byte version) {

        int sz = sizeOfBaseRollup( basicRollup );
        if( version == VERSION_2_ROLLUP )
            sz += CodedOutputStream.computeDoubleSizeNoTag(basicRollup.getSum());

        return sz;
    }
 
源代码22 项目: blueflood   文件: StatsSerDes.java

public int sizeOf(T stat) {
    int sz = 1 + 1; // type + isFP.
    sz += stat.isFloatingPoint() ?
            CodedOutputStream.computeDoubleSizeNoTag(stat.toDouble()) :
            CodedOutputStream.computeRawVarint64Size(stat.toLong());
    return sz;
}
 

@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	MediaType contentType = outputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = getDefaultContentType(message);
		Assert.state(contentType != null, "No content type");
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	if (PROTOBUF.isCompatibleWith(contentType)) {
		setProtoHeader(outputMessage, message);
		CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
		message.writeTo(codedOutputStream);
		codedOutputStream.flush();
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
		TextFormat.print(message, outputStreamWriter);
		outputStreamWriter.flush();
		outputMessage.getBody().flush();
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
		outputMessage.getBody().flush();
	}
}
 
源代码24 项目: bazel   文件: ImmutableBiMapCodecTest.java

@Override
public void serialize(SerializationContext context, Dummy value, CodedOutputStream codedOut)
    throws SerializationException {
  if (throwsOnSerialization) {
    throw new SerializationException("Expected failure");
  }
}
 
源代码25 项目: bazel   文件: HashSetCodec.java

@Override
public void serialize(SerializationContext context, HashSet<E> obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  codedOut.writeInt32NoTag(obj.size());
  for (Object object : obj) {
    context.serialize(object, codedOut);
  }
}
 
源代码26 项目: teku   文件: ProtobufEncoder.java

public static Bytes encodeVarInt(final int value) {
  try {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(output);
    codedOutputStream.writeUInt32NoTag(value);
    codedOutputStream.flush();
    return Bytes.wrap(output.toByteArray());
  } catch (final IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码27 项目: bazel   文件: LongArrayCodec.java

@Override
public void serialize(SerializationContext context, long[] obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  codedOut.writeInt32NoTag(obj.length);
  for (long l : obj) {
    codedOut.writeInt64NoTag(l);
  }
}
 
源代码28 项目: bazel   文件: DynamicCodec.java

@Override
public void serialize(SerializationContext context, Object obj, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  for (int i = 0; i < offsets.length; ++i) {
    serializeField(context, codedOut, obj, offsets[i].type, offsets[i].offset);
  }
}
 
源代码29 项目: blueflood   文件: GaugeSerDes.java

private void serializeGauge(BluefloodGaugeRollup rollup, byte[] buf) throws IOException {
    rollupSize.update(buf.length);
    CodedOutputStream protobufOut = CodedOutputStream.newInstance(buf);
    serializeRollupV1(rollup, protobufOut);
    protobufOut.writeRawVarint64(rollup.getTimestamp());
    putUnversionedDoubleOrLong(rollup.getLatestNumericValue(), protobufOut);
}
 
源代码30 项目: bazel   文件: ImmutableSortedSetCodec.java

@Override
public void serialize(
    SerializationContext context, ImmutableSortedSet<E> object, CodedOutputStream codedOut)
    throws SerializationException, IOException {
  context.serialize(object.comparator(), codedOut);
  codedOut.writeInt32NoTag(object.size());
  for (Object obj : object) {
    context.serialize(obj, codedOut);
  }
}
 
 类所在包
 同包方法