libmoost
/home/mhx/git/github/libmoost/include/moost/container/memory_mapped_dataset/section_writer_base.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00028 #ifndef MOOST_CONTAINER_MEMORY_MAPPED_DATASET_SECTION_WRITER_BASE_HPP__
00029 #define MOOST_CONTAINER_MEMORY_MAPPED_DATASET_SECTION_WRITER_BASE_HPP__
00030 
00031 #include <string>
00032 #include <vector>
00033 #include <stdexcept>
00034 
00035 #include <boost/type_traits/is_pod.hpp>
00036 #include <boost/noncopyable.hpp>
00037 
00038 #include "dataset.hpp"
00039 
00040 namespace moost { namespace container {
00041 
00045 class mmd_section_writer_base : public boost::noncopyable
00046 {
00047 public:
00058    mmd_section_writer_base(memory_mapped_dataset::writer& wr, const std::string& name, const std::string& type, size_t alignment)
00059       : m_name(name)
00060       , m_wr(wr)
00061       , m_committed(false)
00062    {
00063       wr.create_section(name, type, alignment);
00064    }
00065 
00066    virtual ~mmd_section_writer_base()
00067    {
00068       try
00069       {
00070          commit();
00071       }
00072       catch (...)
00073       {
00074       }
00075    }
00076 
00087    void commit()
00088    {
00089       if (!m_committed)
00090       {
00091          pre_commit();
00092          m_wr.commit_section(m_name);
00093          m_committed = true;
00094       }
00095    }
00096 
00097 protected:
00098    void rollback()
00099    {
00100       m_wr.uncreate_section(m_name);
00101    }
00102 
00103    template <typename T>
00104    void setattr(const std::string& attr, const T& value)
00105    {
00106       m_wr.setattr(m_name, attr, value);
00107    }
00108 
00109    template <typename T>
00110    void write(const std::vector<T>& vec)
00111    {
00112       BOOST_STATIC_ASSERT_MSG(boost::is_pod<T>::value, "only POD types can be written to a dataset");
00113       write(reinterpret_cast<const char *>(&vec[0]), vec.size()*sizeof(T));
00114    }
00115 
00116    template <typename T>
00117    void write(const T& value)
00118    {
00119       BOOST_STATIC_ASSERT_MSG(boost::is_pod<T>::value, "only POD types can be written to a dataset");
00120       write(reinterpret_cast<const char *>(&value), sizeof(value));
00121    }
00122 
00123    void write(const std::string& value)
00124    {
00125       write(&value[0], value.size());
00126    }
00127 
00128    void write(const char *value, size_t size)
00129    {
00130       if (m_committed)
00131       {
00132          throw std::runtime_error("write access to committed section");
00133       }
00134       m_wr.write(m_name, value, size);
00135    }
00136 
00137    virtual void pre_commit()
00138    {
00139    }
00140 
00141 private:
00142    const std::string m_name;
00143    memory_mapped_dataset::writer& m_wr;
00144    bool m_committed;
00145 };
00146 
00147 }}
00148 
00149 #endif