literal.hpp 1.63 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
#include <rtg/tensor_view.hpp>
Paul's avatar
Paul committed
7
#include <rtg/raw_data.hpp>
Paul's avatar
Paul committed
8
9
10

namespace rtg {

Paul's avatar
Paul committed
11
struct literal : raw_data<literal>
Paul's avatar
Paul committed
12
{
Paul's avatar
Paul committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    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)
    {
Paul's avatar
Paul committed
29
30
31
32
33
34
35
36
37
38
        assert(s.packed());
        static_assert(std::is_trivial<T>{}, "Literals can only be trivial types");
        std::copy(x.begin(), x.end(), reinterpret_cast<T*>(buffer.data()));
    }

    template<class T>
    literal(shape s, const std::initializer_list<T>& x) 
    : buffer(s.bytes(), 0), shape_(s)
    {
        assert(s.packed());
Paul's avatar
Paul committed
39
40
41
        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
42
43
44
45
    
    literal(shape s, const char* x)
    : buffer(x, x+s.bytes()), shape_(s)
    {}
Paul's avatar
Paul committed
46
47
48
49
50
51

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

Paul's avatar
Paul committed
52
    const char* data() const
Paul's avatar
Paul committed
53
    {
Paul's avatar
Paul committed
54
        return this->buffer.data();
Paul's avatar
Paul committed
55
56
57
58
59
60
61
    }

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

Paul's avatar
Paul committed
62
63
64
    argument get_argument() const
    {
        auto b = buffer;
Paul's avatar
Paul committed
65
        return {shape_, [b]() mutable { return b.data(); }};
Paul's avatar
Paul committed
66
67
    }

Paul's avatar
Paul committed
68
private:
Paul's avatar
Paul committed
69
70
71
72
73
74
75
    std::vector<char> buffer;
    shape shape_;
};

}

#endif