SendBuffer.h 26.8 KB
Newer Older
1 2
//======================================================================================================================
//
3
//  This file is part of waLBerla. waLBerla is free software: you can
4
//  redistribute it and/or modify it under the terms of the GNU General Public
5
//  License as published by the Free Software Foundation, either version 3 of
6
//  the License, or (at your option) any later version.
7 8 9 10
//
//  waLBerla 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
11
//  for more details.
12
//
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
//  You should have received a copy of the GNU General Public License along
//  with waLBerla (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>.
//
//! \file SendBuffer.h
//! \ingroup core
//! \author Klaus Iglberger
//! \brief Implementation of a MPI send buffer.
//!
//! Copyright (C) 2009 Klaus Iglberger
//! Taken from "pe Physics Engine" with small changes
//
//======================================================================================================================

#pragma once

#include "waLBerlaDefinitions.h"
#include "BufferSizeTrait.h"
#include "growPolicies/ConstantGrowth.h"
#include "growPolicies/LinearGrowth.h"
#include "growPolicies/OptimalGrowth.h"

#include "core/debug/Debug.h"
35
#include "core/Sanitizer.h"
36 37 38 39

#include <boost/mpl/logical.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
40
#include <boost/type_traits/is_fundamental.hpp>
41 42 43 44
#include <boost/utility/enable_if.hpp>

#include <algorithm>
#include <typeinfo>
45
#include <cstring>
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

namespace walberla {
namespace mpi {

//======================================================================================================================
//
//  CLASS DEFINITION
//
//======================================================================================================================

//**********************************************************************************************************************
/*!\brief Implementation of a MPI send buffer.
// \ingroup mpi
//
// The SendBuffer class is a special purpose implementation for the MPI communication
// functionality. It offers a convenient and safe setup of MPI messages even for mixed-type
// communication. The following example gives an impression of the usage of the SendBuffer
// class:

   \code
   using namespace mpi;

   // Adding a double and an integer to a send buffer
   SendBuffer buffer;
   double d( 2.1 );
   Vec3 v( 3.5, -2.1, 0.7 );
   buffer << d << v;

   // Sending a MPI message to process 0 with the contents of the send buffer
   MPI_Send( buffer.ptr(), buffer.size(), MPI_BYTE, 0, 0, MPI_COMM_WORLD );
   \endcode
// For another example see also the Buffer Unit Test in File BufferTest.cpp
//
// Note that the order of data values in the send buffer is depending on the order the
// elements are added to the buffer. This order is not changed during the MPI communication
// and the same order has to be used during the extraction of the sent data elements. See
// also the RecvBuffer class description for the receiver side of the MPI communication.
*/
template< typename T = unsigned char    // Element type
85
          , typename G = OptimalGrowth >  // Growth policy
86 87 88
class GenericSendBuffer
{
public:
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

   template <typename VT>
   class Ptr
   {
   public:
      static_assert( boost::is_fundamental<VT>::value, "only fundamental data types are allowed");
      typedef VT value_type;

      Ptr(GenericSendBuffer<T, G>& buffer, const std::ptrdiff_t offset, const size_t length)
         : buffer_(buffer), offset_(offset), length_(length) {}

      inline VT& operator*();
      inline VT* operator->();
      inline VT& operator[](const size_t& rhs);
   private:
      GenericSendBuffer<T, G>& buffer_;
      const std::ptrdiff_t     offset_;
      const size_t             length_;
   };

109 110 111 112 113 114 115 116
   //**Type definitions*************************************************************************************************
   typedef T  ElementType;  //!< Type of the receive buffer elements.
   //*******************************************************************************************************************

   //**Constructors*****************************************************************************************************
   /*!\name Constructors */
   //@{
   explicit inline GenericSendBuffer( size_t initCapacity = 0 );
117
   inline GenericSendBuffer( const GenericSendBuffer& sb );
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
   //@}
   //*******************************************************************************************************************

   //**Destructor*******************************************************************************************************
   /*!\name Destructor */
   //@{
   inline ~GenericSendBuffer();
   //@}
   //*******************************************************************************************************************

   //**Assignment operator**********************************************************************************************
   /*!\name Assignment operator */
   //@{
   GenericSendBuffer& operator=( const GenericSendBuffer& sb );
   //@}
   //*******************************************************************************************************************

   //**Get functions****************************************************************************************************
   /*!\name Get functions */
   //@{
   inline size_t maxSize () const;
   inline size_t size    () const;
   inline size_t capacity() const;
   inline bool   isEmpty () const;
   //@}
   //*******************************************************************************************************************

