MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches

◆ npy_dtype()

std::optional< NpyTypestr > MayaFlux::IO::Detail::npy_dtype ( std::string_view typestr,
std::string & why )
nodiscard

Parse a numpy type string such as <f4, >i8 or |b1.

Parameters
whyReceives the reason when the type is not supported.

Definition at line 88 of file TensorCodec.cpp.

89{
90 size_t pos = 0;
91 bool big_endian = false;
92 if (!typestr.empty()) {
93 switch (typestr[0]) {
94 case '>':
95 big_endian = true;
96 pos = 1;
97 break;
98 case '=':
99 big_endian = !host_is_little_endian();
100 pos = 1;
101 break;
102 case '<':
103 case '|':
104 pos = 1;
105 break;
106 default:
107 break;
108 }
109 }
110 if (pos >= typestr.size()) {
111 why = "malformed numpy type string '" + std::string(typestr) + "'";
112 return std::nullopt;
113 }
114
115 const char code = typestr[pos++];
116 unsigned size = 0;
117 const char* end = typestr.data() + typestr.size();
118 const auto [parsed, error] = std::from_chars(typestr.data() + pos, end, size);
119 if (error != std::errc {} || parsed != end || size == 0 || size > 16) {
120 why = "malformed numpy type string '" + std::string(typestr) + "'";
121 return std::nullopt;
122 }
123
124 const auto bits = static_cast<uint8_t>(size * 8);
125 const auto make = [&](Kind kind) -> std::optional<NpyTypestr> {
126 return NpyTypestr { .dtype = { .kind = kind, .bits = bits, .lanes = 1 }, .big_endian = big_endian && size > 1 };
127 };
128
129 switch (code) {
130 case 'f':
131 if (size == 2 || size == 4 || size == 8)
132 return make(Kind::FLOAT);
133 break;
134 case 'i':
135 if (size == 1 || size == 2 || size == 4 || size == 8)
136 return make(Kind::INT);
137 break;
138 case 'u':
139 if (size == 1 || size == 2 || size == 4 || size == 8)
140 return make(Kind::UINT);
141 break;
142 case 'b':
143 if (size == 1)
144 return make(Kind::BOOL);
145 break;
146 case 'c':
147 if (size == 8 || size == 16)
148 return make(Kind::COMPLEX);
149 break;
150 default:
151 break;
152 }
153
154 why = "numpy type '" + std::string(typestr) + "' is not supported";
155 return std::nullopt;
156}
bool host_is_little_endian() noexcept
Whether this machine stores multi-byte values least significant byte first.
Element type and byte order read from a numpy type string.

References host_is_little_endian().

Referenced by parse_npy_header().

Here is the call graph for this function:
Here is the caller graph for this function: