161 std::stringstream ss;
162 bool inquotes =
false;
170 if (ch == std::char_traits<char>::eof())
173 char c =
static_cast<char>(ch);
175 if (not inquotes
and c ==
'"')
177 else if (inquotes
and c ==
'"')
179 if (in.peek() ==
'"')
180 ss <<
static_cast<char>(in.get());
184 else if (not inquotes
and c == delimiter)
189 else if (not inquotes
and (c ==
'\r' or c ==
'\n'))
191 if (in.peek() ==
'\n')
193 row.append(ss.str());
201 if (ss.str().size() > 0 or
row.size() > 0)
202 row.append(ss.str());
226 char delimiter =
',')
228 std::stringstream ss(line);
255 char delimiter =
',')
262 if (
row.size() == 0
and not in.good())
292 char delimiter =
',')
294 std::ifstream
file(filename);
295 if (not
file.is_open())
296 throw std::runtime_error(
"Cannot open file: " + filename);
321inline std::string
csv_escape(
const std::string & field,
char delimiter =
',')
323 bool needs_quoting =
false;
328 if (c == delimiter or c ==
'"' or c ==
'\n' or c ==
'\r')
330 needs_quoting =
true;
335 if (not needs_quoting)
339 std::string result =
"\"";
379 char delimiter =
',',
380 const std::string & line_ending =
"\n")
382 for (
size_t i = 0; i <
row.size(); ++i)
405 char delimiter =
',',
406 const std::string & line_ending =
"\n")
408 for (
size_t i = 0; i <
rows.size(); ++i)
427 char delimiter =
',',
428 const std::string & line_ending =
"\n")
430 std::ofstream
file(filename);
431 if (not
file.is_open())
432 throw std::runtime_error(
"Cannot open file for writing: " + filename);
469 if (
rows.size() == 0)
472 size_t expected_cols =
rows(0).size();
473 for (
size_t i = 1; i <
rows.size(); ++i)
474 if (
rows(i).
size() != expected_cols)
503 for (
size_t i = 0; i <
rows.size(); ++i)
506 throw std::out_of_range(
"Column index " + std::to_string(col_index) +
507 " out of range for row " + std::to_string(i));
537 std::istringstream ss(field);
542 throw std::invalid_argument(
"Cannot convert '" + field +
"' to number");
551 return std::stoi(field);
558 return std::stol(field);
565 return std::stod(field);
572 return std::stof(field);
616 [[nodiscard]]
const std::string &
operator[](
size_t index)
const
624 [[nodiscard]]
const std::string &
operator[](
const std::string & column_name)
const
627 throw std::runtime_error(
"No header set for CsvRow");
630 if ((*
header_)(i) == column_name)
633 throw std::out_of_range(
"Column not found: " + column_name);
637 [[nodiscard]]
const std::string &
at(
size_t index)
const
640 throw std::out_of_range(
"Index out of range: " + std::to_string(index));
645 [[nodiscard]]
bool has_column(
const std::string & column_name)
const
647 if (
header_ ==
nullptr)
return false;
649 if ((*
header_)(i) == column_name)
655 template <
typename T>
656 [[nodiscard]]
T get(
size_t index)
const
658 return csv_to_number<T>(
fields_(index));
662 template <
typename T>
663 [[nodiscard]]
T get(
const std::string & column_name)
const
665 return csv_to_number<T>((*
this)[column_name]);
724 explicit CsvReader(
const std::string & filename,
char delimiter =
',')
728 if (not
file_.is_open())
729 throw std::runtime_error(
"Cannot open file: " + filename);
733 explicit CsvReader(std::istream & stream,
char delimiter =
',')
812 return CsvRow(std::move(fields));
905template <
typename Pred>
910 for (
size_t i = 0; i <
rows.size(); ++i)
911 if (predicate(
rows(i)))
930 const std::string &
value)
959 for (
size_t i = 0; i <
rows.size(); ++i)
962 for (
size_t j = 0; j < col_indices.
size(); ++j)
964 size_t idx = col_indices(j);
970 result.
append(std::move(new_row));
989 for (
size_t i = n; i <
rows.size(); ++i)
1007 size_t limit = (n <
rows.size()) ? n :
rows.size();
1008 for (
size_t i = 0; i < limit; ++i)
1031 for (
size_t i = 0; i <
rows.size(); ++i)
1032 for (
size_t j = 0; j <
rows(i).size(); ++j)
1033 if (
rows(i)(j).empty())
1041template <
typename Pred>
1046 for (
size_t i = 0; i <
rows.size(); ++i)
1047 if (predicate(
rows(i)))
1056template <
typename Pred>
1060 for (
size_t i = 0; i <
rows.size(); ++i)
1061 if (predicate(
rows(i)))
1073 const std::string &
value)
1087 for (
size_t i = 0; i <
rows.size(); ++i)
1089 if (col_index >=
rows(i).
size())
continue;
1091 const std::string & val =
rows(i)(col_index);
1093 for (
size_t j = 0; j < result.
size(); ++j)
1094 if (result(j) == val) { found =
true;
break; }
1117 if (
rows.size() == 0)
1121 throw std::runtime_error(
"Cannot transpose non-rectangular CSV data");
1124 size_t num_cols =
rows(0).size();
1127 for (
size_t j = 0; j < num_cols; ++j)
1130 for (
size_t i = 0; i < num_rows; ++i)
1132 result.
append(std::move(new_row));
1150 bool ascending =
true)
1154 for (
size_t i = 0; i <
rows.size(); ++i)
1158 for (
size_t i = 0; i < indices.
size(); ++i)
1159 for (
size_t j = i + 1; j < indices.
size(); ++j)
1161 const std::string & a = (col_index <
rows(indices(i)).size())
1162 ?
rows(indices(i))(col_index) :
"";
1163 const std::string & b = (col_index <
rows(indices(j)).size())
1164 ?
rows(indices(j))(col_index) :
"";
1166 bool should_swap = ascending ? (a > b) : (a < b);
1168 std::swap(indices(i), indices(j));
1173 for (
size_t i = 0; i < indices.
size(); ++i)
1189template <
typename T>
1193 bool ascending =
true)
1197 for (
size_t i = 0; i <
rows.size(); ++i)
1199 T val = (col_index <
rows(i).size())
1200 ? csv_to_number<T>(
rows(i)(col_index)) :
T{};
1205 for (
size_t i = 0; i < pairs.
size(); ++i)
1206 for (
size_t j = i + 1; j < pairs.
size(); ++j)
1208 bool should_swap = ascending
1209 ? (pairs(i).first > pairs(j).first)
1210 : (pairs(i).first < pairs(j).first);
1212 std::swap(pairs(i), pairs(j));
1217 for (
size_t i = 0; i < pairs.
size(); ++i)
1235 for (
size_t i = 0; i <
rows.size(); ++i)
1237 bool is_duplicate =
false;
1238 for (
size_t j = 0; j < result.
size(); ++j)
1243 for (
size_t k = 0;
k <
rows(i).size(); ++
k)
1244 if (result(j)(
k) !=
rows(i)(
k)) {
equal =
false;
break; }
1246 if (
equal) { is_duplicate =
true;
break; }
1249 if (not is_duplicate)
1265template <
typename Func>
1272 for (
size_t i = 0; i <
rows.size(); ++i)
1275 for (
size_t j = 0; j <
rows(i).size(); ++j)
1277 result.
append(std::move(new_row));
1304 constexpr unsigned char bom[] = {0xEF, 0xBB, 0xBF};
1306 while (taken < 3
and in.peek() == bom[taken])
1314 for (; taken > 0; --taken)
1329 auto trim = [](
const std::string & s) -> std::string {
1331 while (start < s.size()
and std::isspace(
static_cast<unsigned char>(s[start])))
1334 size_t end = s.size();
1335 while (end > start
and std::isspace(
static_cast<unsigned char>(s[end - 1])))
1338 return s.substr(start, end - start);
1354 const std::string & default_value)
1357 return s.empty() ? default_value : s;
1377 size_t max_rows = (left.size() > right.size()) ? left.
size() : right.size();
1379 for (
size_t i = 0; i < max_rows; ++i)
1384 if (i < left.size())
1385 for (
size_t j = 0; j < left(i).size(); ++j)
1386 new_row.
append(left(i)(j));
1389 if (i < right.size())
1390 for (
size_t j = 0; j < right(i).size(); ++j)
1391 new_row.
append(right(i)(j));
1393 result.
append(std::move(new_row));
1413 for (
size_t i = 0; i < top.size(); ++i)
1416 for (
size_t i = 0; i < bottom.size(); ++i)
1417 result.
append(bottom(i));
1434 size_t left_key_col,
1436 size_t right_key_col)
1440 for (
size_t i = 0; i < left.size(); ++i)
1442 if (left_key_col >= left(i).
size())
continue;
1443 const std::string & left_key = left(i)(left_key_col);
1445 for (
size_t j = 0; j < right.size(); ++j)
1447 if (right_key_col >= right(j).size())
continue;
1449 if (left_key == right(j)(right_key_col))
1454 for (
size_t k = 0;
k < left(i).size(); ++
k)
1457 for (
size_t k = 0;
k < right(j).size(); ++
k)
1458 if (
k != right_key_col)
1461 result.
append(std::move(new_row));
1484 for (
size_t k = 0;
k <
keys.size(); ++
k)
1487 for (
size_t i = 0; i <
rows.size(); ++i)
1490 result.
append(std::move(group));
1515template <
typename Func>
1522 for (
size_t i = 0; i <
rows.size(); ++i)
1525 for (
size_t j = 0; j <
rows(i).size(); ++j)
1528 result.
append(std::move(new_row));
1545 const std::string & old_name,
1546 const std::string & new_name)
1548 if (
rows.size() == 0)
1555 for (
size_t j = 0; j <
rows(0).size(); ++j)
1557 if (
rows(0)(j) == old_name)
1558 new_header.
append(new_name);
1562 result.
append(std::move(new_header));
1565 for (
size_t i = 1; i <
rows.size(); ++i)
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void swap(Array &s) noexcept
Swap this with s
T & append(const T &data)
Append a copy of data
const Array< std::string > & operator*() const
bool operator!=(const Iterator &other) const
Array< std::string > current_
Iterator(CsvReader *reader, bool at_end)
Lazy CSV reader for large files.
void skip(size_t n)
Skip N rows.
CsvRow next_row()
Read the next row with header access.
Array< std::string > next()
Read the next row as Array.
CsvReader(std::istream &stream, char delimiter=',')
Construct reader from stream.
CsvReader(const std::string &filename, char delimiter=',')
Construct reader from file path.
void reset()
Reset to beginning (only works for file-based readers).
const Array< std::string > & header() const
Get the header (if read).
CsvReader(CsvReader &&other)
Take the stream and the header of another reader, which is left reading nothing.
Array< std::string > read_header()
Read and store the header row.
Array< std::string > header_
size_t rows_read() const
Get number of rows read so far.
void swap(CsvReader &other)
Exchange the streams, the headers and the counters of this reader and another.
bool has_next() const
Check if more rows are available.
CsvReader & operator=(CsvReader &&other)
Exchange this reader with another, which is left with the previous stream and header of this one.
bool has_header() const
Check if header was read.
A CSV row with header-based field access.
T get(const std::string &column_name) const
Get field as numeric type by column name.
T get(size_t index) const
Get field as numeric type.
const Array< std::string > * header_
const std::string & at(size_t index) const
Get field by index with bounds checking.
const Array< std::string > * header() const
Get column names (if header set).
const std::string & operator[](const std::string &column_name) const
Get field by column name.
bool empty() const
Check if row is empty.
size_t size() const
Get number of fields.
Array< std::string > fields_
CsvRow(Array< std::string > fields)
Construct from fields only (no header access).
bool has_column(const std::string &column_name) const
Check if column exists.
CsvRow(Array< std::string > fields, const Array< std::string > &header)
Construct with header reference for name-based access.
const std::string & operator[](size_t index) const
Get field by index.
const Array< std::string > & fields() const
Get underlying array.
Main namespace for Aleph-w library functions.
long csv_to_number< long >(const std::string &field)
size_t csv_find_row(const Array< Array< std::string > > &rows, Pred predicate)
Find first row matching a predicate.
Array< Array< std::string > > csv_sort_by_column_numeric(const Array< Array< std::string > > &rows, size_t col_index, bool ascending=true)
Sort CSV data by a column with numeric comparison.
Array< Array< std::string > > csv_trim_fields(const Array< Array< std::string > > &rows)
Trim whitespace from all fields.
std::string csv_escape(const std::string &field, char delimiter=',')
Escape a string for CSV output.
Array< Array< std::string > > csv_read_file(const std::string &filename, char delimiter=',')
Read all rows from a CSV file.
Array< Array< std::string > > csv_transform(const Array< Array< std::string > > &rows, Func func)
Apply a transformation to each field.
Array< Array< std::string > > csv_filter_by_value(const Array< Array< std::string > > &rows, size_t col_index, const std::string &value)
Filter CSV rows by column value.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool csv_skip_bom(std::istream &in)
Skip UTF-8 BOM if present.
Array< Array< std::string > > csv_transpose(const Array< Array< std::string > > &rows)
Transpose CSV data (swap rows and columns).
T csv_to_number(const std::string &field)
Convert a CSV field to a numeric type.
Array< Array< std::string > > csv_rename_column(const Array< Array< std::string > > &rows, const std::string &old_name, const std::string &new_name)
Rename a column (in the header row).
Array< Array< std::string > > csv_take_rows(const Array< Array< std::string > > &rows, size_t n)
Take only the first N rows of CSV data.
std::decay_t< typename HeadC::Item_Type > T
Array< std::string > csv_get_column(const Array< Array< std::string > > &rows, size_t col_index)
Get a column from CSV data.
Array< Array< std::string > > csv_join_horizontal(const Array< Array< std::string > > &left, const Array< Array< std::string > > &right)
Join two CSV datasets horizontally (add columns).
Array< Array< std::string > > csv_unique(const Array< Array< std::string > > &rows)
Remove duplicate rows.
Array< Array< Array< std::string > > > csv_group_by(const Array< Array< std::string > > &rows, size_t col_index)
Group rows by a column value.
float csv_to_number< float >(const std::string &field)
and
Check uniqueness with explicit hash + equality functors.
void csv_write_row(std::ostream &out, const Array< std::string > &row, char delimiter=',', const std::string &line_ending="\n")
Write a CSV row to an output stream.
size_t csv_num_columns(const Array< std::string > &row)
Get the number of columns in a CSV row.
size_t csv_count_empty(const Array< Array< std::string > > &rows)
Count empty fields in CSV data.
std::string trim(const std::string &s)
Return a trimmed copy of a std::string (leading + trailing whitespace removed).
Array< std::string > csv_read_row(std::istream &in, char delimiter=',')
Read a single CSV row from an input stream.
size_t csv_find_by_value(const Array< Array< std::string > > &rows, size_t col_index, const std::string &value)
Find row where column equals value.
bool csv_is_rectangular(const Array< Array< std::string > > &rows)
Check if all rows have the same number of columns.
bool equal(Itor1 beg, const Itor1 &end, Itor2 cmpBeg, BinaryPredicate op=BinaryPredicate())
Test if two ranges are equal.
Array< std::string > csv_distinct(const Array< Array< std::string > > &rows, size_t col_index)
Get distinct values in a column.
Array< Array< std::string > > csv_filter(const Array< Array< std::string > > &rows, Pred predicate)
Filter CSV rows by a predicate.
Array< Array< std::string > > csv_read_all(std::istream &in, char delimiter=',')
Read all rows from a CSV input stream.
int csv_to_number< int >(const std::string &field)
double csv_to_number< double >(const std::string &field)
Array< Array< std::string > > csv_inner_join(const Array< Array< std::string > > &left, size_t left_key_col, const Array< Array< std::string > > &right, size_t right_key_col)
Inner join two CSV datasets by a key column.
void csv_write_file(const std::string &filename, const Array< Array< std::string > > &rows, char delimiter=',', const std::string &line_ending="\n")
Write CSV data to a file.
Array< Array< std::string > > csv_skip_rows(const Array< Array< std::string > > &rows, size_t n)
Skip the first N rows of CSV data.
Array< Array< std::string > > csv_select_columns(const Array< Array< std::string > > &rows, const Array< size_t > &col_indices)
Select specific columns from CSV data.
Array< Array< std::string > > csv_fill_empty(const Array< Array< std::string > > &rows, const std::string &default_value)
Replace empty fields with a default value.
size_t csv_count_if(const Array< Array< std::string > > &rows, Pred predicate)
Count rows matching a predicate.
Array< Array< std::string > > csv_join_vertical(const Array< Array< std::string > > &top, const Array< Array< std::string > > &bottom)
Join two CSV datasets vertically (add rows).
Array< Array< std::string > > csv_add_column(const Array< Array< std::string > > &rows, Func func)
Add a new column with computed values.
Array< Array< std::string > > csv_sort_by_column(const Array< Array< std::string > > &rows, size_t col_index, bool ascending=true)
Sort CSV data by a column.
void csv_write_all(std::ostream &out, const Array< Array< std::string > > &rows, char delimiter=',', const std::string &line_ending="\n")
Write multiple CSV rows to an output stream.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
size_t csv_count_rows(const Array< Array< std::string > > &rows)
Count total number of rows.
Dynamic array container with automatic resizing.