
package uk.co.wingpath.modbus;

/**
* This class is used for assembling the data of a Modbus message.
*/

public class MessageBuilder
{
    private byte [] data;
    private int count;

    public MessageBuilder ()
    {
        data = new byte [500];
        count = 0;
    }

    /**
    * Gets the data.
    * @return a copy of the data array.
    */
    public byte [] getData ()
    {
        byte [] a = new byte [count];
        System.arraycopy (data, 0, a, 0, count);
        return a;
    }

    /**
    * Adds a byte of data to the end of the message.
    * @param b the data byte to be added.
    */
    public void addByte (int b)
    {
        if (count + 1 > data.length)
            increaseCapacity (1);
        data [count++] = (byte) b;
    }

    /**
    * Adds a 16-bit integer to the end of the message.
    * @param n the integer to be added.
    */
    public void addInt (int n)
    {
        if (count + 2 > data.length)
            increaseCapacity (2);
        data [count++] = (byte) (n >> 8);
        data [count++] = (byte) n;
    }

    /**
    * Adds a sub-array of data to the end of the message.
    * @param data array containing the data to be added.
    * @param offset start of data to be added.
    * @param len number of bytes to be added.
    */
    public void addData (byte [] data, int offset, int len)
    {
        if (count + len > this.data.length)
            increaseCapacity (len);
        System.arraycopy (data, offset, this.data, count, len);
        count += len;
    }

    /**
    * Adds an array of data to the end of the message.
    * @param data array containing the data to be added.
    */
    public void addData (byte [] data)
    {
        addData (data, 0, data.length);
    }

    private void increaseCapacity (int inc)
    {
        if (inc < 100)
            inc = 100;
        byte [] newData = new byte [data.length + inc];
        System.arraycopy (data, 0, newData, 0, count);
        data = newData;
    }
}

