if (t == null) {
throw new IllegalArgumentException("Object to marshall cannot be null");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CodedOutputStream out = CodedOutputStream.newInstance(baos);
if (t instanceof String) {
out.writeString(wrappedInt64, (String) t);
} else if (t instanceof Long) {
out.writeInt64(wrappedInt64, (Long) t);
} else if (t instanceof Integer) {
out.writeInt32(wrappedInt32, (Integer) t);
} else if (t instanceof Double) {
out.writeDouble(wrappedDouble, (Double) t);
} else if (t instanceof Float) {
out.writeFloat(wrappedFloat, (Float) t);
} else if (t instanceof Boolean) {
out.writeBool(wrappedBool, (Boolean) t);
} else if (t instanceof byte[]) {
byte[] bytes = (byte[]) t;
out.writeTag(wrappedBytes, WireFormat.WIRETYPE_LENGTH_DELIMITED);
out.writeRawVarint32(bytes.length);
out.writeRawBytes(bytes);
} else if (t instanceof Enum) {
// use an enum encoder
EnumEncoder enumEncoder = ctx.getEnumEncoder((Class<Enum>) t.getClass());
out.writeString(wrappedDescriptorFullName, enumEncoder.getFullName());
out.writeEnum(wrappedEnum, enumEncoder.encode((Enum) t));
} else {
// this is either an unknown primitive type or a message type
// try to use a message marshaller
MessageMarshaller marshaller = ctx.getMarshaller(t.getClass());
out.writeString(wrappedDescriptorFullName, marshaller.getFullName());
out.writeTag(wrappedMessageBytes, WireFormat.WIRETYPE_LENGTH_DELIMITED);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); //todo here we should use a better buffer allocation strategy
CodedOutputStream out2 = CodedOutputStream.newInstance(baos2);
ProtobufWriterImpl writer = new ProtobufWriterImpl(ctx);
writer.write(out2, t);
out.writeRawVarint32(baos2.size());
out.writeRawBytes(baos2.toByteArray());
}