package com.atlassian.bitbucket.mesh.io;

import javax.annotation.Nonnull;
import java.nio.ByteBuffer;

import static java.util.Objects.requireNonNull;

public class ByteUtils {

    private ByteUtils() {
        throw new UnsupportedOperationException("Do not instantiate");
    }

    /**
     * Copies data from the {@code src} buffer into the {@code dst}, and returns whether all data
     * was copied (as a convenience; the caller could also check {@code src.hasRemaining()}).
     *
     * @param src the source buffer
     * @param dst the destination buffer
     * @return {@code true} if the {@code src} buffer was copied in full; otherwise, {@code false}
     *         if the {@code dst} buffer could not hold all the data
     */
    public static boolean copy(@Nonnull ByteBuffer src, @Nonnull ByteBuffer dst) {
        requireNonNull(src, "src");
        requireNonNull(dst, "dst");
        int available = dst.remaining();
        if (src.remaining() > available) {
            //The source has more data than we can fit in the destination's available space,
            //so slice off what we can and put that, then advance the position
            ByteBuffer slice = src.slice();
            slice.limit(available);
            dst.put(slice);

            src.position(src.position() + available);

            return false;
        }

        //The full source will fit in the destination
        dst.put(src);

        return true;
    }
}
