Stratax 0.3.1
Loading...
Searching...
No Matches
Print.hpp
1#pragma once
2
3#include <ostream>
4#include <string>
5
6#include <stratax/containers/Matrix.hpp>
7#include <stratax/containers/Tensor.hpp>
8#include <stratax/containers/Vector.hpp>
9#include <stratax/core/ArrayView.hpp>
10
11namespace stratax::container {
12
13namespace detail {
14
15template<typename T>
16void print_value(std::ostream& os, const T& value)
17{
18 using type = std::remove_cvref_t<T>;
19
20 if constexpr (std::same_as<type, dtype::bool_>)
21 {
22 os << (value ? "true" : "false");
23 }
24 else if constexpr (
25 std::same_as<type, dtype::int8> ||
26 std::same_as<type, dtype::uint8>)
27 {
28 os << static_cast<int>(value);
29 }
30 else
31 {
32 os << value;
33 }
34}
35
37template<Array A>
38void print_recursive(
39 std::ostream& os,
40 const A& array,
41 std::size_t dim,
42 std::size_t offset,
43 std::size_t depth,
44 const char* sibling_separator)
45{
46 const auto& shape = array.shape();
47 const auto logical_strides = shape.strides();
48
49 os << "[";
50
51 if (dim == shape.rank() - 1)
52 {
53 for (std::size_t i = 0; i < shape[dim]; ++i)
54 {
55 print_value(
56 os,
57 array[offset + i * logical_strides[dim]]);
58
59 if (i + 1 != shape[dim])
60 os << ", ";
61 }
62 }
63 else
64 {
65 os << '\n';
66
67 for (std::size_t i = 0; i < shape[dim]; ++i)
68 {
69 os << std::string((depth + 1) * 4, ' ');
70 print_recursive(
71 os,
72 array,
73 dim + 1,
74 offset + i * logical_strides[dim],
75 depth + 1,
76 sibling_separator);
77
78 if (i + 1 != shape[dim])
79 {
80 os << sibling_separator;
81 }
82 }
83
84 os << '\n';
85 os << std::string(depth * 4, ' ');
86 }
87
88 os << "]";
89}
90
91template<Array A>
92std::ostream& print_array(
93 std::ostream& os,
94 const A& array)
95{
96 if (array.empty())
97 {
98 os << "[]";
99 return os;
100 }
101
102 const char* sibling_separator =
103 array.rank() == 2 ? "\n" : ",\n";
104
105 print_recursive(
106 os,
107 array,
108 0,
109 0,
110 0,
111 sibling_separator);
112 return os;
113}
114
115}
116
117template<typename T>
118std::ostream& operator<<(std::ostream& os, const Vector<T>& vector)
119{
120 return detail::print_array(os, vector);
121}
122
123template<typename T>
124std::ostream& operator<<(std::ostream& os, const Matrix<T>& matrix)
125{
126 return detail::print_array(os, matrix);
127}
128
129template<typename T>
130std::ostream& operator<<(std::ostream& os, const Tensor<T>& tensor)
131{
132 return detail::print_array(os, tensor);
133}
134
135}
136
137namespace stratax::core {
138
139template<typename T>
140std::ostream& operator<<(std::ostream& os, const ArrayView<T>& view)
141{
142 return container::detail::print_array(os, view);
143}
144
145}