/*
 * Copyright 2009 Yuichiro Moriguchi
 *
 * 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 net.morilib.lisp.nano.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Stack;

/**
 * An utility class for I/O.
 * <p>I/Oのためのユーティリティクラスである。
 * 
 * 
 * @author MORIGUCHI, Yuichiro 2010/04/18
 */
public final class IOs {

	private IOs() {}

	/**
	 * closes the given stream.
	 * <p>与えられたストリームをクローズする.
	 * 
	 * @param stream  the stream to be closed
	 */
	public static void close(InputStream stream) {
		if(stream != null) try {
			stream.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	//
	private static Stack<PrintStream> outstack =
		new Stack<PrintStream>(); 

	/**
	 * 
	 * @param ps
	 */
	public static void pushOut(PrintStream ps) {
		outstack.push(System.out);
		System.setOut(ps);
	}

	/**
	 * 
	 */
	public static PrintStream popOut() {
		PrintStream r = outstack.pop();

		System.setOut(r);
		return r;
	}

	//
	private static Stack<InputStream> instack =
		new Stack<InputStream>(); 

	/**
	 * 
	 * @param ps
	 */
	public static void pushIn(InputStream ps) {
		instack.push(System.in);
		System.setIn(ps);
	}

	/**
	 * 
	 */
	public static InputStream popIn() {
		InputStream r = instack.pop();

		System.setIn(r);
		return r;
	}

}
