package iitb.con.indexing.isam;
import iitb.con.ds.ItemSerializer;
import java.nio.ByteBuffer;
public class NonLeafNode implements ItemSerializer<NonLeafNode> {
public short BlockId = -1;
public Object value;
private static final byte PREFIX_SIZE = 8;
private static final char TERMINATING_CHAR = '$';
public NonLeafNode(){ }
public NonLeafNode(Object value){
this.value = value;
}
public NonLeafNode(Object value, short BlockId){
this.BlockId = BlockId;
this.value = value;
}
public ByteBuffer serialize(NonLeafNode node) {
ByteBuffer buf = null;
if(value != null) {
if(value instanceof String) {
value = getStringPrefix(((String)value));
buf = ByteBuffer.allocate(2 + PREFIX_SIZE);
buf.put(((String)value).getBytes());
}else if(value instanceof Integer) {
buf = ByteBuffer.allocate(6);
buf.putInt((Integer)value);
}else if(value instanceof Float) {
buf = ByteBuffer.allocate(6);
buf.putFloat((Float)value);
}else if(value instanceof Double) {
buf = ByteBuffer.allocate(10);
buf.putDouble((Double)value);
}else if(value instanceof Boolean) {
buf = ByteBuffer.allocate(3);
if(((Boolean)value).booleanValue())
buf.put((byte)1);
else
buf.put((byte)0);
}
buf.putShort(node.BlockId);
}
buf.rewind();
return buf;
}
private String getStringPrefix(String s){
if(s.length() >= PREFIX_SIZE)
return s.substring(0, PREFIX_SIZE);
else {
char[] chars = new char[PREFIX_SIZE];
for(int i = 0; i < s.length(); i++)
chars[i] = s.charAt(i);
for(int i = s.length(); i < PREFIX_SIZE; i++)
chars[i] = TERMINATING_CHAR;
return new String(chars);
}
}
private String trimStringPrefix(byte[] b){
char[] chars = new char[PREFIX_SIZE];
for(int i = 0; i < b.length; i++) {
chars[i] = (char)b[i];
if(chars[i] == TERMINATING_CHAR) {
char [] ch = new char[i];
for(int j = 0; j < i ; j++)
ch[j] = chars[j];
return new String(ch);
}
}
return new String(chars);
}
public NonLeafNode deSerialize(ByteBuffer buf) {
if(value != null) {
if(value instanceof String) {
byte[] tempBuf = new byte[PREFIX_SIZE];
buf.get(tempBuf);
this.value = trimStringPrefix(tempBuf);
}else if(value instanceof Integer) {
this.value = new Integer(buf.getInt());
}else if(value instanceof Float) {
this.value = new Float(buf.getFloat());
}else if(value instanceof Double) {
this.value = new Double(buf.getDouble());
}else if(value instanceof Boolean) {
if (buf.get() == 0)
this.value = new Boolean(false);
else
this.value = new Boolean(true);
}
this.BlockId = buf.getShort();
}
return this;
}
public Object attributeDeSerialize(ByteBuffer buf, Object name) {
return null;
}
}