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