From 3bbcde9192ac2a73edd48556e41d8403827e3d3a Mon Sep 17 00:00:00 2001 From: AnotherTest Date: Fri, 19 Mar 2021 17:27:35 +0330 Subject: [PATCH] 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. --- .../Applications/Spreadsheet/Readers/XSV.cpp | 18 ++++++++++++++++-- .../Applications/Spreadsheet/Readers/XSV.h | 9 ++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Userland/Applications/Spreadsheet/Readers/XSV.cpp b/Userland/Applications/Spreadsheet/Readers/XSV.cpp index fca9742ace..adc28be508 100644 --- a/Userland/Applications/Spreadsheet/Readers/XSV.cpp +++ b/Userland/Applications/Spreadsheet/Readers/XSV.cpp @@ -48,8 +48,17 @@ void XSV::set_error(ReadError error) Vector XSV::headers() const { Vector 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(*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); diff --git a/Userland/Applications/Spreadsheet/Readers/XSV.h b/Userland/Applications/Spreadsheet/Readers/XSV.h index a3fab2edd3..309e0ec384 100644 --- a/Userland/Applications/Spreadsheet/Readers/XSV.h +++ b/Userland/Applications/Spreadsheet/Readers/XSV.h @@ -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 headers() const; + [[nodiscard]] bool has_explicit_headers() const { return (static_cast(m_behaviours) & static_cast(ParserBehaviour::ReadHeaders)) != 0; } class Row { public: @@ -115,7 +116,11 @@ public: StringView operator[](StringView name) const; StringView operator[](size_t column) const; + template + 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(*this); } auto end() { return RowIterator(*this, m_rows.size()); }