Skip to content

Instantly share code, notes, and snippets.

@edanuff
Created December 17, 2010 23:27
Show Gist options
  • Save edanuff/745898 to your computer and use it in GitHub Desktop.
Save edanuff/745898 to your computer and use it in GitHub Desktop.
Replacement UUIDType for Cassandra
import java.nio.ByteBuffer;
import java.util.UUID;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.MarshalException;
import org.apache.cassandra.utils.ByteBufferUtil;
/**
* @author edanuff
*
*/
public class UUIDType extends AbstractType {
/**
*
*/
public static final UUIDType instance = new UUIDType();
UUIDType() {
} // singleton
@Override
public int compare(ByteBuffer b1, ByteBuffer b2) {
if ((b1 == null) || (b1.remaining() < 16)) {
return ((b2 == null) || (b2.remaining() < 16)) ? 0 : -1;
}
if ((b2 == null) || (b2.remaining() < 16)) {
return 1;
}
int s1 = b1.arrayOffset() + b1.position();
byte[] o1 = b1.array();
int s2 = b2.arrayOffset() + b2.position();
byte[] o2 = b2.array();
if (o1.length == s1) {
return o2.length == s2 ? 0 : -1;
}
if (o2.length == s2) {
return 1;
}
if (((o1[s1 + 6] & 0xf0) == 0x10) && ((o2[s2 + 6] & 0xf0) == 0x10)) {
int res = compareTimestampBytes(s1, o1, s2, o2);
if (res != 0) {
return res;
}
}
return ByteBufferUtil.compareUnsigned(b1, b2);
}
private static int compareTimestampBytes(int s1, byte[] o1, int s2,
byte[] o2) {
int d = (o1[s1 + 6] & 0xF) - (o2[s2 + 6] & 0xF);
if (d != 0) {
return d;
}
d = (o1[s1 + 7] & 0xFF) - (o2[s2 + 7] & 0xFF);
if (d != 0) {
return d;
}
d = (o1[s1 + 4] & 0xFF) - (o2[s2 + 4] & 0xFF);
if (d != 0) {
return d;
}
d = (o1[s1 + 5] & 0xFF) - (o2[s2 + 5] & 0xFF);
if (d != 0) {
return d;
}
d = (o1[s1 + 0] & 0xFF) - (o2[s2 + 0] & 0xFF);
if (d != 0) {
return d;
}
d = (o1[s1 + 1] & 0xFF) - (o2[s2 + 1] & 0xFF);
if (d != 0) {
return d;
}
d = (o1[s1 + 2] & 0xFF) - (o2[s2 + 2] & 0xFF);
if (d != 0) {
return d;
}
return (o1[s1 + 3] & 0xFF) - (o2[s2 + 3] & 0xFF);
}
private static UUID getUUID(ByteBuffer bytes) {
bytes = bytes.slice();
if (bytes.remaining() < 16) {
return new UUID(0, 0);
}
UUID uuid = new UUID(bytes.getLong(), bytes.getLong());
return uuid;
}
@Override
public void validate(ByteBuffer bytes) {
if ((bytes.remaining() != 0) && (bytes.remaining() != 16)) {
throw new MarshalException("UUIDs must be exactly 16 bytes");
}
}
@Override
public String getString(ByteBuffer bytes)
{
if (bytes.remaining() == 0) {
return "";
}
if (bytes.remaining() != 16) {
throw new MarshalException("UUIDs must be exactly 16 bytes");
}
UUID uuid = getUUID(bytes);
return uuid.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment