/* shm.hh - shared memory
 * Copyright 2007 Bas Wijnen <wijnen@debian.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef SHEVEK_SHM_HH
#define SHEVEK_SHM_HH

#include "refbase.hh"
#include "error.hh"
#include <string>
#include <typeinfo>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

namespace shevek
{
	/// This class implements an interface for sharing memory between processes.
	template <typename T> class shm : public refbase
	{
		shm (std::string const &name, bool l_create, bool writable, bool keep);
		~shm ();
		T *m_data;
		std::string m_name;
		int m_fd;
		bool m_destroy;
	public:
		/// Create a new block of shared memory.
		/** If keep is true, it will not be unlinked when the object is destroyed.
		 */
		static Glib::RefPtr <shm <T> > create (std::string const &name, bool keep = false) { return Glib::RefPtr <shm <T> > (new shm (name, true, true, keep)); }
		/// Open an existing block of shared memory.
		static Glib::RefPtr <shm <T> > open (std::string const &name, bool writable = true) { return Glib::RefPtr <shm <T> > (new shm (name, false, writable, true)); }
		/// Access the shared data.
		T *data () { return m_data; }
		/// Access the shared data.
		T const *data () const { return m_data; }
	};

	template <typename T> shm <T>::shm (std::string const &name, bool l_create, bool writable, bool keep)
	{
		m_destroy = !keep;
		m_name = std::string ("/") + typeid (T).name () + '-' + name;
		m_fd = shm_open (m_name.c_str (), l_create ? O_CREAT | O_EXCL | O_RDWR : writable ? O_RDWR : O_RDONLY, 0666);
		if (m_fd < 0)
		{
			shevek_error_errno ("unable to open shared memory file " + m_name);
			throw "unable to open shared memory file";
		}
		if (l_create && ftruncate (m_fd, sizeof (T)) < 0)
		{
			shevek_error_errno ("unable to set size of shared memory file " + m_name);
			throw "unable to set size of shared memory file";
		}
		m_data = reinterpret_cast <T *> (mmap (NULL, sizeof (T), writable ? PROT_READ | PROT_WRITE : PROT_READ, MAP_SHARED, m_fd, 0));
		if (!m_data)
		{
			shevek_error_errno ("unable to map shared memory file " + m_name);
			throw "unable to map shared memory";
		}
	}

	template <typename T> shm <T>::~shm ()
	{
		close (m_fd);
		munmap (m_data, sizeof (T));
		if (m_destroy)
			shm_unlink (m_name.c_str ());
	}
}

#endif