   //**Operators********************************************************************************************************
   /*!\name Operators */
   //@{
   template< typename V >
   typename boost::enable_if< boost::mpl::or_< boost::is_arithmetic<V>, boost::is_enum<V> >,
150
   GenericSendBuffer&  >::type
151 152 153 154 155 156 157
   operator<<( V value );

   //@}
   //*******************************************************************************************************************

   //**Repositioning ***************************************************************************************************
   /*!\name Repositioning */
158
   inline T *  forward( uint_t elements );
159 160 161 162 163 164 165
   inline void rewind(const size_t & size);
   //@}
   //*******************************************************************************************************************

   //**Utility functions************************************************************************************************
   /*!\name Utility functions */
   //@{
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
   /**
    * Returns a special pointer class to modify the allocated memory location later.
    *
    * Example:
    * \snippet BufferTest.cpp SendBuffer Overwrite Test
    * The buffer now contains 1, 3, 2, 3
    */
   template <typename VT>
   inline
   Ptr<VT> allocate( const size_t length = 1, const VT& v = VT() )
   {
      auto tmp = typename GenericSendBuffer<T,G>::template Ptr<VT>(*this, getOffset(), length);
      for (size_t i = 0; i < length; ++i)
         *this << v;
      return tmp;
   }
182 183 184 185 186
   inline T*             ptr    () const;
   inline void           reserve( size_t newCapacity );
   inline void           clear  ();
   inline void           reset  ();
   inline void           addDebugMarker( const char * marker );
187 188 189 190 191 192 193 194 195 196 197
   //@}
   //*******************************************************************************************************************

private:
   //**Utility functions************************************************************************************************
   /*!\name Utility functions */
   //@{
   void extendMemory( size_t newCapacity );

   template< typename V >
   typename boost::enable_if< boost::mpl::or_< boost::is_arithmetic<V>, boost::is_enum<V> >,
198
   GenericSendBuffer&  >::type
199
   put( V value );
200 201 202

   inline std::ptrdiff_t getOffset() const;
   inline T*             getMemoryLocation( const std::ptrdiff_t offset);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
   //@}
   //*******************************************************************************************************************

   //**Member variables*************************************************************************************************
   /*!\name Member variables */
   //@{
   T* begin_;  //!< Pointer to the first element of the send buffer.
   T* cur_;    //!< Pointer to the current/last element of the send buffer.
   T* end_;    //!< Pointer to the end of the storage of the send buffer.
   //@}
   //*******************************************************************************************************************

   //**Compile time checks**********************************************************************************************
   static_assert( boost::is_arithmetic<T>::value, "SendBuffer<T>: T has to be native datatype" ) ;
   //*******************************************************************************************************************

