Skip to content

Commit cd8cd72

Browse files
committed
paramlist.h: ParamValue as_span, as_cspan
Convenience methods that give a bounded span of the data that a PV holds. Signed-off-by: Larry Gritz <[email protected]>
1 parent 4902772 commit cd8cd72

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

src/include/OpenImageIO/paramlist.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,26 @@ class OIIO_UTIL_API ParamValue {
215215
b = std::move(tmp);
216216
}
217217

218+
/// Return a `cspan<T>` pointing to the bounded data. If the type `T` is
219+
/// not the actual underlying base type, return an empty span.
220+
template<typename T> cspan<T> as_cspan() const noexcept
221+
{
222+
return BaseTypeFromC<T>::value == m_type.basetype
223+
? make_cspan(reinterpret_cast<const T*>(data()),
224+
size_t(m_nvalues * m_type.basevalues()))
225+
: cspan<T>();
226+
}
227+
228+
/// Return a `span<T>` pointing to the bounded data. If the type `T` is
229+
/// not the actual underlying base type, return an empty span.
230+
template<typename T> span<T> as_span() noexcept
231+
{
232+
return BaseTypeFromC<T>::value == m_type.basetype
233+
? make_span(reinterpret_cast<T*>(const_cast<void*>(data())),
234+
size_t(m_nvalues * m_type.basevalues()))
235+
: span<T>();
236+
}
237+
218238
// Use with extreme caution! This is just doing a cast. You'd better
219239
// be really sure you are asking for the right type. Note that for
220240
// "string" data, you can get<ustring> or get<char*>, but it's not

src/libutil/paramlist.cpp

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,17 +126,13 @@ template<class T>
126126
static void
127127
parse_elements(string_view value, ParamValue& p)
128128
{
129-
using namespace Strutil;
130-
TypeDesc type = p.type();
131-
int num_items = type.numelements() * type.aggregate;
132-
T* data = (T*)p.data();
133-
// Erase any leading whitespace
129+
auto data = p.as_span<T>();
134130
value.remove_prefix(value.find_first_not_of(" \t"));
135-
for (int i = 0; i < num_items; ++i) {
131+
for (auto&& d : data) {
136132
// Make a temporary copy so we for sure have a 0-terminated string.
137133
std::string temp = value;
138134
// Grab the first value from it
139-
data[i] = from_string<T>(temp);
135+
d = Strutil::from_string<T>(temp);
140136
// Skip the value (eat until we find a delimiter -- space, comma, tab)
141137
value.remove_prefix(value.find_first_of(" ,\t"));
142138
// Skip the delimiter

0 commit comments

Comments
 (0)