1 // (C) Copyright 2005 Matthias Troyer
3 // Use, modification and distribution is subject to the Boost Software
4 // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
7 // Authors: Matthias Troyer
9 #ifndef BOOST_MPI_PACKED_OPRIMITIVE_HPP
10 #define BOOST_MPI_PACKED_OPRIMITIVE_HPP
12 #include <boost/mpi/config.hpp>
13 #include <cstddef> // size_t
14 #include <boost/config.hpp>
16 #include <boost/mpi/datatype.hpp>
17 #include <boost/mpi/exception.hpp>
18 #include <boost/serialization/detail/get_data.hpp>
19 #include <boost/serialization/array.hpp>
20 #include <boost/assert.hpp>
22 #include <boost/mpi/allocator.hpp>
24 namespace boost { namespace mpi {
26 /// serialization using MPI::Pack
28 class BOOST_MPI_DECL packed_oprimitive
31 /// the type of the buffer into which the data is packed upon serialization
32 typedef std::vector<char, allocator<char> > buffer_type;
34 packed_oprimitive(buffer_type & b, MPI_Comm const & comm)
40 void const * address() const
45 const std::size_t& size() const
47 return size_ = buffer_.size();
50 void save_binary(void const *address, std::size_t count)
52 save_impl(address,MPI_BYTE,count);
55 // fast saving of arrays
57 void save_array(serialization::array<T> const& x, unsigned int /* file_version */)
60 save_impl(x.address(), get_mpi_datatype(*x.address()), x.count());
63 typedef is_mpi_datatype<mpl::_1> use_array_optimization;
65 #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
66 friend class archive::save_access;
72 // default saving of primitives.
74 void save(const T & t)
76 save_impl(&t, get_mpi_datatype<T>(t), 1);
79 template<class CharType>
80 void save(const std::basic_string<CharType> &s)
82 unsigned int l = static_cast<unsigned int>(s.size());
85 save_impl(s.data(),get_mpi_datatype(CharType()),s.size());
90 void save_impl(void const * p, MPI_Datatype t, int l)
92 // allocate enough memory
94 BOOST_MPI_CHECK_RESULT(MPI_Pack_size,(l,t,comm,&memory_needed));
96 int position = buffer_.size();
97 buffer_.resize(position + memory_needed);
99 // pack the data into the buffer
100 BOOST_MPI_CHECK_RESULT(MPI_Pack,
101 (const_cast<void*>(p), l, t, boost::serialization::detail::get_data(buffer_), buffer_.size(), &position, comm));
102 // reduce the buffer size if needed
103 BOOST_ASSERT(std::size_t(position) <= buffer_.size());
104 if (std::size_t(position) < buffer_.size())
105 buffer_.resize(position);
108 buffer_type& buffer_;
109 mutable std::size_t size_;
113 } } // end namespace boost::mpi
115 #endif // BOOST_MPI_PACKED_OPRIMITIVE_HPP