Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-10-26 09:34:35

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/StreamableContainer.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <ostream>
0010 
0011 namespace celeritas
0012 {
0013 //---------------------------------------------------------------------------//
0014 /*!
0015  * Helper class to print a contiguous range of data.
0016  *
0017  * Since this class is used by both \c Array and \c Span, it is templated
0018  * solely on the item type, and directly uses a non-owning pointer with a size.
0019  * \code
0020    std::cout << StreamableContainer{s.data(), s.size()} << std::endl;
0021    \endcode
0022  */
0023 template<class T>
0024 struct StreamableContainer
0025 {
0026     T const* data{};
0027     std::size_t size{};
0028 };
0029 
0030 //---------------------------------------------------------------------------//
0031 // Template deduction guides
0032 //---------------------------------------------------------------------------//
0033 
0034 template<class T>
0035 StreamableContainer(T const*, std::size_t) -> StreamableContainer<T>;
0036 
0037 //---------------------------------------------------------------------------//
0038 // FREE FUNCTIONS
0039 //---------------------------------------------------------------------------//
0040 /*!
0041  * Write a container to a stream.
0042  */
0043 template<class T>
0044 inline std::ostream& operator<<(std::ostream& os, StreamableContainer<T> sc)
0045 {
0046     std::streamsize size = static_cast<std::streamsize>(sc.size);
0047     std::streamsize width = os.width();
0048     std::streamsize remainder = 0;
0049 
0050     os.width(0);
0051     os << '{';
0052     if (width > 2 + (size - 1))
0053     {
0054         // Subtract width for spaces and braces
0055         width -= 2 + (size - 1);
0056         // Individual width is 1/N of that, rounded down, keep remainder
0057         // separate
0058         remainder = width % size;
0059         width = width / size;
0060     }
0061     else
0062     {
0063         width = 0;
0064     }
0065 
0066     // First element gets the remainder
0067     os.width(width + remainder);
0068     if (size > 0)
0069     {
0070         os << sc.data[0];
0071     }
0072 
0073     for (std::streamsize i = 1; i < size; ++i)
0074     {
0075         os << ',';
0076         os.width(width);
0077         os << sc.data[i];
0078     }
0079     os << '}';
0080 
0081     return os;
0082 }
0083 
0084 //---------------------------------------------------------------------------//
0085 }  // namespace celeritas