/*
 * Created on 2004-08-19
 *
 * Part of the Symbian development plug-in for Eclipse
 * Copyright (C) Mikołaj Zalewski, 2004
 */
package pl.zalewski.mikolaj.symbdev.templates;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

/**
 * @author mikolaj
 *
 * Creates an InputStream from a Reader and a Charset
 */
public class InputStreamFromReader extends InputStream {

    Reader reader;
    Charset cs;
    ByteBuffer buf;
    
    public InputStreamFromReader(Reader reader, Charset charset) {
        super();
        this.reader=reader;
        this.cs=charset;
    }

    /* (non-Javadoc)
     * @see java.io.InputStream#read()
     */
    public int read() throws IOException {
        if (buf!=null)
        {
            byte ch;
            try {
                ch=buf.get();
                return ch;
            }
            catch (BufferUnderflowException e)
            {
                buf=null;
            }            
        }
        
        char[] cbuf=new char[128];
        int count=reader.read(cbuf);
        if (count==0 || count==-1) return -1;
        
        buf=cs.encode(new String(cbuf, 0, count));
        return read();
    }

}
