literal.hpp 2.24 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
#ifndef GUARD_RTGLIB_LITERAL_HPP
#define GUARD_RTGLIB_LITERAL_HPP

#include <rtg/shape.hpp>
Paul's avatar
Paul committed
5
#include <rtg/argument.hpp>
Paul's avatar
Paul committed
6
7
8
9
10

namespace rtg {

struct literal 
{
Paul's avatar
Paul committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    literal()
    : buffer(), shape_()
    {}

    template<class T>
    literal(T x) 
    : buffer(sizeof(T), 0), shape_(shape::get_type<T>{})
    {
        static_assert(std::is_trivial<T>{}, "Literals can only be trivial types");
        *(reinterpret_cast<T*>(buffer.data())) = x;
    }

    template<class T>
    literal(shape s, const std::vector<T>& x) 
    : buffer(s.bytes(), 0), shape_(s)
    {
        static_assert(std::is_trivial<T>{}, "Literals can only be trivial types");
        std::copy(x.begin(), x.end(), reinterpret_cast<T*>(buffer.data()));
    }
Paul's avatar
Paul committed
30
31
32
33
    
    literal(shape s, const char* x)
    : buffer(x, x+s.bytes()), shape_(s)
    {}
Paul's avatar
Paul committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

    friend bool operator==(const literal& x, const literal& y)
    {
        bool result = x.buffer.empty() && y.buffer.empty();
        if(not result && x.shape_ == y.shape_ and x.buffer.size() == y.buffer.size())
        {
            x.shape_.visit_type([&](auto as) {
                auto space = x.shape_.bytes() / sizeof(as());
                auto * xstart = &as.from(x.buffer.data());
                auto * ystart = &as.from(y.buffer.data());
                result = std::equal(xstart, xstart+space, ystart, ystart+space);

            });
        }
        return result;
    }

    friend bool operator!=(const literal& x, const literal& y)
    {
        return !(x == y);
    }

    template<class Visitor>
    void visit(Visitor v, std::size_t n=0) const
    {
        shape_.visit_type([&](auto as) {
            v(as.from(this->buffer.data(), n));
        });
    }

    bool empty() const
    {
        return this->buffer.empty();
    }

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

    const shape& get_shape() const
    {
        return this->shape_;
    }

Paul's avatar
Paul committed
84
85
86
87
88
89
90
91
92
    argument get_argument() const
    {
        argument arg;
        auto b = buffer;
        arg.s = shape_;
        arg.data = [b]() mutable { return b.data(); };
        return arg;
    }

Paul's avatar
Paul committed
93
private:
Paul's avatar
Paul committed
94
95
96
97
98
99
100
    std::vector<char> buffer;
    shape shape_;
};

}

#endif