/*
 * Copyright 2008 nori090
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.coderepos.nori090.pcraw;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SocketChannel;

/**
 * @author nori090
 * @version $Rev: 138 $ $Date: 2008-08-01 06:28:28 +0900 (Fri, 01 Aug 2008) $
 */
public abstract class StreamIO {
    SocketChannel sock;

    int readInt()
        throws IOException {
        ByteBuffer bb = ByteBuffer.wrap( new byte[4] );
        bb.order( ByteOrder.LITTLE_ENDIAN );
        while ( bb.hasRemaining() ) {
            if ( sock.read( bb ) == -1 ) {
                throw new IOException( "end of stream!" );
            }
        }
        bb.rewind();
        return bb.getInt();
    }

    byte[] readExact( int size )
        throws IOException {
        ByteBuffer bb = ByteBuffer.wrap( new byte[size] );
        bb.order( ByteOrder.BIG_ENDIAN );
        while ( bb.hasRemaining() ) {
            if ( sock.read( bb ) == -1 ) {
                throw new IOException( "end of stream!" );
            }
        }
        bb.rewind();
        return bb.array();
    }

    void writeInt( int v )
        throws IOException {
        ByteBuffer bb = ByteBuffer.wrap( new byte[4] );
        bb.order( ByteOrder.LITTLE_ENDIAN );
        bb.putInt( v );
        bb.rewind();
        sock.write( bb );
    }

    void writeInt( short v )
        throws IOException {
        ByteBuffer bb = ByteBuffer.wrap( new byte[2] );
        bb.order( ByteOrder.LITTLE_ENDIAN );
        bb.putShort( v );
        bb.rewind();
        sock.write( bb );
    }

    void writeExact( byte[] bs )
        throws IOException {
        ByteBuffer bb = ByteBuffer.wrap( bs );
        bb.rewind();
        sock.write( bb );
    }

    char[] toChar( byte[] bs ) {
        char[] cs = new char[bs.length];
        for ( int i = 0; i < bs.length; i++ ) {
            cs[i] = (char) bs[i];
        }
        return cs;
    }

    byte[] toByte( char[] cs ) {
        byte[] bs = new byte[cs.length];
        for ( int i = 0; i < cs.length; i++ ) {
            bs[i] = (byte) cs[i];
        }
        return bs;
    }
}
