DWordData.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 DWORD data type. The GFF DWORD is a four bytes unsigned integer and can have a value from 0 to
 * 4294967296.
 * <p>
 * @author charly4711
 */
public class DWordData extends AbstractFixedLengthData<Integer, DWordData>
        implements NumberData<Long>, Cloneable {

    /**
     * The length of a DWORD in bytes
     */
    public static final int LENGTH = 4;
    private static final Logger LOGGER = LoggerFactory.getLogger(DWordData.class);
    private int value = 0;

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

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

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

    /*
     *
     * read from file
     *
     */
    /**
     * Creates a new instance of {@code DWordData} 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 DWordData read(RandomAccessFile in)
            throws IOException {
        return new DWordData((int)read(in, Integer.class));
    }

    /*
     *
     * setter
     *
     */
    /**
     * Sets this instance's value.
     * <p>
     * @param i The value to set.
     */
    private void setValue(int i) {
        value = i;
    }

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

    /*
     *
     * getter
     *
     */
    /**
     * Returns this instance's numeric value as a long. A DWORD is four bytes as is the Java int primitive type.
     * However, a DWORD is always unsigned and there is no unsigned int in Java. Therefore, to make sure you always
     * retrieve the correct positive number, use this method.
     * <p>
     * @return The numeric value of this instance.
     */
    @Override
    public Long getValueAsNumber() {
        long l = 0;
        long mask = Long.parseLong("00000000FFFFFFFF", 16);
        l = (l | (long) value) & mask;
        return l;
    }

    /**
     * Returns this instance's value as an int. Only use this method if you use the value returned as a bit field.
     * Because the Java int primitive type is always signed, a large numeric value for a DWORD will be treated as a
     * negative int.
     * <p>
     * @return The value of this instance as a potentially negative int.
     */
    @Override
    public Integer getValue() {
        LOGGER.debug("Retrieving signed int value :" + value);
        return value;
    }

    /**
     * Returns this instance's value as a byte array in the same order it would be stored in a GFF file.
     * <p>
     * @return The value of this instance as a bit field split into four bytes.
     */
    @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 DWordData}
     * rather than just {@code Object}.
     * <p>
     * @return A deep copy of this object.
     * @throws java.lang.CloneNotSupportedException
     */
    @Override
    public DWordData clone() throws CloneNotSupportedException {
        LOGGER.debug("Cloning object");
        DWordData clone = (DWordData) super.clone();
        clone.setValue(value);

        return new DWordData(value);
    }

    /**
     * Overrides the {@code java.lang.Object} method to make test for equality possible for this object.
     * <p>
     * @param compare The Object to compare this object with.
     * @return True if the objects have the same value, false if not.
     */
    @Override
    public boolean equals(Object compare) {
        if (compare == this) {
            return true;
        }

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

        DWordData dw = (DWordData) compare;
        return dw.getValueAsNumber().equals(this.getValueAsNumber());
    }

    /**
     * Overrides the {@code java.lang.Object} method to ensure we have a hash code consistent with the test for
     * equality.
     * <p>
     * @return The hash returned is based on the value.
     */
    @Override
    public int hashCode() {
        return value;
    }

    @Override
    public String toString() {
        String iS = Integer.toHexString(value);
        if (iS.length() < LENGTH * 2) {
            StringBuilder sb = new StringBuilder();
            sb.append(iS);
            for (int i = 0; i < (LENGTH * 2) - iS.length(); i++) {
                sb.append("0");
            }
            iS = sb.toString();
        }
        return iS;
    }
}