streamutils.hpp 1.3 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
10
namespace migraph {
inline namespace MIGRAPH_INLINE_NS {
Paul's avatar
Paul committed
11

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

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

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

Paul's avatar
Paul committed
37
38
namespace detail {

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

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

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

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

#endif