streamutils.hpp 1.2 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>
Paul's avatar
Paul committed
7

Paul's avatar
Paul committed
8
namespace migraph {
Paul's avatar
Paul committed
9

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

    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
22
23
            std::for_each(
                std::next(sr.r->begin()), sr.r->end(), [&](auto&& x) { os << ", " << x; });
Paul's avatar
Paul committed
24
25
26
27
28
29
30
31
32
33
34
        }
        return os;
    }
};

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

Paul's avatar
Paul committed
35
36
namespace detail {

Paul's avatar
Paul committed
37
38
39
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
40
41
42
43
{
    os << stream_range(r);
}

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

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

Paul's avatar
Paul committed
57
} // namespace migraph
Paul's avatar
Paul committed
58
59

#endif