   template< typename U >
   friend class GenericRecvBuffer;
};
//**********************************************************************************************************************

typedef GenericSendBuffer<> SendBuffer;


227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
//======================================================================================================================
//
//  GenericSendBuffer<T,G>::Ptr<VT>
//
//======================================================================================================================

template< typename T    // Element type
          , typename G >  // Growth policy
template <typename VT>
inline
VT& GenericSendBuffer<T,G>::Ptr<VT>::operator*()
{
   return *operator->();
}

template< typename T    // Element type
          , typename G >  // Growth policy
template <typename VT>
inline
VT* GenericSendBuffer<T,G>::Ptr<VT>::operator->()
{
   return reinterpret_cast<value_type*>( buffer_.getMemoryLocation( offset_ + static_cast<std::ptrdiff_t>(BUFFER_DEBUG_OVERHEAD) ) );
}

template< typename T    // Element type
          , typename G >  // Growth policy
template <typename VT>
inline
VT& GenericSendBuffer<T,G>::Ptr<VT>::operator[](const size_t& rhs)
{
   WALBERLA_ASSERT_LESS(rhs, length_, "out of bounds access!");
   return *reinterpret_cast<value_type*>(
            buffer_.getMemoryLocation(
               offset_ +
261
               static_cast<std::ptrdiff_t>( rhs * ( BUFFER_DEBUG_OVERHEAD + sizeof(VT) ) + BUFFER_DEBUG_OVERHEAD )
262 263 264 265
               )
            );
}

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

//======================================================================================================================
//
//  CONSTRUCTORS
//
//======================================================================================================================

//**********************************************************************************************************************
/*!\brief Standard constructor for SendBuffer.
//
// \param initCapacity The initial capacity of the send buffer.
//
// The default initial capacity of the send buffer is specified by the selected growth policy.
*/
template< typename T    // Element type
281
          , typename G >  // Growth policy
282 283 284 285 286 287 288 289 290 291 292 293 294 295
inline GenericSendBuffer<T,G>::GenericSendBuffer( size_t initCapacity )
   : begin_( new T[initCapacity] )  // Pointer to the first element
   , cur_  ( begin_ )               // Pointer to the current/last element
   , end_  ( begin_ )               // Pointer to the end of the storage
{}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Copy constructor for SendBuffer.
//
// \param sb The send buffer to be copied.
*/
template< typename T    // Element type
296
          , typename G >  // Growth policy
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
inline GenericSendBuffer<T,G>::GenericSendBuffer( const GenericSendBuffer& sb )
   : begin_( new T[sb.size()] )  // Pointer to the first element
   , cur_  ( begin_+sb.size() )  // Pointer to the current/last element
   , end_  ( cur_ )              // Pointer to the end of the storage
{
   for( size_t i=0; i<sb.size(); ++i )
      begin_[i] = sb.begin_[i];
}
//**********************************************************************************************************************




//======================================================================================================================
//
//  DESTRUCTOR
//
//======================================================================================================================

//**********************************************************************************************************************
/*!\brief Destructor for SendBuffer.
*/
template< typename T    // Element type
320
          , typename G >  // Growth policy
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
inline GenericSendBuffer<T,G>::~GenericSendBuffer()
{
   delete [] begin_;
}
//**********************************************************************************************************************




//======================================================================================================================
//
//  ASSIGNMENT OPERATOR
//
//======================================================================================================================

//**********************************************************************************************************************
/*!\brief Copy assignment operator for SendBuffer.
//
// \param sb The send buffer to be copied.
// \return Reference to the assigned send buffer.
*/
template< typename T    // Element type
343
          , typename G >  // Growth policy
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
GenericSendBuffer<T,G>& GenericSendBuffer<T,G>::operator=( const GenericSendBuffer& sb )
{
   if( &sb == this ) return *this;

   if( sb.size() > capacity() ) {
      T* newBegin( new T[sb.size()] );
      end_ = std::copy( sb.begin_, sb.cur_, newBegin );
      std::swap( begin_, newBegin );
      delete [] newBegin;

      cur_ = end_;
   }
   else {
      cur_ = std::copy( sb.begin_, sb.end_, begin_ );
   }

   return *this;
}
//**********************************************************************************************************************




//======================================================================================================================
//
//  GET FUNCTIONS
//
//======================================================================================================================

//**********************************************************************************************************************
/*!\brief Returns the maximum possible size of the send buffer.
//
// \return The maximum possible size.
*/
template< typename T    // Element type
379
          , typename G >  // Growth policy
380 381 382 383 384 385 386 387 388 389 390 391 392
inline size_t GenericSendBuffer<T,G>::maxSize() const
{
   return size_t(-1) / sizeof(T);
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Returns the current size of the send buffer.
//
// \return The current size.
*/
template< typename T    // Element type
393
          , typename G >  // Growth policy
394 395 396 397 398 399 400 401 402 403 404 405 406
inline size_t GenericSendBuffer<T,G>::size() const
{
   return numeric_cast< size_t >( cur_ - begin_ );
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Returns the capacity of the send buffer.
//
// \return The capacity.
*/
template< typename T    // Element type
407
          , typename G >  // Growth policy
408 409 410 411 412 413 414 415 416 417 418 419 420
inline size_t GenericSendBuffer<T,G>::capacity() const
{
   return numeric_cast< size_t >( end_ - begin_ );
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Returns \a true if the send buffer is empty.
//
// \return \a true if the send buffer is empty, \a false if it is not.
*/
template< typename T    // Element type
421
          , typename G >  // Growth policy
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
inline bool GenericSendBuffer<T,G>::isEmpty() const
{
   return begin_ == cur_;
}
//**********************************************************************************************************************




//======================================================================================================================
//
//  OPERATORS
//
//======================================================================================================================

//**********************************************************************************************************************
/*!\brief Implements operator<< without debugging system
//
// \return Reference to the send buffer.
//
*/
template< typename T    // Element type
444
          , typename G >  // Growth policy
445 446
template< typename V >  // Type of the built-in data value
typename boost::enable_if< boost::mpl::or_< boost::is_arithmetic<V>, boost::is_enum<V> >,
447
GenericSendBuffer<T,G>& >::type
448 449 450 451
GenericSendBuffer<T,G>::put( V value )
{
   // Compile time check that V is built-in data type
   static_assert( boost::is_arithmetic<V>::value || boost::is_enum<V>::value,
452
                  "SendBuffer accepts only built-in data types");
453 454 455 456 457 458 459 460 461 462 463 464 465

   static_assert( sizeof(V) >= sizeof(T), "Type that is stored has to be bigger than T" );
   static_assert( sizeof(V)  % sizeof(T) == 0, "V has to be divisible by T ");

   size_t count =  sizeof(V) / sizeof(T) ;
   const size_t rest = numeric_cast< size_t >( end_ - cur_ );

   // Checking the size of the remaining memory
   if( rest < count ) {
      extendMemory( size() + count );
   }

   // Adding the data value
466
   std::memcpy( cur_, &value, sizeof(V) );
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
   cur_ += count;

   // Invariants check
   WALBERLA_ASSERT_LESS_EQUAL( cur_, end_ );

   return *this;
}
//**********************************************************************************************************************



//**********************************************************************************************************************
/*!\brief Adds a built-in data value to the send buffer.
//
// \return Reference to the send buffer.
//
// This function adds one data value of built-in data type to the send buffer.
//
// \b Note: This operator may only be used for built-in data types. The attempt to use
// a user-defined data type results in a compile time error!
*/
template< typename T    // Element type
489
          , typename G >  // Growth policy
490 491
template< typename V >  // Type of the built-in data value
typename boost::enable_if< boost::mpl::or_< boost::is_arithmetic<V>, boost::is_enum<V> >,
492
GenericSendBuffer<T,G>& >::type
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
GenericSendBuffer<T,G>::operator<<( V value )
{
   addDebugMarker( typeid(V).name() );
   return put( value );
}
//**********************************************************************************************************************







//======================================================================================================================
//
//  REPOSITIONING
//
//======================================================================================================================

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
//**********************************************************************************************************************
/*!\brief Forward the given number of elements.
//
// \param elements The number of elements to be advanced.
// \return Previous position.
//
// This function forwards \a element send buffer elements of type \a T and returns the previous buffer position.
*/
template< typename T    // Element type
        , typename G >  // Growth policy
T * GenericSendBuffer<T,G>::forward( uint_t elements )
{
   const size_t rest = numeric_cast< size_t >( end_ - cur_ );

   // Checking the size of the remaining memory
   if( rest < elements ) {
      extendMemory( size() + elements );
   }

   // Adding the data value
   auto previous = cur_;
   cur_ += elements;

   // Invariants check
   WALBERLA_ASSERT_LESS_EQUAL( cur_, end_ );

   return previous;
}

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
//**********************************************************************************************************************
/*!\brief Rewinds the stream to a previous position
//
   \code
   // Filling a send buffer with a double and an integer value
   SendBuffer<byte> buffer;
   double d =  2.1;
   buffer << d;
   size_t memorizedSize = buffer.size();
   int i=3;
   buffer << i;
   buffer.rewind(memorizedSize);
   i=5;
   buffer << i; //overwrites the 3 in the buffer with the new value 5
   \endcode
*/
template< typename T    // Element type
558
          , typename G >  // Growth policy
559 560 561 562 563 564 565 566 567 568 569 570 571 572
inline void GenericSendBuffer<T,G>::rewind(const size_t & s)
{
   WALBERLA_ASSERT_LESS(s, size());
   cur_ = begin_ + s;
   WALBERLA_ASSERT_EQUAL(size(), s);
}


//======================================================================================================================
//
//  UTILITY FUNCTIONS
//
//======================================================================================================================

573

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
//**********************************************************************************************************************
/*!\brief Returns a pointer to the first element of the send buffer.
//
// \return Pointer to the first element of the send buffer.
//
// This utility function enables the SendBuffer to be used directly as send buffer in MPI
// send functions:

   \code
   using namespace communication;

   // Filling a send buffer with a double and an integer value
   SendBuffer<byte> buffer;
   double d =  2.1;
   int i= 2;
   buffer << d << i;

   // Sending a MPI message to process 0 with the contents of the send buffer
   MPI_Send( buffer.ptr(), buffer.size(), MPI_BYTE, 0, 0, MPI_COMM_WORLD );
   \endcode
*/
template< typename T    // Element type
596
          , typename G >  // Growth policy
597 598 599 600 601 602
inline T* GenericSendBuffer<T,G>::ptr() const
{
   return begin_;
}
//**********************************************************************************************************************

603 604 605 606 607 608 609
/**
 * Returns the offset from the beginning to the current position inside the buffer in bytes.
 *
 * \attention This is a low level function. Use with care!
 * \see getMemoryLocation()
 */
template< typename T    // Element type
610
          , typename G >  // Growth policy
611 612 613 614 615 616 617 618 619 620 621 622 623
inline std::ptrdiff_t GenericSendBuffer<T,G>::getOffset() const
{
   return cur_ - begin_;
}


/**
 * Returns the memory address corresponding to the offset. Offset is measured in bytes from the beginning of the buffer.
 *
 * \attention This is a low level function. Use with care!
 * \see getOffset()
 */
template< typename T    // Element type
624
          , typename G >  // Growth policy
625 626 627 628 629
inline T*   GenericSendBuffer<T,G>::getMemoryLocation( const std::ptrdiff_t offset)
{
   return begin_ + offset;
}

630 631 632 633 634 635 636 637 638 639 640

//**********************************************************************************************************************
/*!\brief Setting the minimum capacity of the send buffer.
//
// \param newCapacity The new minimum capacity of the send buffer.
// \return void
//
// This function reserves at least \a newCapacity elements of data type \a T for the send
// buffer.
*/
template< typename T    // Element type
641
          , typename G >  // Growth policy
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
inline void GenericSendBuffer<T,G>::reserve( size_t newCapacity )
{
   if( newCapacity > capacity() )
      extendMemory( newCapacity );
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Extending the internal memory of the send buffer.
//
// \param newCapacity The new minimum capacity of the send buffer.
// \return void
*/
template< typename T    // Element type
657
          , typename G >  // Growth policy
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
void GenericSendBuffer<T,G>::extendMemory( size_t newCapacity )
{
   // Calculating the new capacity
   WALBERLA_ASSERT_GREATER( newCapacity, capacity() );
   newCapacity = G()( capacity(), newCapacity );
   WALBERLA_ASSERT_GREATER( newCapacity, capacity() );

   // Allocating a new array
   T* tmp = new T[newCapacity];

   // Replacing the old array
   cur_ = std::copy( begin_, cur_, tmp );
   std::swap( tmp, begin_ );
   end_ = begin_ + newCapacity;
   delete [] tmp;
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Clearing the send buffer.
//
// \return void
//
// This function performs a complete reset of the send buffer.
*/
template< typename T    // Element type
685
          , typename G >  // Growth policy
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
inline void GenericSendBuffer<T,G>::clear()
{
   cur_ = begin_;
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Clearing the send buffer.
//
// \return void
//
// This function performs a complete reset of the send buffer - including the deletion of allocated memory!
*/
template< typename T    // Element type
701
          , typename G >  // Growth policy
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
inline void GenericSendBuffer<T,G>::reset()
{
   delete [] begin_;
   begin_ = new T[0];
   cur_ = begin_;
   end_ = begin_;
}
//**********************************************************************************************************************


//**********************************************************************************************************************
/*!\brief Adds a debug marker if buffer debugging is enabled
//
// See corresponding function GenericRecvBuffer::readDebugMarker()
*/
#ifdef WALBERLA_BUFFER_DEBUG

template< typename T    // Element type
720
          , typename G >  // Growth policy
721 722 723 724 725 726 727 728 729 730 731 732 733
inline void GenericSendBuffer<T,G>::addDebugMarker( const char * marker )
{
   uint_t len = std::strlen( marker );
   // Push the first BUFFER_DEBUG_OVERHEAD chars of the marker
   for( uint_t i = 0; i < len && i < BUFFER_DEBUG_OVERHEAD; ++i )
      put( T( marker[i] ) );
   // If marker was shorter then BUFFER_DEBUG_OVERHEAD fill the rest with '-'
   // to always have the same length
   for( uint_t i = len; i < BUFFER_DEBUG_OVERHEAD; ++i )
      put( T( '-' ) );
}
#else
template< typename T    // Element type
734
          , typename G >  // Growth policy
735 736 737 738 739 740 741 742 743 744
inline void GenericSendBuffer<T,G>::addDebugMarker( const char *  )
{}
#endif

//**********************************************************************************************************************



} // namespace mpi
} // namespace walberla