public void writeObject()

in foundations/foundation-protobuf/src/main/java/io/protostuff/ProtobufOutputEx.java [163:236]


  public <T> void writeObject(final int tag, int tagSize, final T value, final SchemaWriter<T> schemaWriter)
      throws IOException {
    final LinkedBuffer lastBuffer;

    // write the tag
    if (tagSize == 1 && tail.offset != tail.buffer.length) {
      lastBuffer = tail;
      size++;
      lastBuffer.buffer[lastBuffer.offset++] = (byte) tag;
    } else {
      tail = lastBuffer = writeRawVarInt32(tag, this, tail);
    }

    final int lastOffset = tail.offset, lastSize = size;

    if (lastOffset == lastBuffer.buffer.length) {
      // not enough size for the 1-byte delimiter
      final LinkedBuffer nextBuffer = new LinkedBuffer(nextBufferSize);
      // new buffer for the content
      tail = nextBuffer;

      schemaWriter.writeTo(this, value);

      final int msgSize = size - lastSize;

      final byte[] delimited = new byte[computeRawVarint32Size(msgSize)];
      writeRawVarInt32(msgSize, delimited, 0);

      size += delimited.length;

      // wrap the byte array (delimited) and insert between the two buffers
      new LinkedBuffer(delimited, 0, delimited.length, lastBuffer).next = nextBuffer;
      return;
    }

    // we have enough space for the 1-byte delim
    lastBuffer.offset++;
    size++;

    schemaWriter.writeTo(this, value);

    final int msgSize = size - lastSize - 1;

    // optimize for small messages
    if (msgSize < 128) {
      // fits
      lastBuffer.buffer[lastOffset] = (byte) msgSize;
      return;
    }

    // split into two buffers

    // the second buffer (contains the message contents)
    final LinkedBuffer view = new LinkedBuffer(lastBuffer.buffer,
        lastOffset + 1, lastBuffer.offset);

    if (lastBuffer == tail) {
      tail = view;
    } else {
      view.next = lastBuffer.next;
    }

    // the first buffer (contains the tag)
    lastBuffer.offset = lastOffset;

    final byte[] delimited = new byte[computeRawVarint32Size(msgSize)];
    writeRawVarInt32(msgSize, delimited, 0);

    // add the difference
    size += (delimited.length - 1);

    // wrap the byte array (delimited) and insert between the two buffers
    new LinkedBuffer(delimited, 0, delimited.length, lastBuffer).next = view;
  }