raw_data.hpp 2.03 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4

#ifndef RTG_GUARD_RAW_DATA_HPP
#define RTG_GUARD_RAW_DATA_HPP

Paul's avatar
Paul committed
5
6
#include <rtg/tensor_view.hpp>

Paul's avatar
Paul committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
namespace rtg {

template<class Derived>
struct raw_data
{
    friend bool operator==(const Derived& x, const Derived& y)
    {
        auto&& xshape = x.get_shape();
        auto&& yshape = y.get_shape();
        bool result = x.empty() && y.empty();
        if(not result && xshape == yshape)
        {
            auto&& xbuffer = x.data();
            auto&& ybuffer = y.data();
            // TODO: Dont use tensor view for single values
            xshape.visit_type([&](auto as) {
                auto xview = make_view(xshape, as.from(xbuffer));
                auto yview = make_view(yshape, as.from(ybuffer));
                result = xview == yview;
            });
        }
        return result;
    }

    friend bool operator!=(const Derived& x, const Derived& y)
    {
        return !(x == y);
    }
Paul's avatar
Paul committed
35
36
37
38
39
40
41
42
43
    
    template<class Stream>
    friend Stream& operator<<(Stream& os, const Derived& d)
    {
        d.visit([&](auto x) {
            os << x;
        });
        return os;
    }
Paul's avatar
Paul committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

    template<class Visitor>
    void visit_at(Visitor v, std::size_t n=0) const
    {
        auto && s = static_cast<const Derived&>(*this).get_shape();
        auto && buffer = static_cast<const Derived&>(*this).data();
        s.visit_type([&](auto as) {
            v(*(as.from(buffer)+s.index(n)));
        });
    }

    template<class Visitor>
    void visit(Visitor v) const
    {
        auto && s = static_cast<const Derived&>(*this).get_shape();
        auto && buffer = static_cast<const Derived&>(*this).data();
        s.visit_type([&](auto as) {
Paul's avatar
Paul committed
61
            v(make_view(s, as.from(buffer)));
Paul's avatar
Paul committed
62
63
64
65
66
67
        });
    }

    bool single() const
    {
        auto && s = static_cast<const Derived&>(*this).get_shape();
Paul's avatar
Paul committed
68
        return s.elements() == 1;
Paul's avatar
Paul committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    }

    template<class T>
    T at(std::size_t n=0) const
    {
        T result;
        this->visit_at([&](auto x) {
            result = x;
        });
        return result;
    }
};

} // namespace rtg

#endif