### Question:
BsonEncoder { public static void encodeDocument(Map<String, ?> document, ByteBuf out) { int indexBefore = out.writerIndex(); out.writeIntLE(0); for (String key : document.keySet()) { encodeValue(key, document.get(key), out); } out.writeByte(BsonConstants.TERMINATING_BYTE); int indexAfter = out.writerIndex(); out.writerIndex(indexBefore); out.writeIntLE(indexAfter - indexBefore); out.writerIndex(indexAfter); } private  BsonEncoder(); static void encodeDocument(Map<String, ?> document, ByteBuf out); static void encodeValue(byte type, Object value, ByteBuf buffer); static byte determineType(Object value);  }### Answer:
@Test void testEncodeEmptyDocument() throws Exception { Document document = new Document(); ByteBuf buffer = Unpooled.buffer(); try { BsonEncoder.encodeDocument(document, buffer); assertThat(buffer.writerIndex()).isEqualTo(5); assertThat(buffer.readerIndex()).isEqualTo(0); assertThat(buffer.readIntLE()).isEqualTo(5); assertThat(buffer.readByte()).isEqualTo(BsonConstants.TERMINATING_BYTE); } finally { buffer.release(); } }
@Test void testEncodeDecodeRoundtrip() throws Exception { Document document = new Document(); document.put("key1", "value"); document.put("key2", 123.0); document.put("key3", Arrays.asList(1L, 2L)); document.put("key4", true); document.put("key5", UUID.randomUUID()); document.put("key6", new ObjectId()); ByteBuf buffer = Unpooled.buffer(); try { BsonEncoder.encodeDocument(document, buffer); Document decodedDocument = BsonDecoder.decodeBson(buffer); assertThat(decodedDocument).isEqualTo(document); } finally { buffer.release(); } }