/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.nio;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;

/**
 * Utility methods for working with the <code>ByteBuffer</code> class.
 *
 * @author Alex Leigh
 */
public class ByteBufferUtil {
    /**
     * Return a <code>byte[]</code> representing the contents of the given <code>ByteBuffer</code>. If the
     * <code>ByteBuffer</code> is read-only then the contents of the buffer will be copied into newly allocated space
     * . Otherwise, the <code>byte[]</code> backing the <code>ByteBuffer</code> is returned.
     *
     * @param buf
     * @return
     */
    public static byte[] array(ByteBuffer buf) {
        if (!buf.isReadOnly()) return buf.array();

        byte[] b = new byte[buf.remaining()];
        buf.rewind();
        buf.get(b);

        return b;
    }

    public static String getString(ByteBuffer b) {
        int i;
        while (b.hasRemaining()) {
            ByteBuffer nextString = b.slice(); // View on b with same start position
            //noinspection StatementWithEmptyBody
            for (i = 0; b.hasRemaining() && b.get() != 0x00; i++) {
                // Count to next NUL
            }
            nextString.limit(i); // view now stops before NUL
            CharBuffer s = StandardCharsets.UTF_8.decode(nextString);
            return s.toString();
        }
        return null;
    }
}