Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-15 08:55:05

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file corecel/io/ScopedStreamRedirect.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <ostream>
0010 #include <sstream>
0011 #include <string>
0012 
0013 #include "corecel/Macros.hh"
0014 
0015 namespace celeritas
0016 {
0017 //---------------------------------------------------------------------------//
0018 /*!
0019  * Redirect the given stream to an internal stringstream.
0020  *
0021  * This is primarily for interfacing with poorly-behaved external libraries
0022  * that write to cout/cerr by default.
0023  *
0024  * \code
0025     ScopedStreamRedirect silenced(&std::cout);
0026     LoadVecGeom();
0027     CELER_LOG(diagnostic) << "Vecgeom said: " << silenced.str();
0028    \endcode
0029  *
0030  * The environment variable \c CELER_DISABLE_REDIRECT will prevent stream
0031  * redirection, which might be needed if the code segfaults/aborts before this
0032  * class's destructor is reached.
0033  */
0034 class ScopedStreamRedirect
0035 {
0036   public:
0037     // Whether stream redirection is enabled
0038     static bool allow_redirect();
0039 
0040     // Construct with pointer to a stream e.g. cout
0041     explicit ScopedStreamRedirect(std::ostream* os);
0042 
0043     // Restore stream on destruction
0044     ~ScopedStreamRedirect();
0045 
0046     //!@{
0047     //! Prevent copying and moving for RAII class
0048     CELER_DELETE_COPY_MOVE(ScopedStreamRedirect);
0049     //!@}
0050 
0051     // Get redirected output, with trailing whitespaces removed
0052     std::string str();
0053 
0054     // Get the raw stream after flushing the input
0055     std::stringstream& get();
0056 
0057   private:
0058     // >>> DATA
0059 
0060     // Holds a reference to the stream being redirected
0061     std::ostream* input_stream_;
0062 
0063     // Stores the redirected streams output buffer
0064     std::streambuf* input_buffer_{nullptr};
0065 
0066     // Holds an output buffer to share with the redirected stream
0067     std::stringstream temp_stream_;
0068 };
0069 
0070 //---------------------------------------------------------------------------//
0071 }  // namespace celeritas