Skip to content

Instantly share code, notes, and snippets.

@adutra
Created May 31, 2016 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adutra/9f09f1c8e377ee774f6388d5fb073045 to your computer and use it in GitHub Desktop.
Save adutra/9f09f1c8e377ee774f6388d5fb073045 to your computer and use it in GitHub Desktop.
IntBlobCodec.java
package com.datastax.driver.extras.codecs.blobs;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.TypeCodec;
import java.nio.ByteBuffer;
public class IntBlobCodec extends TypeCodec.PrimitiveIntCodec {
public static final IntBlobCodec INSTANCE = new IntBlobCodec();
private IntBlobCodec() {
super(DataType.blob());
}
@Override
public ByteBuffer serializeNoBoxing(int value, ProtocolVersion protocolVersion) {
return wrap(value);
}
@Override
public int deserializeNoBoxing(ByteBuffer value, ProtocolVersion protocolVersion) {
return unwrap(value);
}
@Override
public Integer parse(String value) {
return unwrap(TypeCodec.blob().parse(value));
}
@Override
public String format(Integer value) {
return TypeCodec.blob().format(wrap(value));
}
private ByteBuffer wrap(int value) {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(value);
bb.flip();
return bb;
}
private int unwrap(ByteBuffer bytes) {
return (bytes == null || bytes.remaining() == 0) ? 0 : bytes.duplicate().getInt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment