Package org.chaidb.db.api.keys

Source Code of org.chaidb.db.api.keys.FloatKey

/*
* 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 FloatKey implements Key {

    public float key;

    /**
     * Construct a FloatKey from byte[]
     */
    public FloatKey(byte[] encoded) {
        int intBits = ByteTool.bytesToInt(encoded, 0, true);
        key = Float.intBitsToFloat(intBits);
    }

    /**
     * Constructor
     */
    public FloatKey(float key) {
        this.key = key;
    }

    // implement Key methods

    public byte[] toBytes() {
        int intBits = Float.floatToIntBits(key);
        return ByteTool.intToBytes(intBits, true);
    }

    public int size() {
        return 4;
    }

    public String toString() {
        return Float.toString(key);
    }

    public int getKeyType() {
        return FLOAT_KEY;
    }

    public int compareTo(Key otherKey) throws ChaiDBException {
        checkKeyType(otherKey);
        FloatKey key2 = (FloatKey) otherKey;
        return KeyTool.compareFloat(key, key2.key);
    }

    private void checkKeyType(Key otherKey) throws ChaiDBException {
        int keyType = otherKey.getKeyType();
        if (keyType != FLOAT_KEY) {
            ArrayList params = new ArrayList(2);
            // required
            params.add(Key.KEY_TYPES[Key.FLOAT_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 Float.floatToIntBits(key);
    }

    public boolean equals(Object obj) {
        if (obj instanceof FloatKey) return KeyTool.compareFloat(key, ((FloatKey) obj).key) == 0;
        return false;
    }

    public Object clone() {
        return new FloatKey(key);
    }
}
TOP

Related Classes of org.chaidb.db.api.keys.FloatKey

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.