public final class IntFloatMapMarshaller
implements BytesReader<Map<Integer, Float>>, BytesWriter<Map<Integer, Float>> {
public static final IntFloatMapMarshaller INSTANCE = new IntFloatMapMarshaller();
private IntFloatMapMarshaller() {}
@NotNull
@Override
public Map<Integer, Float> read(@NotNull Bytes bytes, long sizeInBytes) {
return read(bytes, sizeInBytes, null);
}
@NotNull
@Override
public Map<Integer, Float> read(@NotNull Bytes bytes, long sizeInBytes,
@Nullable Map<Integer, Float> toReuse) {
int mapSize = (int) (sizeInBytes / 8);
if (toReuse == null) {
// Might want to create a more efficient, specialized Map here, instead of HashMap
// * 4 / 3 because HashMap's default load factor is 0.75
// This is java.util.HashMap-specific, not needed for a different Map impl
int hashMapCapacity = mapSize * 4 / 3 + 1;
toReuse = new HashMap<>(hashMapCapacity);
} else {
toReuse.clear();
}
for (int i = 0; i < mapSize; i++) {
toReuse.put(bytes.readInt(), bytes.readFloat());
}
return toReuse;
}
@Override
public long size(@NotNull Map<Integer, Float> map) {
return map.size() * 8L;
}
@Override
public void write(@NotNull Bytes bytes, @NotNull Map<Integer, Float> map) {
map.forEach((k, v) -> {
bytes.writeInt(k);
bytes.writeFloat(v);
});
}
}