streamutils.hpp 1.31 KB
Newer Older
Paul's avatar
Paul committed
1
2
#ifndef MIGRAPH_GUARD_STREAMUTILS_HPP
#define MIGRAPH_GUARD_STREAMUTILS_HPP
Paul's avatar
Paul committed
3
4
5

#include <ostream>
#include <algorithm>
Paul's avatar
Paul committed
6
#include <migraph/rank.hpp>
7
#include <migraph/config.hpp>
Paul's avatar
Paul committed
8

9
namespace migraph { inline namespace MIGRAPH_INLINE_NS {
Paul's avatar
Paul committed
10

Paul's avatar
Paul committed
11
template <class T>
Paul's avatar
Paul committed
12
13
14
struct stream_range_container
{
    const T* r;
Paul's avatar
Paul committed
15
    stream_range_container(const T& x) : r(&x) {}
Paul's avatar
Paul committed
16
17
18
19
20
21
22

    friend std::ostream& operator<<(std::ostream& os, const stream_range_container& sr)
    {
        assert(sr.r != nullptr);
        if(!sr.r->empty())
        {
            os << sr.r->front();
Paul's avatar
Paul committed
23
24
            std::for_each(
                std::next(sr.r->begin()), sr.r->end(), [&](auto&& x) { os << ", " << x; });
Paul's avatar
Paul committed
25
26
27
28
29
30
31
32
33
34
35
        }
        return os;
    }
};

template <class Range>
inline stream_range_container<Range> stream_range(const Range& r)
{
    return {r};
}

Paul's avatar
Paul committed
36
37
namespace detail {

Paul's avatar
Paul committed
38
39
40
template <class Range>
auto stream_write_value_impl(rank<1>, std::ostream& os, const Range& r)
    -> decltype(r.begin(), r.end(), void())
Paul's avatar
Paul committed
41
42
43
44
{
    os << stream_range(r);
}

Paul's avatar
Paul committed
45
template <class T>
Paul's avatar
Paul committed
46
47
48
49
50
51
void stream_write_value_impl(rank<0>, std::ostream& os, const T& x)
{
    os << x;
}
} // namespace detail

Paul's avatar
Paul committed
52
template <class T>
Paul's avatar
Paul committed
53
54
55
56
57
void stream_write_value(std::ostream& os, const T& x)
{
    detail::stream_write_value_impl(rank<1>{}, os, x);
}

58
} // inline namespace MIGRAPH_INLINE_NS
Paul's avatar
Paul committed
59
} // namespace migraph
Paul's avatar
Paul committed
60
61

#endif