diff --git a/docs/docs/namespaces/csv.md b/docs/docs/namespaces/csv.md index fceed624e..3fd7607e3 100644 --- a/docs/docs/namespaces/csv.md +++ b/docs/docs/namespaces/csv.md @@ -25,6 +25,8 @@ Signatures: Returns: a `table`. Empty fields use the selected type's missing-input behavior. Sentinel-nullable columns record nulls with `RAY_ATTR_HAS_NULLS`; `SYM`/`STR` fields collapse to ordinary empty values and those columns do not acquire `RAY_ATTR_HAS_NULLS` from them. +A row, and the header, ends at a line end, with quotes in the file or without: line ends are read greedily from left to right, a CRLF or an LFCR whenever the byte at the position starts one, else the single LF or CR (so `\n\r\n\r` is two line ends); inside a quoted cell these bytes are part of the text. `.csv.write` ends rows with LF and quotes every cell that holds a CR or an LF, so what it writes reads back cell for cell. Files that read differently before this rule: a file without quotes in which a CR stands alone under that reading (rows were split at LF only, and the text after such a CR in a line was dropped), a file with quotes that holds an LFCR (each read as two line ends, an empty row after each), a file whose header ends in LFCR (its first data row read as nulls), and a file whose header ends in a CR (its delimiter was guessed from the header and the data after it). + A UTF-8 byte-order mark (the bytes `EF BB BF`, as spreadsheet exports write) at the start of the file is skipped: it is part of neither the first column name nor, in a file without a header, the first cell. `.csv.splayed` and `.csv.parted` skip it too. Errors: `type` (bad arg), `domain` (path is null / too long, zero columns, or a bad options dict), `io` (open/read failure), `limit` (>256 columns), `parse` (a bad row under `{strict: true}`). @@ -65,7 +67,6 @@ The rule: a non-empty cell must be stored as the value its text says. A strict l - the text spells the type's null: `"-32768" reads as a null I16`. These are the values each type keeps as its null sentinel: the minimum of `I16`, `I32`, `I64`, `TIME` (`-596:31:23.648`) and `TIMESTAMP` (`1707-09-22T00:12:43.145224192`), the all-zero `GUID`, and `0Nn` for a `TIMESPAN`; - a time has more fraction digits than its type holds and they are not zeros: `"10:00:00.1234" has more fraction digits than a TIME holds` (`TIME` keeps milliseconds, `TIMESPAN` and `TIMESTAMP` nanoseconds); - a quoted cell has text after its closing quote (`"ab"cd`) or no closing quote. The header's quoted cells are held to the same: `line 1: header cell 1: text after the closing quote`; -- in a file without quotes, where rows end at LF (or CRLF), text follows a lone CR inside the row: the default never reads it. Without a schema the types checked are the inferred ones: a column inferred from the sample as `I64` refuses a later cell of text, so give a schema when the sample may not show every kind of value. An empty cell (`,,` or `""`) is a null in both modes. A final line without a newline is an ordinary row. The line is the file's: the header is line 1 when there is one, and newlines inside quoted cells count, so the line is the one an editor shows the row starting on. When several rows are bad the error names the first in the file, whatever the parallel split. diff --git a/src/io/csv.c b/src/io/csv.c index 23ea0ffa4..efb55e0fe 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -72,6 +72,11 @@ #include #include #endif +#if defined(__GNUC__) && defined(__AVX2__) +#include +#elif defined(__GNUC__) && defined(__SSE2__) +#include +#endif /* -------------------------------------------------------------------------- * Constants @@ -850,6 +855,108 @@ RAY_INLINE void fast_guid(const char* p, size_t len, uint8_t* dst, bool* is_null #define CSV_SCAN_CHUNKS(pool) ((int64_t)ray_pool_total_workers(pool) * 4) #endif +/* Line ends (#1891). A row, the header included, ends at LF, CRLF, a lone + * CR, or LFCR, read greedily left to right (csv_eol_len), with quotes in + * the file or without. The fast scan (no quotes) finds the + * next LF or CR and the byte-at-a-time scan (quotes) walks to it; both take + * the line end there by csv_eol_len, so they split a file the same way. */ + +#if defined(_MSC_VER) +#define CSV_NOINLINE __declspec(noinline) +#else +#define CSV_NOINLINE __attribute__((noinline)) +#endif + +/* The length of the line end at p (1 or 2); p is at an LF or a CR. Line + * ends are read greedily left to right: a CRLF or an LFCR whenever the byte + * at p starts one, else the one byte (#1895), so "\n\r\n\r" is two. */ +RAY_INLINE size_t csv_eol_len(const char* p, const char* end) { + return (p + 1 < end && (p[1] == '\n' || p[1] == '\r') && p[1] != p[0]) ? 2 : 1; +} + +/* Past one line end at p, if p is at one. */ +RAY_INLINE const char* csv_skip_eol(const char* p, const char* end) { + return (p < end && (*p == '\n' || *p == '\r')) ? p + csv_eol_len(p, end) : p; +} + +/* The first LF or CR in [p, end), or NULL: the fast scan's search, one + * pass for both bytes. With AVX2 it reads aligned 32-byte blocks, as the + * C library's memchr does: an aligned block never crosses a page, so the + * bytes of the first block before p and of the last one past end are + * mapped and are masked off. [p, end) must lie in the file mapping every + * caller scans (ray_vm_map_fd_ro: page-aligned, whole pages). */ +RAY_INLINE const char* csv_find_eol(const char* p, const char* end) { + if (p >= end) return NULL; +#if defined(__GNUC__) && defined(__AVX2__) + const __m256i lf = _mm256_set1_epi8('\n'), cr = _mm256_set1_epi8('\r'); +#define CSV_EOL_MASK(q) ((unsigned)_mm256_movemask_epi8(_mm256_or_si256( \ + _mm256_cmpeq_epi8(_mm256_load_si256((const __m256i*)(const void*)(q)), lf), \ + _mm256_cmpeq_epi8(_mm256_load_si256((const __m256i*)(const void*)(q)), cr)))) + const char* blk = (const char*)((uintptr_t)p & ~(uintptr_t)31); + unsigned m = CSV_EOL_MASK(blk) >> (unsigned)(p - blk); + if (m) { const char* r = p + __builtin_ctz(m); return r < end ? r : NULL; } + for (blk += 32; blk < end; blk += 32) { + m = CSV_EOL_MASK(blk); + if (m) { const char* r = blk + __builtin_ctz(m); return r < end ? r : NULL; } + } + return NULL; +#undef CSV_EOL_MASK +#else +#if defined(__GNUC__) && defined(__SSE2__) + const __m128i lf = _mm_set1_epi8('\n'), cr = _mm_set1_epi8('\r'); + while (end - p >= 16) { + __m128i x = _mm_loadu_si128((const __m128i*)(const void*)p); + unsigned m = (unsigned)_mm_movemask_epi8( + _mm_or_si128(_mm_cmpeq_epi8(x, lf), _mm_cmpeq_epi8(x, cr))); + if (m) return p + __builtin_ctz(m); + p += 16; + } +#endif + for (; p < end; p++) + if (*p == '\n' || *p == '\r') return p; + return NULL; +#endif +} + +/* The first LF, CR or quote in [p, end), or NULL: csv_find_eol with the + * quote as a third byte, for the quoted scan outside a quoted cell; the + * same aligned blocks and the same mapping precondition. */ +RAY_INLINE const char* csv_find_qeol(const char* p, const char* end) { + if (p >= end) return NULL; +#if defined(__GNUC__) && defined(__AVX2__) + const __m256i lf = _mm256_set1_epi8('\n'), cr = _mm256_set1_epi8('\r'), + qt = _mm256_set1_epi8('"'); +#define CSV_EOL_MASK(q) ((unsigned)_mm256_movemask_epi8(_mm256_or_si256(_mm256_or_si256( \ + _mm256_cmpeq_epi8(_mm256_load_si256((const __m256i*)(const void*)(q)), lf), \ + _mm256_cmpeq_epi8(_mm256_load_si256((const __m256i*)(const void*)(q)), cr)), \ + _mm256_cmpeq_epi8(_mm256_load_si256((const __m256i*)(const void*)(q)), qt)))) + const char* blk = (const char*)((uintptr_t)p & ~(uintptr_t)31); + unsigned m = CSV_EOL_MASK(blk) >> (unsigned)(p - blk); + if (m) { const char* r = p + __builtin_ctz(m); return r < end ? r : NULL; } + for (blk += 32; blk < end; blk += 32) { + m = CSV_EOL_MASK(blk); + if (m) { const char* r = blk + __builtin_ctz(m); return r < end ? r : NULL; } + } + return NULL; +#undef CSV_EOL_MASK +#else +#if defined(__GNUC__) && defined(__SSE2__) + const __m128i lf = _mm_set1_epi8('\n'), cr = _mm_set1_epi8('\r'), qt = _mm_set1_epi8('"'); + while (end - p >= 16) { + __m128i x = _mm_loadu_si128((const __m128i*)(const void*)p); + unsigned m = (unsigned)_mm_movemask_epi8( + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(x, lf), _mm_cmpeq_epi8(x, cr)), + _mm_cmpeq_epi8(x, qt))); + if (m) return p + __builtin_ctz(m); + p += 16; + } +#endif + for (; p < end; p++) + if (*p == '\n' || *p == '\r' || *p == '"') return p; + return NULL; +#endif +} + typedef struct { const char* buf; size_t file_size; @@ -886,6 +993,72 @@ static void csv_scan_count_fn(void* arg, uint32_t worker_id, } } +/* Pass 2 over one chunk [p, cend) of a file without quotes: the row starts + * into out, their count returned. Mirrors the serial fast path exactly: + * the next LF or CR ends the line, csv_eol_len deciding how long the line + * end is. Out of line, as is the quoted one below, so that neither loop is + * compiled around the other's code. */ +CSV_NOINLINE static int64_t csv_scan_chunk_fast(const char* buf, const char* end, + const char* p, const char* cend, + int64_t* out) { + int64_t n = 0; + size_t checked = 0; + while (p < cend) { + if (RAY_UNLIKELY((++checked & 0xFFFF) == 0 && ray_interrupted())) break; + const char* nl = csv_find_eol(p, cend); + if (!nl) break; + p = nl + csv_eol_len(nl, end); + if (p >= end) break; + out[n++] = (int64_t)(p - buf); + } + return n; +} + +/* The same for a file with quotes. Mirrors the serial slow path exactly: + * quote parity gates the terminators, '\r' alone ends a row, "\r\n" and + * "\n\r" end exactly one (csv_eol_len). + * + * Two shortcuts, provably equivalent. INSIDE a quoted field the serial + * loop's only reachable action is "p++" until it meets the closing '"' (the + * newline arm is gated on !in_quote), so memchr jumps straight to that + * quote. OUTSIDE one its only actions besides "p++" are at a quote or a + * line end, so csv_find_qeol jumps to the next of those: the scan never + * walks bytes one at a time. (#1895: as a byte loop, the quoted scan's + * speed hung on how a compiler laid it out -- one build ran it 37% slower + * than dev's identical loop.) */ +CSV_NOINLINE static int64_t csv_scan_chunk_quoted(const char* buf, const char* end, + const char* p, const char* cend, + int64_t* out, bool in_quote) { + int64_t n = 0; + size_t checked = 0; + if (in_quote) { + const char* q = (const char*)memchr(p, '"', (size_t)(cend - p)); + if (!q) return 0; + p = q + 1; + } + while (p < cend) { + if (RAY_UNLIKELY((++checked & 0xFFF) == 0 && ray_interrupted())) break; + /* outside a quoted cell only a quote and a line end matter: find + * the next of them, as the byte-at-a-time walk would reach it */ + const char* e = csv_find_qeol(p, cend); + if (!e) break; + if (*e == '"') { + /* Bounding the search at cend is defensive, not required: the + * `p < cend` guard already stops the loop after an overshoot, + * so searching to the file end would find the same offsets. + * Bounded because a chunk has no business reading past its own + * slice. */ + const char* q = (const char*)memchr(e + 1, '"', (size_t)(cend - e - 1)); + if (!q) break; + p = q + 1; + continue; + } + p = e + csv_eol_len(e, end); + if (p < end) out[n++] = (int64_t)(p - buf); + } + return n; +} + static void csv_scan_rows_fn(void* arg, uint32_t worker_id, int64_t start, int64_t end_i) { (void)worker_id; @@ -897,78 +1070,34 @@ static void csv_scan_rows_fn(void* arg, uint32_t worker_id, const char* p = buf + ctx->bound[i]; const char* cend = buf + ctx->bound[i + 1]; int64_t* out = ctx->offs + ctx->slot[i]; - int64_t n = 0; - - if (RAY_LIKELY(!ctx->has_quotes)) { - /* Mirrors the serial fast path exactly: only '\n' terminates a - * row, and an optional '\r' immediately after it is absorbed. */ - size_t checked = 0; - while (p < cend) { - if (RAY_UNLIKELY((++checked & 0xFFFF) == 0 && ray_interrupted())) break; - const char* nl = (const char*)memchr(p, '\n', (size_t)(cend - p)); - if (!nl) break; - p = nl + 1; - if (p < end && *p == '\r') p++; - if (p >= end) break; - out[n++] = (int64_t)(p - buf); - } - } else { - /* Mirrors the serial slow path exactly: quote parity gates the - * terminators, '\r' alone ends a row, "\r\n" ends exactly one. - * - * One shortcut, provably equivalent: INSIDE a quoted field the - * serial loop's only reachable action is "p++" until it meets the - * closing '"' (the newline arm is gated on !in_quote), so memchr - * can jump straight to that quote. Worth doing because a quoted - * field is where the byte-at-a-time loop spends its time — long - * URL/title columns are exactly the quoted ones. */ - bool in_quote = ctx->start_quoted[i] != 0; - size_t checked = 0; - while (p < cend) { - if (in_quote) { - if (RAY_UNLIKELY((++checked & 0xFFF) == 0 && ray_interrupted())) break; - /* Bounding the search at cend is defensive, not required: - * the `p < cend` guard above already stops the loop after - * an overshoot, so searching to the file end would find - * the same offsets (it would just do the next chunk's - * work). Bounded because a chunk has no business reading - * past its own slice. */ - const char* q = (const char*)memchr(p, '"', (size_t)(cend - p)); - if (!q) { p = cend; break; } - p = q + 1; - in_quote = false; - continue; - } - /* Outside a quoted field (in_quote is false for the rest of - * this iteration by construction). */ - if (RAY_UNLIKELY((++checked & 0xFFFF) == 0 && ray_interrupted())) break; - char c = *p; - if (c == '"') { - in_quote = true; - p++; - } else if (c == '\n' || c == '\r') { - if (c == '\r' && p + 1 < end && *(p + 1) == '\n') p++; - p++; - if (p < end) out[n++] = (int64_t)(p - buf); - } else { - p++; - } - } - } - ctx->n_out[i] = n; + ctx->n_out[i] = RAY_LIKELY(!ctx->has_quotes) + ? csv_scan_chunk_fast(buf, end, p, cend, out) + : csv_scan_chunk_quoted(buf, end, p, cend, out, ctx->start_quoted[i] != 0); } } -/* Nudge a chunk boundary right so a two-byte line terminator is never split. +/* Nudge a chunk boundary s right, by at most one byte, so that it falls + * where a line end starts, as the serial scan reads the file: a two-byte + * line end is never split. lo is the boundary before, already resolved. * Quoted or not, the left chunk's state machine consumes both bytes of the * pair, so the byte after it must belong to the left chunk as well. */ static size_t csv_scan_split_at(const char* buf, size_t file_size, size_t s, - bool has_quotes) { - if (s == 0 || s >= file_size) return s; - char prev = buf[s - 1], cur = buf[s]; - if (has_quotes) { if (prev == '\r' && cur == '\n') s++; } - else { if (prev == '\n' && cur == '\r') s++; } - return s; + size_t lo) { + if (s <= lo || s >= file_size) return s; +#define CSV_IS_EOL(c) ((c) == '\n' || (c) == '\r') + if (!CSV_IS_EOL(buf[s - 1]) || !CSV_IS_EOL(buf[s])) return s; + /* Inside a run of line-end bytes (#1895). Read greedily, a run starts + * a line end at its first byte, and at every k where buf[k-1] == + * buf[k] (the byte before ends a line end, a single or the second of a + * pair); between such points the bytes alternate and pair up. So the + * nearest such point at or before s -- or lo, the boundary before this + * one, which starts a line end too -- fixes s by parity. The walk + * never passes lo, so the boundaries' walks are disjoint: at most one + * read of each byte over all of them, and none in an LF or CR run. */ + size_t k = s; + while (k > lo && CSV_IS_EOL(buf[k - 1]) && buf[k - 1] != buf[k]) k--; +#undef CSV_IS_EOL + return ((s - k) & 1) ? s + 1 : s; } /* Returns the row count (>=0), -1 if interrupted, or -2 when the parallel @@ -1056,9 +1185,8 @@ static int64_t build_row_offsets_par(const char* buf, size_t buf_size, * byte skipped is always '\n' or '\r', never '"', so the parities * computed above stay exact. */ for (int64_t i = 1; i < n_chunks; i++) { - size_t s = csv_scan_split_at(buf, buf_size, bound[i], ctx.has_quotes); - if (s < bound[i - 1]) s = bound[i - 1]; - bound[i] = s; + size_t s = bound[i] < bound[i - 1] ? bound[i - 1] : bound[i]; + bound[i] = csv_scan_split_at(buf, buf_size, s, bound[i - 1]); } /* Slice sizing: a chunk emits at most one row start per line-terminator @@ -1141,9 +1269,9 @@ static int64_t build_row_offsets_serial(const char* buf, size_t buf_size, bool has_quotes = (memchr(p, '"', remaining) != NULL); if (RAY_LIKELY(!has_quotes)) { - /* Fast path: no quotes, use memchr for newlines. - * Only scans for \n; pure \r line endings (old Mac) treated as single row. - * Empty lines are preserved as rows (for NULL handling). */ + /* Fast path: no quotes; the next LF or CR ends the line, with the + * line end csv_eol_len reads there. Empty lines are preserved as + * rows (for NULL handling). */ for (;;) { if (RAY_UNLIKELY((n & 0xFFFF) == 0)) { if (ray_interrupted()) { @@ -1156,11 +1284,9 @@ static int64_t build_row_offsets_serial(const char* buf, size_t buf_size, (uint64_t)((double)prog_len * (double)(size_t)(p - buf - (ptrdiff_t)data_offset) / (double)remaining)); } - const char* nl = (const char*)memchr(p, '\n', (size_t)(end - p)); + const char* nl = csv_find_eol(p, end); if (!nl) break; - p = nl + 1; - /* Skip optional \r after \n (unusual \n\r endings) */ - if (p < end && *p == '\r') p++; + p = nl + csv_eol_len(nl, end); if (p >= end) break; if (n >= est) { @@ -1173,8 +1299,10 @@ static int64_t build_row_offsets_serial(const char* buf, size_t buf_size, offs[n++] = (int64_t)(p - buf); } } else { - /* Slow path: track quote parity, byte-by-byte. - * Empty lines preserved as rows (for NULL handling). */ + /* Slow path: track quote parity. Inside a quoted cell memchr jumps + * to its closing quote, outside one csv_find_qeol to the next quote + * or line end (as csv_scan_chunk_quoted does). Empty lines + * preserved as rows (for NULL handling). */ bool in_quote = false; size_t checked = 0; while (p < end) { @@ -1190,25 +1318,30 @@ static int64_t build_row_offsets_serial(const char* buf, size_t buf_size, (uint64_t)((double)prog_len * (double)(size_t)(p - buf - (ptrdiff_t)data_offset) / (double)remaining)); } - char c = *p; - if (c == '"') { - in_quote = !in_quote; - p++; - } else if (!in_quote && (c == '\n' || c == '\r')) { - if (c == '\r' && p + 1 < end && *(p + 1) == '\n') p++; - p++; - if (p < end) { - if (n >= est) { - est *= 2; - offs = (int64_t*)scratch_realloc(&hdr, - (size_t)n * sizeof(int64_t), - (size_t)est * sizeof(int64_t)); - if (!offs) { scratch_free(hdr); *offsets_out = NULL; *hdr_out = NULL; return 0; } - } - offs[n++] = (int64_t)(p - buf); + if (in_quote) { + const char* q = (const char*)memchr(p, '"', (size_t)(end - p)); + if (!q) { p = end; break; } + p = q + 1; + in_quote = false; + continue; + } + const char* e = csv_find_qeol(p, end); + if (!e) { p = end; break; } + if (*e == '"') { + p = e + 1; + in_quote = true; + continue; + } + p = e + csv_eol_len(e, end); + if (p < end) { + if (n >= est) { + est *= 2; + offs = (int64_t*)scratch_realloc(&hdr, + (size_t)n * sizeof(int64_t), + (size_t)est * sizeof(int64_t)); + if (!offs) { scratch_free(hdr); *offsets_out = NULL; *hdr_out = NULL; return 0; } } - } else { - p++; + offs[n++] = (int64_t)(p - buf); } } } @@ -1318,13 +1451,12 @@ static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, scratch_free(hdr); return -1; } - const char* nl = (const char*)memchr(p, '\n', (size_t)(end - p)); + const char* nl = csv_find_eol(p, end); if (!nl) { p = end; break; } - p = nl + 1; - if (p < end && *p == '\r') p++; + p = nl + csv_eol_len(nl, end); if (p >= end) break; if (n >= max_rows) break; if (n >= est) { @@ -1352,31 +1484,38 @@ static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, return -1; } } - char c = *p; - if (c == '"') { - in_quote = !in_quote; - p++; - } else if (!in_quote && (c == '\n' || c == '\r')) { - if (c == '\r' && p + 1 < end && *(p + 1) == '\n') p++; - p++; - if (p >= end) break; - if (n >= max_rows) break; - if (n >= est) { - int64_t new_est = est * 2; - if (new_est > max_rows) new_est = max_rows; - offs = (int64_t*)scratch_realloc(&hdr, - (size_t)n * sizeof(int64_t), - (size_t)new_est * sizeof(int64_t)); - if (!offs) { - scratch_free(hdr); - return 0; - } - est = new_est; + /* as the serial slow path: jump to the closing quote, or to + * the next quote or line end */ + if (in_quote) { + const char* q = (const char*)memchr(p, '"', (size_t)(end - p)); + if (!q) { p = end; break; } + p = q + 1; + in_quote = false; + continue; + } + const char* e = csv_find_qeol(p, end); + if (!e) { p = end; break; } + if (*e == '"') { + p = e + 1; + in_quote = true; + continue; + } + p = e + csv_eol_len(e, end); + if (p >= end) break; + if (n >= max_rows) break; + if (n >= est) { + int64_t new_est = est * 2; + if (new_est > max_rows) new_est = max_rows; + offs = (int64_t*)scratch_realloc(&hdr, + (size_t)n * sizeof(int64_t), + (size_t)new_est * sizeof(int64_t)); + if (!offs) { + scratch_free(hdr); + return 0; } - offs[n++] = (int64_t)(p - buf); - } else { - p++; + est = new_est; } + offs[n++] = (int64_t)(p - buf); } } @@ -2243,7 +2382,7 @@ static bool csv_finalize_run(csv_finalize_ctx_t* ctx, int* fill_cols, /* The first bad row a strict parse saw (#1885); row INT64_MAX: none. */ enum { CSV_BAD_CELLS = 1, CSV_BAD_CELL, CSV_BAD_AFTER_QUOTE, CSV_BAD_UNCLOSED, - CSV_BAD_LONE_CR, CSV_BAD_RANGE, CSV_BAD_NULLV, CSV_BAD_PRECISION, + CSV_BAD_RANGE, CSV_BAD_NULLV, CSV_BAD_PRECISION, CSV_BAD_UNDERFLOW }; typedef struct { int64_t row; @@ -2283,9 +2422,7 @@ typedef struct { * (INT16_MIN in an I16), or turns into an infinity (1e39 in an F32) -- is * bad too: a wrapped value is worse than a null. (Out-of-range I64 and * non-finite F64 text already parses to a null.) An empty cell is a null - * in both modes. A file - * without quotes splits rows at LF only, and a cell ends at CR, so text - * after a lone CR inside a row is never read: strict refuses it too. */ + * in both modes. */ static bool csv_quote_closed(const char* p, const char* buf_end) { for (p++; p < buf_end; p++) { if (*p != '"') continue; @@ -2892,16 +3029,11 @@ static void csv_parse_fn_strict(void* arg, uint32_t worker_id, bad_kind == CSV_BAD_NULLV || bad_kind == CSV_BAD_PRECISION || bad_kind == CSV_BAD_UNDERFLOW) && cells != n_cols) bad_kind = 0; - if (!bad_kind && cells == n_cols) { - const char* q = p; - while (q < row_end && (*q == '\r' || *q == '\n')) q++; - if (q < row_end) bad_kind = CSV_BAD_LONE_CR; - } csv_bad_t* bad = &ctx->worker_bad[worker_id]; if ((bad_kind || cells != n_cols) && row < bad->row) { bad->row = row; bad->kind = bad_kind ? bad_kind : (uint8_t)CSV_BAD_CELLS; - bad->col = (bad_kind && bad_kind != CSV_BAD_LONE_CR) ? bad_col : -1; + bad->col = bad_kind ? bad_col : -1; } } } @@ -2913,11 +3045,6 @@ static void csv_parse_fn_strict(void* arg, uint32_t worker_id, /* Not inlined into its one caller, csv_parse_all: inlined there it ran more * instructions per row than it does on its own. */ -#if defined(_MSC_VER) -#define CSV_NOINLINE __declspec(noinline) -#else -#define CSV_NOINLINE __attribute__((noinline)) -#endif CSV_NOINLINE static bool csv_parse_serial(const char* buf, size_t buf_size, const int64_t* row_offsets, int64_t n_rows, int n_cols, char delim, @@ -3207,20 +3334,19 @@ static size_t csv_show(const char* p, size_t len, bool more, char* out, size_t c return o; } -/* The file's line `at` starts on, 1-based: a line ends at LF, CRLF (or - * LFCR) or a lone CR, as a row can. */ +/* The file's line `at` starts on, 1-based: the line ends before it, read + * as the row scans read them -- left to right, csv_eol_len deciding each + * one's length -- so a run such as CRLF then a lone CR is two (#1895). + * Newlines inside quoted cells count too: the line is the one an editor + * shows. Error path only. */ static int64_t csv_line_of(const char* buf, const char* buf_end, const char* at) { int64_t line = 1; - for (const char* q = buf; q < at; ) { - q = memchr(q, '\n', (size_t)(at - q)); - if (!q) break; - line++; q++; - } - for (const char* q = buf; q < at; ) { - q = memchr(q, '\r', (size_t)(at - q)); - if (!q) break; - if ((q + 1 >= buf_end || q[1] != '\n') && (q == buf || q[-1] != '\n')) line++; - q++; + const char* p = buf; + while (p < at) { + const char* e = csv_find_eol(p, at); + if (!e) break; + line++; + p = e + csv_eol_len(e, buf_end); } return line; } @@ -3329,10 +3455,6 @@ static ray_t* csv_strict_error(const ray_csv_opts_t* opts, const char* path, case CSV_BAD_CELLS: snprintf(post, sizeof post, ": expected %d cell%s, got %d", ncols, ncols == 1 ? "" : "s", cells); return csv_strict_msg(op, path, line, NULL, 0, post, NULL, 0, false, "", rsv); - case CSV_BAD_LONE_CR: - return csv_strict_msg(op, path, line, NULL, 0, - ": text after a CR inside the row (a row ends at LF or CRLF)", - NULL, 0, false, "", rsv); case CSV_BAD_UNCLOSED: return csv_strict_msg(op, path, line, name, name_len, ": a quoted cell with no closing quote", NULL, 0, false, "", rsv); @@ -3799,8 +3921,7 @@ static const char* csv_skip_matching_header(const char* p, const char* buf_end, if (dyn) ray_sys_free(dyn); } if (!is_header) return NULL; - if (p < buf_end && *p == '\r') p++; - if (p < buf_end && *p == '\n') p++; + p = csv_skip_eol(p, buf_end); /* LF, CRLF, CR or LFCR (#1891) */ return p; } @@ -3879,7 +4000,7 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h * was considered but adds complexity for a rare edge case. */ if (delimiter == 0) { int commas = 0, tabs = 0; - for (const char* p = text; p < buf_end && *p != '\n'; p++) { + for (const char* p = text; p < buf_end && *p != '\n' && *p != '\r'; p++) { if (*p == ',') commas++; if (*p == '\t') tabs++; } @@ -3941,8 +4062,7 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h /* Consume exactly one line terminator (\r, \n, or \r\n) after the * header row — NOT a run of newlines, because subsequent empty * lines are null data rows. */ - if (p < buf_end && *p == '\r') p++; - if (p < buf_end && *p == '\n') p++; + p = csv_skip_eol(p, buf_end); /* LF, CRLF, CR or LFCR (#1891) */ } else if (col_names_in) { for (int c = 0; c < ncols; c++) col_name_ids[c] = col_names_in[c]; @@ -4445,7 +4565,7 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool if (delimiter == 0) { int commas = 0, tabs = 0; - for (const char* q = text; q < buf_end && *q != '\n'; q++) { + for (const char* q = text; q < buf_end && *q != '\n' && *q != '\r'; q++) { if (*q == ',') commas++; if (*q == '\t') tabs++; } @@ -4495,8 +4615,7 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool col_name_ids[c] = ray_sym_intern(fld, flen); if (dyn_esc) ray_sys_free(dyn_esc); } - if (p < buf_end && *p == '\r') p++; - if (p < buf_end && *p == '\n') p++; + p = csv_skip_eol(p, buf_end); /* LF, CRLF, CR or LFCR (#1891) */ } else if (col_names_in) { for (int c = 0; c < ncols; c++) col_name_ids[c] = col_names_in[c]; @@ -4897,7 +5016,7 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea if (delimiter == 0) { int commas = 0, tabs = 0; - for (const char* q = text; q < buf_end && *q != '\n'; q++) { + for (const char* q = text; q < buf_end && *q != '\n' && *q != '\r'; q++) { if (*q == ',') commas++; if (*q == '\t') tabs++; } @@ -4947,8 +5066,7 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea col_name_ids[c] = ray_sym_intern(fld, flen); if (dyn_esc) ray_sys_free(dyn_esc); } - if (p < buf_end && *p == '\r') p++; - if (p < buf_end && *p == '\n') p++; + p = csv_skip_eol(p, buf_end); /* LF, CRLF, CR or LFCR (#1891) */ } else if (col_names_in) { for (int c = 0; c < ncols; c++) col_name_ids[c] = col_names_in[c]; diff --git a/test/rfl/io/csv_line_ends.rfl b/test/rfl/io/csv_line_ends.rfl new file mode 100644 index 000000000..0224e568f --- /dev/null +++ b/test/rfl/io/csv_line_ends.rfl @@ -0,0 +1,80 @@ +;; @requires: posix (fixtures are written through a POSIX shell via .sys.exec) +;; Line ends (#1891): a row, and the header, ends at LF, CRLF, a lone CR or +;; LFCR, in any mix, with quotes in the file or without; inside a quoted cell +;; they are text. A file without quotes used to split at LF only, so a +;; CR-only file read as one row, and the header reader took CRLF but not +;; LFCR, so the first row after an LFCR header read as empty. +;; Fixtures use the rf_test_csvle_ prefix (the Makefile removes rf_test_*.csv). + +(.sys.exec "rm -rf rf_test_csvle_* rf_test_csvle_sp rf_test_csvle_pt") -- 0 + +;; ── CR line ends read the same with quotes in the file and without ───────── +(.sys.exec "printf 'a,b\\r1,2\\r3,4\\r' > rf_test_csvle_cr.csv; printf 'a,b\\r1,\"2\"\\r3,4\\r' > rf_test_csvle_crq.csv") -- 0 +(set T (.csv.read [I64 I64] "rf_test_csvle_cr.csv")) +(count T) -- 2 +(at T 'a) -- [1 3] +(at T 'b) -- [2 4] +(identical T (.csv.read [I64 I64] "rf_test_csvle_crq.csv")) -- true +;; inferred types see every row too +(at (.csv.read "rf_test_csvle_cr.csv") 'b) -- [2 4] + +;; ── an LFCR header no longer swallows the first row ──────────────────────── +(.sys.exec "printf 'a,b\\n\\r1,2\\n\\r3,4\\n\\r' > rf_test_csvle_lfcr.csv") -- 0 +(set L (.csv.read [I64 I64] "rf_test_csvle_lfcr.csv")) +(at L 'a) -- [1 3] +(at L 'b) -- [2 4] +(.sys.exec "printf 'a,b\\n\\r1,\"2\"\\n\\r3,4\\n\\r' > rf_test_csvle_lfcrq.csv") -- 0 +(identical L (.csv.read [I64 I64] "rf_test_csvle_lfcrq.csv")) -- true + +;; ── every kind of line end in one file ───────────────────────────────────── +;; LF, CRLF, CR, LFCR, then LF + CRLF (an empty line between) +(.sys.exec "printf 'a,b\\n1,2\\r\\n3,4\\r5,6\\n\\r7,8\\n\\r\\n9,10\\n' > rf_test_csvle_mix.csv") -- 0 +(set X (.csv.read [I64 I64] "rf_test_csvle_mix.csv")) +(at X 'a) -- [1 3 5 7 0Nl 9] +(at X 'b) -- [2 4 6 8 0Nl 10] +(.sys.exec "printf 'a,b\\n1,2\\r\\n3,4\\r5,6\\n\\r7,8\\n\\r\\n9,\"10\"\\n' > rf_test_csvle_mixq.csv") -- 0 +(identical X (.csv.read [I64 I64] "rf_test_csvle_mixq.csv")) -- true +;; strict counts each of them as a line +(.sys.exec "printf 'a,b\\n1,2\\r\\n3,4\\r5,6\\n\\r7,x\\n' > rf_test_csvle_mixbad.csv") -- 0 +(try (.csv.read {strict: true} [I64 I64] "rf_test_csvle_mixbad.csv") (fn [e] (at e 'msg))) -- ".csv.read \"rf_test_csvle_mixbad.csv\": line 5, column b: \"x\" is not an I64" + +;; ── inside quotes a CR or an LF is text, whatever the line ends are ──────── +(.sys.exec "printf 'a,b\\r\"x\\ry\",1\\r\"p\\r\\nq\",2\\r\"\\n\\r\",3\\r' > rf_test_csvle_qcr.csv") -- 0 +(set Q (.csv.read [STR I64] "rf_test_csvle_qcr.csv")) +(at Q 'a) -- (list "x\ry" "p\r\nq" "\n\r") +(at Q 'b) -- [1 2 3] + +;; ── what .csv.write writes reads back cell for cell ──────────────────────── +(set W (table [s n] (list (list "x\ry" "p\r\nq" "\n\r" "plain" "\r") [1 2 3 4 5]))) +(.csv.write W "rf_test_csvle_w.csv") +(identical (at (.csv.read [STR I64] "rf_test_csvle_w.csv") 's) (at W 's)) -- true + +;; ── past the parallel scan's 4 MB, with and without quotes ───────────────── +(.sys.exec "awk 'BEGIN{printf \"a,b\\r\"; for(i=1;i<=400000;i++) printf \"%d,%d\\r\", i, i%7}' > rf_test_csvle_bigcr.csv") -- 0 +(set B (.csv.read [I64 I64] "rf_test_csvle_bigcr.csv")) +(count B) -- 400000 +(sum (at B 'a)) -- 80000200000 +(.sys.exec "awk 'BEGIN{printf \"a,b\\n\\r\"; for(i=1;i<=400000;i++) printf \"%d,%d\\n\\r\", i, i%7}' > rf_test_csvle_biglfcr.csv") -- 0 +(set B2 (.csv.read [I64 I64] "rf_test_csvle_biglfcr.csv")) +(count B2) -- 400000 +(identical (at B 'b) (at B2 'b)) -- true +(.sys.exec "awk 'BEGIN{printf \"a,b\\r\"; for(i=1;i<=400000;i++) printf \"%d,\\\"%d\\\"\\r\", i, i%7}' > rf_test_csvle_bigcrq.csv") -- 0 +(identical B (.csv.read [I64 I64] "rf_test_csvle_bigcrq.csv")) -- true +;; LF and CRLF files take the fast scan as before +(.sys.exec "awk 'BEGIN{printf \"a,b\\r\\n\"; for(i=1;i<=400000;i++) printf \"%d,%d\\r\\n\", i, i%7}' > rf_test_csvle_bigcrlf.csv") -- 0 +(identical B (.csv.read [I64 I64] "rf_test_csvle_bigcrlf.csv")) -- true + +;; ── .csv.splayed and .csv.parted split rows the same way ─────────────────── +(set SP (.csv.splayed [I64 I64] "rf_test_csvle_bigcr.csv" "rf_test_csvle_sp")) +(count SP) -- 400000 +(sum (at SP 'a)) -- 80000200000 +(set PT (.csv.parted [I64 I64] "rf_test_csvle_biglfcr.csv" 150000 "rf_test_csvle_pt" 't)) +(count PT) -- 400000 +(count (.csv.splayed [I64 I64] "rf_test_csvle_mix.csv" "rf_test_csvle_sp")) -- 6 + +;; ── edges: a header alone, a last line without its CR ────────────────────── +(.sys.exec "printf 'a,b\\r' > rf_test_csvle_h.csv; printf 'a,b\\r1,2\\r3,4' > rf_test_csvle_nocr.csv") -- 0 +(count (.csv.read [I64 I64] "rf_test_csvle_h.csv")) -- 0 +(at (.csv.read [I64 I64] "rf_test_csvle_nocr.csv") 'b) -- [2 4] + +(.sys.exec "rm -rf rf_test_csvle_* rf_test_csvle_sp rf_test_csvle_pt") -- 0 diff --git a/test/rfl/io/csv_strict.rfl b/test/rfl/io/csv_strict.rfl index 757dd1f34..d0ec3a2a3 100644 --- a/test/rfl/io/csv_strict.rfl +++ b/test/rfl/io/csv_strict.rfl @@ -52,11 +52,11 @@ ;; a file with quotes splits rows at a lone CR as well (.sys.exec "printf 'a,b,c\\r1,\"x\",2.5\\r2,y\\r' > rf_test_csvst_cr.csv") -- 0 (M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cr.csv"))) -- ".csv.read \"rf_test_csvst_cr.csv\": line 3: expected 3 cells, got 2" -;; one without quotes splits at LF only and ends a cell at CR: lenient reads -;; one row and drops the text after its first CR, which strict refuses +;; and so does one without quotes (#1891): every row is read, and checked (.sys.exec "printf 'a,b,c\\r1,x,2.5\\r2,y,3.5\\r' > rf_test_csvst_cr2.csv") -- 0 -(count (.csv.read [I64 SYM F64] "rf_test_csvst_cr2.csv")) -- 1 -(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cr2.csv"))) -- ".csv.read \"rf_test_csvst_cr2.csv\": line 2: text after a CR inside the row (a row ends at LF or CRLF)" +(count (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cr2.csv")) -- 2 +(.sys.exec "printf 'a,b,c\\r1,x,2.5\\r2,y\\r' > rf_test_csvst_cr3.csv") -- 0 +(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cr3.csv"))) -- ".csv.read \"rf_test_csvst_cr3.csv\": line 3: expected 3 cells, got 2" ;; a bad cell that itself spans lines is reported at the line its row starts on (.sys.exec "printf 'a,b\\n\"1\\n2\",x\\n' > rf_test_csvst_qbad.csv") -- 0 (M (fn [] (.csv.read {strict: true} [I64 SYM] "rf_test_csvst_qbad.csv"))) -- ".csv.read \"rf_test_csvst_qbad.csv\": line 2, column a: \"1\\n2\" is not an I64" diff --git a/test/test_csv.c b/test/test_csv.c index 7c9ed50bd..1c87a2b77 100644 --- a/test/test_csv.c +++ b/test/test_csv.c @@ -2569,8 +2569,9 @@ static test_result_t test_csv_strict_matrix(void) { why = ", column v: text after the closing quote"; break; case 7: snprintf(bad, sizeof bad, "%%d,\"%s", tc->good); why = ", column v: a quoted cell with no closing quote"; break; - case 8: snprintf(bad, sizeof bad, "%%d,%s\rjunk", tc->good); - why = ": text after a CR inside the row"; break; + case 8: /* a lone CR ends the row (#1891): "junk" is the next, one cell */ + snprintf(bad, sizeof bad, "%%d,%s\rjunk", tc->good); + why = ": expected 2 cells, got 1"; break; case 9: case 10: { const char* u = rule == 9 ? tc->underflow : tc->underflow_neg; if (!u) continue; @@ -2588,7 +2589,8 @@ static test_result_t test_csv_strict_matrix(void) { ray_t* res = ray_read_csv_ex(path, ',', hdr, types, 2, hdr ? NULL : names, hdr ? 0 : 2, &opts); char head[128]; - snprintf(head, sizeof head, ".csv.read \"%s\": line %d", path, r + 1 + hdr); + snprintf(head, sizeof head, ".csv.read \"%s\": line %d", path, + r + 1 + hdr + (rule == 8)); const char* msg = res && RAY_IS_ERR(res) ? ray_err_msg(res) : NULL; bool good = msg && strcmp(ray_err_code(res), "parse") == 0 && strncmp(msg, head, strlen(head)) == 0 && strstr(msg, want); @@ -2716,6 +2718,196 @@ static test_result_t test_csv_escaped_alloc_fail(void) { PASS(); } +/* The strict error's line counts line ends as the reader splits rows (#1895 + * review): every pair and triple of LF, CRLF, CR and LFCR placed back to + * back between a valid row and a bad one, in a one-column file where each + * empty line is a row, so the bad row's line is the number of rows the + * lenient reader finds; with quotes in the file and without. */ +static test_result_t test_csv_strict_line_ends(void) { + ray_heap_init(); + (void)ray_sym_init(); + static const char* const ends[4] = { "\n", "\r\n", "\r", "\n\r" }; + const char* path = TMP_CSV; + int64_t name = ray_sym_intern("v", 1); + int8_t i64[1] = { RAY_I64 }, str[1] = { RAY_STR }; + char msg[512]; + int checked = 0; + for (int k = 2; k <= 3; k++) { + int combos = k == 2 ? 16 : 64; + for (int c = 0; c < combos; c++) { + for (int quoted = 0; quoted < 2; quoted++) { + char text[64]; + int o = snprintf(text, sizeof text, "%s", quoted ? "\"1\"" : "1"); + for (int j = 0, x = c; j < k; j++, x /= 4) + o += snprintf(text + o, sizeof text - (size_t)o, "%s", ends[x % 4]); + snprintf(text + o, sizeof text - (size_t)o, "x"); + FILE* f = fopen(path, "wb"); + TEST_ASSERT_TRUE(f != NULL); + fputs(text, f); + fclose(f); + ray_t* lenient = ray_read_csv_ex(path, ',', false, str, 1, &name, 1, NULL); + TEST_ASSERT_TRUE(lenient && !RAY_IS_ERR(lenient)); + int64_t rows = ray_table_nrows(lenient); + ray_release(lenient); + ray_csv_opts_t opts = { .strict = true, .op = ".csv.read" }; + ray_t* res = ray_read_csv_ex(path, ',', false, i64, 1, &name, 1, &opts); + char want[160]; + snprintf(want, sizeof want, ".csv.read \"%s\": line %lld, column v: \"x\"", + path, (long long)rows); + const char* got = res && RAY_IS_ERR(res) ? ray_err_msg(res) : "no error"; + if (strncmp(got, want, strlen(want)) != 0) { + char shown[128]; size_t so = 0; + for (const char* q = text; *q && so + 4 < sizeof shown; q++) + so += (size_t)snprintf(shown + so, sizeof shown - so, *q == '\n' ? "\\n" : *q == '\r' ? "\\r" : "%c", *q); + snprintf(msg, sizeof msg, "%s: got %s; want %s", shown, got, want); + if (res && RAY_IS_ERR(res)) ray_error_free(res); else if (res) ray_release(res); + FAIL(strdup(msg)); + } + ray_error_free(res); + checked++; + } + } + } + unlink(path); + ray_sym_destroy(); + ray_heap_destroy(); + TEST_ASSERT_EQ_I(checked, 160); + PASS(); +} + +/* Line ends against a reference written from the rule (#1895): "line ends + * are read greedily left to right, a CRLF or an LFCR whenever the byte at + * the position starts one, else the one byte". Files of cells (digits, + * quoted digits, quoted text holding line ends) between runs of 1 to 4 + * line-end bytes, every such run among them; read as one STR column, rows + * and cells must be the reference's, and a malformed last row must be + * reported at the reference's line. Small files take the serial scan, + * larger ones the parallel one, whose 64-byte test chunks then split runs. */ +static size_t le_ref_len(const char* t, size_t i, size_t n) { + return (i + 1 < n && (t[i + 1] == '\n' || t[i + 1] == '\r') && t[i + 1] != t[i]) ? 2 : 1; +} + +static uint32_t le_rand(uint32_t* s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; } + +static test_result_t test_csv_line_end_reference(void) { + ray_heap_init(); + (void)ray_sym_init(); + const char* path = TMP_CSV; + int64_t name = ray_sym_intern("v", 1); + int8_t str[1] = { RAY_STR }; + size_t cap = 1 << 20; + char* t = (char*)malloc(cap); + size_t* rs = (size_t*)malloc(sizeof(size_t) * 200000); + size_t* re = (size_t*)malloc(sizeof(size_t) * 200000); + char msg[512]; + TEST_ASSERT_TRUE(t && rs && re); + int checked = 0; + /* big 0: serial; 1: parallel; 2: parallel with long runs (up to 3000 + * bytes, alternating, of one byte, or random), so that several chunk + * boundaries fall inside one run */ + for (int big = 0; big < 3; big++) { + for (int seed = 1; seed <= 20; seed++) { + for (int strict = 0; strict < 2; strict++) { + uint32_t st = (uint32_t)(seed * 7919 + big * 104729 + strict); + int rows = big == 2 ? 120 : big ? 3000 : 60; + size_t n = 0; + for (int r = 0; r < rows; r++) { + uint32_t k = le_rand(&st) % 6; + if (k < 3) n += (size_t)snprintf(t + n, cap - n, "%u", le_rand(&st) % 100000); + else if (k < 5) n += (size_t)snprintf(t + n, cap - n, "\"%u\"", le_rand(&st) % 1000); + else { /* quoted text with line ends in it */ + t[n++] = '"'; t[n++] = 'q'; + for (uint32_t j = 1 + le_rand(&st) % 4; j > 0; j--) t[n++] = (le_rand(&st) & 1) ? '\n' : '\r'; + t[n++] = 'q'; t[n++] = '"'; + } + /* the run after the cell: each of the 30 runs of 1-4 bytes + * in turn, then random ones */ + if (big == 2 && le_rand(&st) % 3 == 0) { + uint32_t len = 1 + le_rand(&st) % 3000, kind = le_rand(&st) % 3; + char first = (le_rand(&st) & 1) ? '\r' : '\n'; + for (uint32_t j = 0; j < len; j++) + t[n++] = kind == 0 ? ((j & 1) ? (first == '\r' ? '\n' : '\r') : first) + : kind == 1 ? first + : ((le_rand(&st) & 1) ? '\r' : '\n'); + continue; + } + uint32_t len, bits; + if (r < 30) { len = r < 2 ? 1 : r < 6 ? 2 : r < 14 ? 3 : 4; + bits = (uint32_t)(r - (len == 1 ? 0 : len == 2 ? 2 : len == 3 ? 6 : 14)); } + else { len = 1 + le_rand(&st) % 4; bits = le_rand(&st); } + for (uint32_t j = 0; j < len; j++) t[n++] = ((bits >> j) & 1) ? '\r' : '\n'; + } + size_t bad_at = n; + if (strict) n += (size_t)snprintf(t + n, cap - n, "\"x\"y"); + else n += (size_t)snprintf(t + n, cap - n, "%u", 7u); + /* the reference: rows, and the line of the last row */ + size_t nr = 0, i = 0, start = 0; + bool inq = false; + while (i < n) { + char c = t[i]; + if (c == '"') { inq = !inq; i++; } + else if (!inq && (c == '\n' || c == '\r')) { + rs[nr] = start; re[nr] = i; nr++; + i += le_ref_len(t, i, n); + start = i; + } else i++; + } + if (start < n) { rs[nr] = start; re[nr] = n; nr++; } + int64_t line = 1; + for (size_t q = 0; q < bad_at; ) { + if (t[q] == '\n' || t[q] == '\r') { line++; q += le_ref_len(t, q, n); } else q++; + } + FILE* f = fopen(path, "wb"); + TEST_ASSERT_TRUE(f != NULL); + fwrite(t, 1, n, f); + fclose(f); + if (!strict) { + ray_t* tb = ray_read_csv_ex(path, ',', false, str, 1, &name, 1, NULL); + TEST_ASSERT_TRUE(tb && !RAY_IS_ERR(tb)); + bool same = ray_table_nrows(tb) == (int64_t)nr; + ray_t* col = ray_table_get_col_idx(tb, 0); + for (size_t r = 0; same && r < nr; r++) { + const char* a = t + rs[r]; size_t al = re[r] - rs[r]; + if (al >= 2 && a[0] == '"' && a[al - 1] == '"') { a++; al -= 2; } + size_t bl = 0; + const char* b = ray_str_vec_get(col, (int64_t)r, &bl); + same = bl == al && (al == 0 || memcmp(a, b, al) == 0); + if (!same) { + snprintf(msg, sizeof msg, "%s seed %d: row %zu differs from the reference (%zu rows)", + big == 2 ? "long runs" : big ? "parallel" : "serial", seed, r, nr); + } + } + if (ray_table_nrows(tb) != (int64_t)nr) + snprintf(msg, sizeof msg, "%s seed %d: %lld rows, reference %zu", + big == 2 ? "long runs" : big ? "parallel" : "serial", seed, (long long)ray_table_nrows(tb), nr); + ray_release(tb); + if (!same) FAIL(strdup(msg)); + } else { + ray_csv_opts_t opts = { .strict = true, .op = ".csv.read" }; + ray_t* res = ray_read_csv_ex(path, ',', false, str, 1, &name, 1, &opts); + char want[160]; + snprintf(want, sizeof want, ".csv.read \"%s\": line %lld, column v: text after the closing quote", + path, (long long)line); + const char* got = res && RAY_IS_ERR(res) ? ray_err_msg(res) : "no error"; + if (strcmp(got, want) != 0) { + snprintf(msg, sizeof msg, "%s seed %d: got %s; want %s", big == 2 ? "long runs" : big ? "parallel" : "serial", seed, got, want); + if (res && RAY_IS_ERR(res)) ray_error_free(res); else if (res) ray_release(res); + FAIL(strdup(msg)); + } + ray_error_free(res); + } + checked++; + } + } + } + free(t); free(rs); free(re); + unlink(path); + ray_sym_destroy(); + ray_heap_destroy(); + TEST_ASSERT_EQ_I(checked, 120); + PASS(); +} + const test_entry_t csv_entries[] = { { "csv/splayed_cancel", test_csv_splayed_cancel, NULL, NULL }, { "csv/splayed_cancel_hash", test_csv_splayed_cancel_hash, NULL, NULL }, @@ -2785,5 +2977,7 @@ const test_entry_t csv_entries[] = { { "csv/streaming_infers_like_read", test_csv_streaming_infers_like_read, NULL, NULL }, { "csv/strict_matrix", test_csv_strict_matrix, NULL, NULL }, { "csv/escaped_alloc_fail", test_csv_escaped_alloc_fail, NULL, NULL }, + { "csv/strict_line_ends", test_csv_strict_line_ends, NULL, NULL }, + { "csv/line_end_reference", test_csv_line_end_reference, NULL, NULL }, { NULL, NULL, NULL, NULL }, };