#pragma once

#include <unistd.h>

namespace util {

	/// A wrapper over a file descriptor which
	/// cleanly manages the lifetime of it.
	class UniqueFd {
		int fd;
	public:
		explicit UniqueFd(int fd) {
			reset(fd);
		}

		~UniqueFd() {
			reset();
		}

		UniqueFd(const UniqueFd&) = delete;
		UniqueFd(UniqueFd&& mv) {
			fd = mv.fd;
			mv.fd = -1;
		}

		int get() const { return fd; }

		operator bool() const {
			return fd != -1;
		}

		void reset(int newFd = -1) {
			if(fd != -1)
				close(fd);
			fd = newFd;
		}

	};

}
