Skip to content
Prev Previous commit
Next Next commit
Add a few more tests
  • Loading branch information
komamitsu committed Sep 13, 2022
commit af3d69fb36ab1210d3d44c1408512623704d010b
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.msgpack.core.ExtensionTypeHeader;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageUnpacker;

import java.io.IOException;
import java.time.Instant;
Expand Down Expand Up @@ -66,26 +69,16 @@ protected InstantDeserializer(Class<?> vc)
public Instant deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
// TODO: Check header for all possible cases
MessagePackExtensionType ext = p.readValueAs(MessagePackExtensionType.class);
if (ext.getType() != EXT_TYPE) {
throw new RuntimeException(
String.format("Unexpected extension type (0x%X) for Instant object", ext.getType()));
}

byte[] bytes = ext.getData();

int nanoSeconds = 0;
for (int i = 0; i < SIZE_OF_NANOS_IN_BYTES; i++) {
nanoSeconds += ((int) bytes[i] & 0xFF) << (((SIZE_OF_NANOS_IN_BYTES - 1) - i) * 8);
}

long epochSeconds = 0;
for (int i = 0; i < SIZE_OF_EPOCH_SECONDS_IN_BYTES; i++) {
epochSeconds += ((long) bytes[i + SIZE_OF_NANOS_IN_BYTES] & 0xFF) << (((SIZE_OF_EPOCH_SECONDS_IN_BYTES - 1) - i) * 8);
// MEMO: Reusing this MessageUnpacker instance would improve the performance
try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(ext.getData())) {
return unpacker.unpackTimestamp(new ExtensionTypeHeader(EXT_TYPE, ext.getData().length));
}

return Instant.ofEpochSecond(epochSeconds, nanoSeconds);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.msgpack.core.MessagePack;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.Objects;

import static org.junit.Assert.*;

Expand Down Expand Up @@ -73,4 +76,21 @@ public void testTripleInstantsPojo()
assertEquals(now, deserialized.b);
assertEquals(now.plusSeconds(1), deserialized.c);
}

@Test
public void deserialize64BitFormat()
throws IOException
{
Instant now = Instant.now();

ByteArrayOutputStream os = new ByteArrayOutputStream();
MessagePack.newDefaultPacker(os)
.packMapHeader(1)
.packString("instant")
.packTimestamp(now)
.close();

SingleInstant deserialized = objectMapper.readValue(os.toByteArray(), SingleInstant.class);
assertEquals(now, deserialized.instant);
}
}