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