/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.text;

import java.nio.ByteBuffer;
import net.ranides.assira.io.BufferAdapter;

/**
 *
 * @author ranides
 */
public final class FormatHex {
    
    private static final char[] HC_TABLE = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    private FormatHex() { }
    
    public static StringBuilder format(StringBuilder target, byte value) {
        int ivalue = value & 0xFF;
        target.append( HC_TABLE[ivalue >>> 4] );
        target.append( HC_TABLE[ivalue & 0xF] );
        return target;
    }
    
    public static StringBuilder format(StringBuilder target, byte[] raw) {
        boolean isFirst = true;
        for (byte b : raw) {
            if( !isFirst ) { 
                target.append(' '); 
            } else {
                isFirst = false;
            }
            format(target, b);
        }
        return target;
    }
    
    public static String format(byte value) {
        int ivalue = value & 0xFF;
        char[] out = new char[]{ HC_TABLE[ivalue >>> 4], HC_TABLE[ivalue & 0xF] };
        return new String(out);
    }
    
    public static String format(byte[] raw) {
        return format(new StringBuilder(3 * raw.length), raw).toString();
    }
    
    public static String format(ByteBuffer raw) {
        return format(BufferAdapter.toArray(raw));
    }

}
