ByteData.java

// <editor-fold defaultstate="collapsed" desc="license">
/*
 * Copyright (c) 2014, Karl H. Beckers
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the <ORGANIZATION> nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 **/
// </editor-fold>
package net.jarre_de_the.griffin.types.data;

import java.io.IOException;
import java.io.RandomAccessFile;
import net.jarre_de_the.griffin.exception.ValueTooLargeException;
import net.jarre_de_the.griffin.exception.ValueTooSmallException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation of the BYTE data type. The GFF BYTE is a single unsigned byte
 * and can contain values from 0 to 255.
 * <p>
 * @author charly4711
 */
public class ByteData extends AbstractFixedLengthData<Byte, ByteData>
        implements NumberData<Short>, Cloneable {

    public static final int LENGTH = 1;
    private static final Logger LOGGER = LoggerFactory.getLogger(ByteData.class);
    private byte value = (byte) 0;

    /*
     *
     * constructors
     *
     */
    protected ByteData() {
    }

    /**
     * Creates a new instance of {@code ByteData} and sets a defined value.
     * <p>
     * @param b The value to set. Note that this parameter should only be
     * understood as a bitfield, because a Java byte is signed, a BYTE unsigned.
     */
    public ByteData(byte b) {
        setValue(b);
    }

    /**
     * Creates a new instance of {@code ByteData} and sets a defined value.
     * <p>
     * @param s the value to set in the natural, numeric representation that
     * only fits into a Java short rather than a byte. If you pass a value
     * that doesn't fit into a BYTE, you will get a ValueTooSmallException or
     * ValueTooLargeException runtime exception.
     */
    public ByteData(short s) {
        setValue(s);
    }

    /*
     *
     * read from file
     *
     */
    /**
     * Creates a new instance of {@code ByteData} based on the data read from
     * the file passed. Note that the contents are read from whatever position
     * the file pointer is at.
     * <p>
     * @param in An open {@code RandomAccessFile}.
     * @return
     * @throws java.io.IOException If there are any I/O related problems with
     * file access to in.
     */
    public static ByteData read(RandomAccessFile in)
            throws IOException {
        return new ByteData((Byte) read(in, Byte.class));
    }

    /*
     *
     * setter
     *
     */
    private void setValue(byte b) {
        value = b;
    }

    private void setValue(short s) {
        if (s < 0) {
            throw new ValueTooSmallException(0L, s);
        } else if (s > (Math.pow(2, 8) - 1)) {
            throw new ValueTooLargeException((long) (Math.pow(2, 8) - 1), s);
        }
        value = (byte) s;
    }

    /*
     *
     * getter
     *
     */
    @Override
    public Byte getValue() {
        return value;
    }

    @Override
    public Short getValueAsNumber() {
        short s = 0;
        short mask = Short.parseShort("00FF", 16);
        s = (short) ((short) (s | (short) value) & mask);

        return s;
    }

    @Override
    public byte[] getValueAsByteArray() {
        return super.getValueAsByteArray(value);
    }

    /*
     *
     * utility
     *
     */
    @Override
    public int length() {
        return LENGTH;
    }

    /**
     * Overrides the {@code java.lang.Object} method to ensure we always get
     * back an instance of {@code ByteData} rather than just {@code Object}.
     * <p>
     * @return A deep copy of this object.
     * @throws java.lang.CloneNotSupportedException
     */
    @Override
    public ByteData clone() throws CloneNotSupportedException {
        LOGGER.debug("Cloning object");

        ByteData clone = (ByteData) super.clone();
        clone.setValue((byte) (value & 0x00FF));

        return clone;
    }

    @Override
    public boolean equals(Object compare) {
        if (compare == this) {
            return true;
        }

        if (!(compare instanceof ByteData)) {
            return false;
        }

        ByteData bd = (ByteData) compare;
        return this.getValueAsNumber().equals(bd.getValueAsNumber());
    }

    @Override
    public int hashCode() {
        int code = 0;
        int mask = Integer.parseInt("11000000", 2);
        code |= (value & mask) << 24;
        mask = Integer.parseInt("00110000", 2);
        code |= (value & mask) << 16;
        mask = Integer.parseInt("00001100", 2);
        code |= (value & mask) << 8;
        mask = Integer.parseInt("00000011", 2);
        code |= (value & mask);

        return code;
    }

    @Override
    public String toString() {
        return "" + value;
    }
}