/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.media.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * This class implements methods for creating an input or output stream on a ByteBuffer.
 *
 * <p>Obtain or create a ByteBuffer:
 * <pre>ByteBuffer buf = ByteBuffer.allocate(10);</pre>
 *
 * <p>Create an output stream on the ByteBuffer:
 * <pre>OutputStream os = newOutputStream(buf);</pre>
 *
 * <p>Create an input stream on the ByteBuffer:
 * <pre>InputStream is = newInputStream(buf);</pre>
 *
 * @version <tt>$Revision: 1.1 $</tt>
 * @author <a href="mailto:ricardoarguello@users.sourceforge.net">Ricardo Argüello</a>
 */
public class ByteBufferUtils
{
   /**
    * Returns an output stream for a ByteBuffer.
    * The write() methods use the relative ByteBuffer put() methods.
    */
   public static OutputStream newOutputStream(final ByteBuffer buf)
   {
      return new OutputStream()
      {
         public synchronized void write(int b) throws IOException
         {
            buf.put((byte) b);
         }

         public synchronized void write(byte[] bytes, int off, int len)
            throws IOException
         {
            buf.put(bytes, off, len);
         }
      };
   }

   /**
    * Returns an input stream for a ByteBuffer.
    * The read() methods use the relative ByteBuffer get() methods.
    */
   public static InputStream newInputStream(final ByteBuffer buf)
   {
      return new InputStream()
      {
         public synchronized int read() throws IOException
         {
            if (!buf.hasRemaining())
            {
               return -1;
            }
            return buf.get();
         }

         public synchronized int read(byte[] bytes, int off, int len)
            throws IOException
         {
            // Read only what's left
            len = Math.min(len, buf.remaining());
            buf.get(bytes, off, len);
            return len;
         }
      };
   }
}
