Commit b1e9363f authored by Paul's avatar Paul
Browse files

Print literals

parent 94f17f0a
......@@ -26,6 +26,16 @@ struct literal : raw_data<literal>
literal(shape s, const std::vector<T>& x)
: buffer(s.bytes(), 0), shape_(s)
{
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());
static_assert(std::is_trivial<T>{}, "Literals can only be trivial types");
std::copy(x.begin(), x.end(), reinterpret_cast<T*>(buffer.data()));
}
......
......@@ -25,7 +25,6 @@ struct program
return std::addressof(instructions.back());
}
instruction * add_parameter(std::string name, shape s)
{
instructions.push_back({"param:"+std::move(name), s, {}});
......
......@@ -2,6 +2,8 @@
#ifndef RTG_GUARD_RAW_DATA_HPP
#define RTG_GUARD_RAW_DATA_HPP
#include <rtg/tensor_view.hpp>
namespace rtg {
template<class Derived>
......@@ -31,6 +33,15 @@ struct raw_data
return !(x == y);
}
template<class Stream>
friend Stream& operator<<(Stream& os, const Derived& d)
{
d.visit([&](auto x) {
os << x;
});
return os;
}
template<class Visitor>
void visit_at(Visitor v, std::size_t n=0) const
{
......@@ -47,14 +58,14 @@ struct raw_data
auto && s = static_cast<const Derived&>(*this).get_shape();
auto && buffer = static_cast<const Derived&>(*this).data();
s.visit_type([&](auto as) {
v(make_view(this->s, as.from(buffer)));
v(make_view(s, as.from(buffer)));
});
}
bool single() const
{
auto && s = static_cast<const Derived&>(*this).get_shape();
return this->s.elements() == 1;
return s.elements() == 1;
}
template<class T>
......
......@@ -135,6 +135,19 @@ struct tensor_view
return !(x == y);
}
friend std::ostream& operator<<(std::ostream& os, const tensor_view<T>& x)
{
if(!x.empty())
{
os << x.front();
for(std::size_t i = 1;i < x.shape_.elements();i++)
{
os << ", " << x.data_[x.shape_.index(i)];
}
}
return os;
}
private:
T* data_;
shape shape_;
......
#include <rtg/literal.hpp>
#include <sstream>
#include <string>
#include "test.hpp"
int main() {
void literal_test()
{
EXPECT(rtg::literal{1} == rtg::literal{1});
EXPECT(rtg::literal{1} != rtg::literal{2});
EXPECT(rtg::literal{} == rtg::literal{});
......@@ -22,3 +26,35 @@ int main() {
EXPECT(l4.empty());
}
void literal_os1()
{
rtg::literal l{1};
std::stringstream ss;
ss << l;
EXPECT(ss.str() == "1");
}
void literal_os2()
{
rtg::literal l{};
std::stringstream ss;
ss << l;
EXPECT(ss.str() == "");
}
void literal_os3()
{
rtg::shape s{rtg::shape::int_type, {3}};
rtg::literal l{s, {1, 2, 3}};
std::stringstream ss;
ss << l;
EXPECT(ss.str() == "1, 2, 3");
}
int main() {
literal_test();
literal_os1();
literal_os2();
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment