Skip to content

Commit

Permalink
AVRO-4073: Create Convenience toBytes Method for Datum Writer (#3197)
Browse files Browse the repository at this point in the history
  • Loading branch information
belugabehr authored Oct 7, 2024
1 parent 84bc732 commit ec2378b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lang/java/avro/src/main/java/org/apache/avro/io/DatumWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/
package org.apache.avro.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.avro.Schema;
Expand All @@ -36,4 +37,19 @@ public interface DatumWriter<D> {
* the schema from the datum to the output.
*/
void write(D datum, Encoder out) throws IOException;

/**
* Convenience method to Write a datum to a byte array. Traverse the schema,
* depth first, writing each leaf value in the schema from the datum to the byte
* array.
*
* @param datum The datum to serialize
* @return The serialized datum stored in an array of bytes
*/
default byte[] toByteArray(D datum) throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream(128)) {
write(datum, EncoderFactory.get().directBinaryEncoder(out, null));
return out.toByteArray();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,20 @@ void nonStringable() throws Exception {
}
}

@Test
void testToByteArray() throws Exception {
final Schema string = Schema.create(Type.STRING);
final DatumWriter<String> writer = new SpecificDatumWriter<>(string);

try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
final Encoder encoder = EncoderFactory.get().directBinaryEncoder(baos, null);
writer.write("test", encoder);

final byte[] bytes = writer.toByteArray("test");
assertArrayEquals(baos.toByteArray(), bytes);
}
}

@Test
void classNameContainingReservedWords() {
final Schema schema = Schema.createRecord("AnyName", null, "db.public.table", false);
Expand Down

0 comments on commit ec2378b

Please # to comment.