// This file is part of the Coral project.
// Please read the copyright notice in the LICENSE file.

#include "fdstreambuf.h"

#include <ext/stdio_filebuf.h>
#include <unistd.h>
#include <ios>

namespace coral {

	std::auto_ptr<std::streambuf> ofdstreambuf(int fd) {
		try {
#if __GNUC__ == 3 && __GNUC_MINOR__ < 4
			return std::auto_ptr<std::streambuf>(new __gnu_cxx::stdio_filebuf<char>(fd, std::ios_base::out, true, 4096));
#else
			return std::auto_ptr<std::streambuf>(new __gnu_cxx::stdio_filebuf<char>(fd, std::ios_base::out));
#endif
		} catch (...) {
			(void) close(fd);
			throw;
		}
	}

	std::auto_ptr<std::streambuf> ifdstreambuf(int fd) {
		try {
#if __GNUC__ == 3 && __GNUC_MINOR__ < 4
			return std::auto_ptr<std::streambuf>(new __gnu_cxx::stdio_filebuf<char>(fd, std::ios_base::in, true, 4096));
#else
			return std::auto_ptr<std::streambuf>(new __gnu_cxx::stdio_filebuf<char>(fd, std::ios_base::in));
#endif
		} catch (...) {
			(void) close(fd);
			throw;
		}
	}

	std::auto_ptr<std::streambuf> iofdstreambuf(int fd) {
		try {
#if __GNUC__ == 3 && __GNUC_MINOR__ < 4
			return std::auto_ptr<std::streambuf>(new __gnu_cxx::stdio_filebuf<char>(fd, std::ios_base::in | std::ios_base::out, true, 4096));
#else
			return std::auto_ptr<std::streambuf>(new __gnu_cxx::stdio_filebuf<char>(fd, std::ios_base::in | std::ios_base::out));
#endif
		} catch (...) {
			(void) close(fd);
			throw;
		}
	}

}
