Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AVRO-4073: Create Convenience toBytes Method for Datum Writer #3197

Merged
merged 1 commit into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading