shape.hpp 1.64 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
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
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
84
85
#ifndef GUARD_RTGLIB_SHAPE_HPP
#define GUARD_RTGLIB_SHAPE_HPP

#include <vector>
#include <cassert>

namespace rtg {

struct shape
{
    enum type_t
    {
        float_type,
        int_type
    };

    shape();
    shape(type_t t);
    shape(type_t t, std::vector<std::size_t> l);
    shape(type_t t, std::vector<std::size_t> l, std::vector<std::size_t> s);


    type_t type() const;
    const std::vector<std::size_t> lens() const;
    const std::vector<std::size_t> strides() const;
    std::size_t elements() const;
    std::size_t bytes() const;

    friend bool operator==(const shape& x, const shape& y);
    friend bool operator!=(const shape& x, const shape& y);

    template<class T>
    struct as
    {
        using type = T;

        template<class U>
        T operator()(U u) const
        {
            return T(u);
        }

        T operator()() const
        {
            return {};
        }

        std::size_t size(std::size_t n=0) const
        {
            return sizeof(T)*n;
        }

        template<class U>
        T& from(U* buffer, std::size_t n=0) const
        {
            return *(reinterpret_cast<T*>(buffer)+n);
        }
    };

    template<class Visitor>
    void visit_type(Visitor v) const
    {
        switch(this->type_) 
        {
            case float_type:
                v(as<float>());
                return;
            case int_type:
                v(as<int>());
                return;
        }
        assert(true);
    }
private:
    type_t type_;
    std::vector<std::size_t> lens_;
    std::vector<std::size_t> strides_;

    void calculate_strides();
    std::size_t element_space() const;
};

}

#endif