Spreadsheet/XSV: Add at() accessors

These are just aliases for operator[].
Also make the headers() getter return a vector of empty strings when the
csv file has no explicit headers.
This commit is contained in:
AnotherTest 2021-03-19 17:27:35 +03:30 committed by Andreas Kling
parent 39f3f3be94
commit 3bbcde9192
Notes: sideshowbarker 2024-07-18 21:10:18 +09:00
2 changed files with 24 additions and 3 deletions

View File

@ -48,8 +48,17 @@ void XSV::set_error(ReadError error)
Vector<String> XSV::headers() const
{
Vector<String> headers;
for (auto& field : m_names)
headers.append(field.is_string_view ? field.as_string_view : field.as_string.view());
if (has_explicit_headers()) {
for (auto& field : m_names)
headers.append(field.is_string_view ? field.as_string_view : field.as_string.view());
} else {
// No headers read, grab one of the rows and generate empty names
if (m_rows.is_empty())
return headers;
for ([[maybe_unused]] auto& field : m_rows.first())
headers.append(String::empty());
}
return headers;
}
@ -263,6 +272,11 @@ const XSV::Row XSV::operator[](size_t index) const
return const_cast<XSV&>(*this)[index];
}
XSV::Row XSV::at(size_t index) const
{
return this->operator[](index);
}
XSV::Row XSV::operator[](size_t index)
{
VERIFY(m_rows.size() > index);

View File

@ -49,7 +49,7 @@ ParserBehaviour operator|(ParserBehaviour left, ParserBehaviour right);
struct ParserTraits {
String separator;
String quote { "\"" };
enum {
enum QuoteEscape {
Repeat,
Backslash,
} quote_escape { Repeat };
@ -103,6 +103,7 @@ public:
size_t size() const { return m_rows.size(); }
Vector<String> headers() const;
[[nodiscard]] bool has_explicit_headers() const { return (static_cast<u32>(m_behaviours) & static_cast<u32>(ParserBehaviour::ReadHeaders)) != 0; }
class Row {
public:
@ -115,7 +116,11 @@ public:
StringView operator[](StringView name) const;
StringView operator[](size_t column) const;
template<typename T>
StringView at(T column) const { return this->operator[](column); }
size_t index() const { return m_index; }
size_t size() const { return m_xsv.headers().size(); }
// FIXME: Implement begin() and end(), keeping `Field' out of the API.
@ -166,6 +171,8 @@ public:
const Row operator[](size_t index) const;
Row operator[](size_t index);
Row at(size_t index) const;
auto begin() { return RowIterator<false>(*this); }
auto end() { return RowIterator<false>(*this, m_rows.size()); }