/*
* Copyright (C) 2006 http://www.chaidb.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
package org.chaidb.db.api.keys;
import org.chaidb.db.exception.ChaiDBException;
import org.chaidb.db.exception.ErrorCode;
import org.chaidb.db.helper.ByteTool;
import org.chaidb.db.index.Key;
import java.util.ArrayList;
public class IntKey implements Key {
// the value of IntKey
public int key;
/**
* Construct an IntKey out of byte[].
*/
public IntKey(byte[] encoded) {
key = ByteTool.bytesToInt(encoded, 0, true);
}
/**
* Constructor
*
* @param key the IntKey value
*/
public IntKey(int key) {
this.key = key;
}
// implement Key methods
public int getKeyType() {
return INT_KEY;
}
public byte[] toBytes() {
return ByteTool.intToBytes(key, true);
}
public int size() {
return 4;
}
public String toString() {
return Integer.toString(key);
}
/**
* Compares to another IntKey.
*/
public int compareTo(Key otherKey) throws ChaiDBException {
checkKeyType(otherKey);
IntKey key2 = (IntKey) otherKey;
return KeyTool.compareInt(key, key2.key);
}
private void checkKeyType(Key key) throws ChaiDBException {
int keyType = key.getKeyType();
if (keyType != INT_KEY) {
ArrayList params = new ArrayList(2);
// required
params.add(Key.KEY_TYPES[Key.INT_KEY]);
// found
params.add(Key.KEY_TYPES[keyType]);
throw new ChaiDBException(ErrorCode.INDEX_KEY_TYPE_ERROR, params);
}
}
// override java.lang.Object methods
public int hashCode() {
return key;
}
public boolean equals(Object obj) {
if (obj instanceof IntKey) return KeyTool.compareInt(key, ((IntKey) obj).key) == 0;
return false;
}
public Object clone() {
return new IntKey(key);
}
public int getInt() {
return key;
}
}