package info.knacki.pass.io;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.logging.Logger;

public class CharsetHelper {
    private static final Logger log = Logger.getLogger(CharsetHelper.class.getName());
    public final static String DEFAULT_CHARSET = "UTF-8";

    public static String ByteArrayToString(byte[] arr) {
        return ByteArrayToString(arr, 0, arr.length);
    }

    public static String ByteArrayToString(byte[] arr, int offset, int len) {
        try {
            return new String(arr, offset, Math.min(len, arr.length -offset), DEFAULT_CHARSET);
        }
        catch (UnsupportedEncodingException e) {
            log.severe("Unsupported charset " +DEFAULT_CHARSET);
        }
        return new String(arr, offset, Math.min(len, arr.length -offset), Charset.defaultCharset());
    }

    public static byte[] StringToByteArray(String str) {
        try {
            return str.getBytes(DEFAULT_CHARSET);
        }
        catch (UnsupportedEncodingException e) {
            log.severe("Unsupported charset " +DEFAULT_CHARSET);
        }
        return str.getBytes(Charset.defaultCharset());
    }
}
