zsv 1.4.3 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +140 -2
  3. data/README.md +129 -275
  4. data/ext/zsv/ZSV_UPSTREAM +7 -0
  5. data/ext/zsv/common.h +0 -12
  6. data/ext/zsv/extconf.rb +70 -122
  7. data/ext/zsv/options.c +63 -62
  8. data/ext/zsv/options.h +8 -11
  9. data/ext/zsv/parser.c +390 -201
  10. data/ext/zsv/parser.h +35 -22
  11. data/ext/zsv/row.c +75 -28
  12. data/ext/zsv/row.h +15 -9
  13. data/ext/zsv/upstream.rb +55 -0
  14. data/ext/zsv/vendor/zsv/LICENSE +21 -0
  15. data/ext/zsv/vendor/zsv/VENDORED_FROM +2 -0
  16. data/ext/zsv/vendor/zsv/configure +1212 -0
  17. data/ext/zsv/vendor/zsv/include/zsv/api.h +375 -0
  18. data/ext/zsv/vendor/zsv/include/zsv/common.h +397 -0
  19. data/ext/zsv/vendor/zsv/include/zsv/ext/implementation.h +62 -0
  20. data/ext/zsv/vendor/zsv/include/zsv/ext/implementation_private.h +113 -0
  21. data/ext/zsv/vendor/zsv/include/zsv/ext/sheet.h +80 -0
  22. data/ext/zsv/vendor/zsv/include/zsv/ext.h +333 -0
  23. data/ext/zsv/vendor/zsv/include/zsv/utils/appname.h +51 -0
  24. data/ext/zsv/vendor/zsv/include/zsv/utils/arg.h +139 -0
  25. data/ext/zsv/vendor/zsv/include/zsv/utils/cache.h +49 -0
  26. data/ext/zsv/vendor/zsv/include/zsv/utils/clock.h +36 -0
  27. data/ext/zsv/vendor/zsv/include/zsv/utils/compiler.h +69 -0
  28. data/ext/zsv/vendor/zsv/include/zsv/utils/db.h +19 -0
  29. data/ext/zsv/vendor/zsv/include/zsv/utils/dirs.h +149 -0
  30. data/ext/zsv/vendor/zsv/include/zsv/utils/dl.h +22 -0
  31. data/ext/zsv/vendor/zsv/include/zsv/utils/emcc/fs_api.h +28 -0
  32. data/ext/zsv/vendor/zsv/include/zsv/utils/err.h +22 -0
  33. data/ext/zsv/vendor/zsv/include/zsv/utils/file-mem.h +18 -0
  34. data/ext/zsv/vendor/zsv/include/zsv/utils/file.h +125 -0
  35. data/ext/zsv/vendor/zsv/include/zsv/utils/jq.h +65 -0
  36. data/ext/zsv/vendor/zsv/include/zsv/utils/json.h +19 -0
  37. data/ext/zsv/vendor/zsv/include/zsv/utils/mem.h +19 -0
  38. data/ext/zsv/vendor/zsv/include/zsv/utils/memmem.h +13 -0
  39. data/ext/zsv/vendor/zsv/include/zsv/utils/os.h +145 -0
  40. data/ext/zsv/vendor/zsv/include/zsv/utils/output.h +34 -0
  41. data/ext/zsv/vendor/zsv/include/zsv/utils/overwrite.h +71 -0
  42. data/ext/zsv/vendor/zsv/include/zsv/utils/overwrite_writer.h +53 -0
  43. data/ext/zsv/vendor/zsv/include/zsv/utils/prop.h +119 -0
  44. data/ext/zsv/vendor/zsv/include/zsv/utils/rng.h +35 -0
  45. data/ext/zsv/vendor/zsv/include/zsv/utils/signal.h +25 -0
  46. data/ext/zsv/vendor/zsv/include/zsv/utils/sql.h +13 -0
  47. data/ext/zsv/vendor/zsv/include/zsv/utils/string.h +173 -0
  48. data/ext/zsv/vendor/zsv/include/zsv/utils/utf8.h +41 -0
  49. data/ext/zsv/vendor/zsv/include/zsv/utils/win/dl.h +25 -0
  50. data/ext/zsv/vendor/zsv/include/zsv/utils/writer.h +109 -0
  51. data/ext/zsv/vendor/zsv/include/zsv/zsv_export.h +33 -0
  52. data/ext/zsv/vendor/zsv/include/zsv.h.in +18 -0
  53. data/ext/zsv/vendor/zsv/src/Makefile +238 -0
  54. data/ext/zsv/vendor/zsv/src/vector_delim.c +60 -0
  55. data/ext/zsv/vendor/zsv/src/zsv.c +622 -0
  56. data/ext/zsv/vendor/zsv/src/zsv_internal.c +789 -0
  57. data/ext/zsv/vendor/zsv/src/zsv_scan_delim.c +285 -0
  58. data/ext/zsv/vendor/zsv/src/zsv_scan_delim_fast.c +741 -0
  59. data/ext/zsv/vendor/zsv/src/zsv_scan_fixed.c +88 -0
  60. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_avx2.h +89 -0
  61. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_neon.h +80 -0
  62. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_sse2.h +93 -0
  63. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_wasm.h +79 -0
  64. data/ext/zsv/vendor/zsv/src/zsv_strencode.c +84 -0
  65. data/ext/zsv/zsv_ext.c +176 -105
  66. data/lib/zsv/errors.rb +32 -0
  67. data/lib/zsv/input.rb +88 -0
  68. data/lib/zsv/options.rb +132 -0
  69. data/lib/zsv/strict_validator.rb +124 -0
  70. data/lib/zsv/version.rb +1 -1
  71. data/lib/zsv.rb +137 -35
  72. metadata +82 -11
data/ext/zsv/parser.c CHANGED
@@ -1,314 +1,503 @@
1
- /* Parser wrapper implementation using zsv's callback API */
1
+ /* Parser wrapper implementation using zsv's callback API
2
+ *
3
+ * zsv pushes rows into zsv_row_handler() from inside zsv_parse_more(). Ruby
4
+ * code that can raise (allocation, Hash#[]= on custom header objects, IO#read)
5
+ * therefore runs below zsv's C frames. A longjmp through those frames would
6
+ * leave zsv half-way through a buffer, so every callback runs its Ruby code
7
+ * under rb_protect(), records the jump state, and returns normally; the
8
+ * exception is re-raised once control is back in our code, after the parser
9
+ * has been closed.
10
+ *
11
+ * Row size: zsv holds a row in one buffer and, when a row fills it, warns
12
+ * through errprintf and hands the row on cut short. The buffer is therefore
13
+ * sized to hold any row of max_row_size bytes, the row handler raises for a
14
+ * longer one, and the truncation warning raises too, so no row is ever
15
+ * returned incomplete. zsv's overflow_row_handler is not used: zsv 1.4.4 calls
16
+ * it with its own scanner as the context instead of ours. */
2
17
  #include "parser.h"
3
- #include <errno.h>
4
18
  #include <string.h>
5
19
 
6
- /* Forward declarations */
7
- static void zsv_parser_init_common(zsv_ruby_parser_t *parser, VALUE opts_hash);
8
- static void zsv_parser_finish_safe(zsv_ruby_parser_t *parser);
20
+ static ID id_read;
21
+ static ID id_rewind;
9
22
 
10
- /* Row handler callback for zsv */
11
- static void zsv_row_handler(void *ctx)
23
+ static void zsv_parser_create_zsv(zsv_ruby_parser_t *parser);
24
+
25
+ void zsv_parser_init_struct(zsv_ruby_parser_t *parser)
12
26
  {
13
- zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)ctx;
27
+ memset(parser, 0, sizeof(*parser));
28
+ parser->source = Qnil;
29
+ parser->row_buffer = Qnil;
30
+ parser->headers = Qnil;
31
+ zsv_options_init(&parser->options);
32
+ }
14
33
 
15
- /* Don't allocate Ruby objects during cleanup/GC */
16
- if (parser->in_cleanup) {
17
- return;
34
+ /* ---- GC support ---------------------------------------------------------- */
35
+
36
+ /* The zsv buffer: the requested read size, but always room for a row of
37
+ * max_row_size bytes plus the byte that ends it. zsv only cuts a row short
38
+ * when the row alone fills the buffer. */
39
+ static size_t zsv_parser_buffer_size(const zsv_ruby_options_t *options)
40
+ {
41
+ size_t row_buffer = (size_t)options->max_row_size + 1;
42
+ if (row_buffer == 0) { /* 32-bit size_t and max_row_size == UINT_MAX */
43
+ row_buffer = SIZE_MAX;
18
44
  }
45
+ return options->buffer_size > row_buffer ? options->buffer_size : row_buffer;
46
+ }
19
47
 
20
- /* Reset row builder for new row */
21
- zsv_row_builder_reset(parser->row_builder);
48
+ void zsv_parser_mark(zsv_ruby_parser_t *parser)
49
+ {
50
+ rb_gc_mark_movable(parser->source);
51
+ rb_gc_mark_movable(parser->row_buffer);
52
+ rb_gc_mark_movable(parser->headers);
53
+ rb_gc_mark_movable(parser->options.header_array);
54
+ if (parser->row_builder) {
55
+ zsv_row_builder_mark(parser->row_builder);
56
+ }
57
+ }
22
58
 
23
- /* Get all cells in this row */
24
- size_t cell_count = zsv_cell_count(parser->zsv);
59
+ void zsv_parser_compact(zsv_ruby_parser_t *parser)
60
+ {
61
+ parser->source = rb_gc_location(parser->source);
62
+ parser->row_buffer = rb_gc_location(parser->row_buffer);
63
+ parser->headers = rb_gc_location(parser->headers);
64
+ parser->options.header_array = rb_gc_location(parser->options.header_array);
65
+ if (parser->row_builder) {
66
+ zsv_row_builder_compact(parser->row_builder);
67
+ }
68
+ }
69
+
70
+ size_t zsv_parser_memsize(const zsv_ruby_parser_t *parser)
71
+ {
72
+ size_t size = sizeof(*parser);
73
+ if (parser->row_builder) {
74
+ size += zsv_row_builder_memsize(parser->row_builder);
75
+ }
76
+ if (parser->zsv) {
77
+ size += zsv_parser_buffer_size(&parser->options);
78
+ }
79
+ return size;
80
+ }
81
+
82
+ /* ---- zsv callbacks --------------------------------------------------------- */
83
+
84
+ /* An empty unquoted line: CSV returns [] for it, not [""] */
85
+ static bool zsv_parser_blank_row(zsv_ruby_parser_t *parser, size_t cell_count)
86
+ {
87
+ if (cell_count == 0) {
88
+ return true;
89
+ }
90
+ if (cell_count != 1) {
91
+ return false;
92
+ }
93
+ struct zsv_cell cell = zsv_get_cell(parser->zsv, 0);
94
+ return cell.len == 0 && !(cell.quoted & ZSV_PARSER_QUOTE_CLOSED);
95
+ }
96
+
97
+ static void zsv_parser_build_row(zsv_ruby_parser_t *parser, size_t cell_count)
98
+ {
99
+ zsv_row_builder_reset(parser->row_builder);
25
100
  for (size_t i = 0; i < cell_count; i++) {
26
101
  struct zsv_cell cell = zsv_get_cell(parser->zsv, i);
27
102
  zsv_row_builder_add_cell(parser->row_builder, cell.str, cell.len);
28
103
  }
104
+ }
105
+
106
+ /* Raise ZSV::MalformedCSVError for the current record; its #line_number is the
107
+ * 1-based record, as in CSV ("... in line N.") */
108
+ static void zsv_parser_raise_malformed(zsv_ruby_parser_t *parser, VALUE message)
109
+ {
110
+ VALUE args[2] = {message, SIZET2NUM(parser->record_count)};
111
+ rb_exc_raise(rb_class_new_instance(2, args, eMalformedCSVError));
112
+ }
113
+
114
+ static VALUE zsv_row_handler_body(VALUE arg)
115
+ {
116
+ zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)arg;
117
+ parser->record_count++;
118
+
119
+ if (parser->row_truncated ||
120
+ zsv_row_length_raw_bytes(parser->zsv) > parser->options.max_row_size) {
121
+ zsv_parser_raise_malformed(parser, rb_sprintf("Row longer than max_row_size (%u bytes)",
122
+ parser->options.max_row_size));
123
+ }
124
+ if (parser->column_overflow) {
125
+ zsv_parser_raise_malformed(parser, rb_sprintf("Row with more than max_columns (%u) fields",
126
+ parser->options.max_columns));
127
+ }
29
128
 
30
129
  /* Skip lines if configured */
31
130
  if (parser->lines_skipped < (size_t)parser->options.skip_lines) {
32
131
  parser->lines_skipped++;
33
- return;
132
+ return Qnil;
34
133
  }
35
134
 
36
- /* Process header row - only if headers:true and no custom headers provided */
37
- if (parser->options.headers && NIL_P(parser->options.header_array) &&
38
- !parser->header_row_processed) {
135
+ size_t cell_count = zsv_cell_count(parser->zsv);
136
+ bool blank = zsv_parser_blank_row(parser, cell_count);
137
+
138
+ /* Header row - only if headers: true and no custom headers provided.
139
+ * Blank lines before it are skipped. */
140
+ if (parser->options.headers && !parser->header_row_processed) {
141
+ if (blank) {
142
+ return Qnil;
143
+ }
144
+ zsv_parser_build_row(parser, cell_count);
39
145
  parser->headers = zsv_row_builder_to_array(parser->row_builder);
40
146
  zsv_row_builder_set_headers(parser->row_builder, parser->headers);
41
147
  parser->header_row_processed = true;
42
- return; /* Don't store header row */
148
+ return Qnil;
43
149
  }
44
150
 
45
- /* Build row as array or hash */
46
- VALUE row;
47
- if (!NIL_P(parser->headers)) {
48
- row = zsv_row_builder_to_hash(parser->row_builder);
49
- } else {
50
- row = zsv_row_builder_to_array(parser->row_builder);
51
- }
151
+ zsv_parser_build_row(parser, blank ? 0 : cell_count);
52
152
 
53
- /* Add row to buffer */
153
+ VALUE row = NIL_P(parser->headers) ? zsv_row_builder_to_array(parser->row_builder)
154
+ : zsv_row_builder_to_hash(parser->row_builder);
54
155
  rb_ary_push(parser->row_buffer, row);
55
- parser->row_count++;
156
+ return Qnil;
56
157
  }
57
158
 
58
- /* Initialize common parser setup */
59
- static void zsv_parser_init_common(zsv_ruby_parser_t *parser, VALUE opts_hash)
159
+ static void zsv_row_handler(void *ctx)
60
160
  {
61
- /* Parse options */
62
- zsv_options_parse(opts_hash, &parser->options);
161
+ zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)ctx;
162
+ if (parser->exception_state) {
163
+ return; /* an earlier callback raised; drop the rest of this chunk */
164
+ }
165
+ rb_protect(zsv_row_handler_body, (VALUE)parser, &parser->exception_state);
166
+ }
63
167
 
64
- /* Create row builder */
65
- parser->row_builder = zsv_row_builder_new(parser->options.encoding);
168
+ /* zsv prints warnings to stderr. Silence them, and turn the two that mean
169
+ * data loss into errors: both are printed just before the damaged row reaches
170
+ * zsv_row_handler, which raises. */
171
+ static int zsv_errprintf(void *ctx, const char *format, ...)
172
+ {
173
+ zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)ctx;
174
+ if (strstr(format, "exceeds row max") != NULL) {
175
+ parser->column_overflow = true; /* columns beyond max_columns dropped */
176
+ } else if (strstr(format, "truncated") != NULL) {
177
+ parser->row_truncated = true; /* a row that filled the whole buffer */
178
+ }
179
+ return 0;
180
+ }
181
+
182
+ static size_t zsv_string_read(void *buffer, size_t size, size_t count, void *ctx)
183
+ {
184
+ zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)ctx;
185
+ if (size == 0) {
186
+ return 0;
187
+ }
188
+
189
+ /* The source is frozen, so its length cannot change between reads. The
190
+ * pointer is re-read on every call because GC compaction may move it. */
191
+ size_t length = RSTRING_LEN(parser->source);
192
+ size_t available = length - parser->source_offset;
193
+ size_t copied = available < size * count ? available : size * count;
194
+ copied -= copied % size;
195
+
196
+ memcpy(buffer, RSTRING_PTR(parser->source) + parser->source_offset, copied);
197
+ parser->source_offset += copied;
198
+ return copied / size;
199
+ }
200
+
201
+ typedef struct {
202
+ zsv_ruby_parser_t *parser;
203
+ size_t requested;
204
+ } zsv_io_read_args_t;
205
+
206
+ static VALUE zsv_io_read_chunk(VALUE arg)
207
+ {
208
+ zsv_io_read_args_t *args = (zsv_io_read_args_t *)arg;
209
+ VALUE io = args->parser->source;
210
+ VALUE chunk = rb_funcall(io, id_read, 1, SIZET2NUM(args->requested));
211
+
212
+ if (NIL_P(chunk)) {
213
+ return Qnil;
214
+ }
215
+ StringValue(chunk);
216
+ if ((size_t)RSTRING_LEN(chunk) > args->requested) {
217
+ rb_raise(rb_eIOError, "%s#read returned more bytes than requested", rb_obj_classname(io));
218
+ }
219
+ return chunk;
220
+ }
221
+
222
+ static size_t zsv_io_read(void *buffer, size_t size, size_t count, void *ctx)
223
+ {
224
+ zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)ctx;
225
+ if (parser->exception_state || size == 0 || count == 0) {
226
+ return 0;
227
+ }
228
+
229
+ zsv_io_read_args_t args = {parser, size * count};
230
+ VALUE chunk = rb_protect(zsv_io_read_chunk, (VALUE)&args, &parser->exception_state);
231
+ if (parser->exception_state || NIL_P(chunk)) {
232
+ return 0; /* zsv sees EOF; the driver re-raises the exception */
233
+ }
234
+
235
+ size_t length = RSTRING_LEN(chunk);
236
+ memcpy(buffer, RSTRING_PTR(chunk), length);
237
+ RB_GC_GUARD(chunk);
238
+ return length / size;
239
+ }
240
+
241
+ /* ---- setup ------------------------------------------------------------------ */
242
+
243
+ static void zsv_parser_create_zsv(zsv_ruby_parser_t *parser)
244
+ {
245
+ struct zsv_opts zopts;
246
+ memset(&zopts, 0, sizeof(zopts));
66
247
 
67
- /* Initialize zsv parser with callback */
68
- struct zsv_opts zopts = {0};
69
248
  zopts.delimiter = parser->options.delimiter;
249
+ zopts.buffsize = zsv_parser_buffer_size(&parser->options);
250
+ /* zsv only uses max_row_size to grow buffsize to twice its value: pass
251
+ * half the buffer so zsv keeps ours (and its unsigned doubling cannot
252
+ * wrap); the row limit itself is enforced by zsv_row_handler_body */
253
+ zopts.max_row_size =
254
+ (unsigned)(zopts.buffsize / 2 < UINT_MAX / 2 ? zopts.buffsize / 2 : UINT_MAX / 2);
255
+ zopts.max_columns = parser->options.max_columns;
256
+ zopts.keep_empty_header_rows = 1; /* we handle blank lines ourselves */
70
257
  zopts.row_handler = zsv_row_handler;
71
258
  zopts.ctx = parser;
259
+ zopts.errprintf = zsv_errprintf;
260
+ zopts.errf = parser;
261
+
262
+ switch (parser->source_kind) {
263
+ case ZSV_SOURCE_FILE:
264
+ zopts.stream = parser->file; /* default reader is fread() */
265
+ break;
266
+ case ZSV_SOURCE_STRING:
267
+ zopts.read = zsv_string_read;
268
+ zopts.stream = parser;
269
+ break;
270
+ case ZSV_SOURCE_IO:
271
+ zopts.read = zsv_io_read;
272
+ zopts.stream = parser;
273
+ break;
274
+ case ZSV_SOURCE_NONE:
275
+ rb_raise(eZSVError, "parser has no input source");
276
+ }
72
277
 
73
- if (parser->file) {
74
- zopts.stream = parser->file;
75
- parser->zsv = zsv_new(&zopts);
76
- } else {
77
- /* IO object handling would require custom read callback */
78
- rb_raise(rb_eNotImpError, "IO object parsing not yet implemented");
278
+ parser->zsv = zsv_new(&zopts);
279
+ if (!parser->zsv) {
280
+ parser->closed = true;
281
+ rb_raise(rb_eNoMemError, "failed to create zsv parser");
79
282
  }
283
+ }
80
284
 
81
- /* Set headers: use custom headers if provided, otherwise will be read from first row */
285
+ static void zsv_parser_reset_state(zsv_ruby_parser_t *parser)
286
+ {
287
+ parser->record_count = 0;
288
+ parser->lines_skipped = 0;
289
+ parser->eof_reached = false;
290
+ parser->column_overflow = false;
291
+ parser->row_truncated = false;
292
+ parser->exception_state = 0;
293
+ parser->row_buffer = rb_ary_new();
294
+
295
+ /* Custom headers skip the first row; otherwise it is read as the header */
82
296
  if (!NIL_P(parser->options.header_array)) {
83
297
  parser->headers = parser->options.header_array;
84
- zsv_row_builder_set_headers(parser->row_builder, parser->headers);
85
- parser->header_row_processed = true; /* Skip reading headers from file */
298
+ parser->header_row_processed = true;
86
299
  } else {
87
300
  parser->headers = Qnil;
301
+ parser->header_row_processed = false;
88
302
  }
89
-
90
- parser->row_buffer = rb_ary_new();
91
- parser->closed = false;
92
- parser->eof_reached = false;
93
- parser->in_cleanup = false;
94
- parser->current_row = Qnil;
303
+ zsv_row_builder_set_headers(parser->row_builder, parser->headers);
95
304
  }
96
305
 
97
- /* Create parser from file path */
98
- zsv_ruby_parser_t *zsv_parser_new_from_path(const char *path, VALUE opts_hash)
306
+ /* Parse options and allocate Ruby-side state. Runs before any OS resource is
307
+ * acquired so an invalid option cannot leak a FILE*. */
308
+ static void zsv_parser_setup(zsv_ruby_parser_t *parser, VALUE opts_hash)
99
309
  {
100
- zsv_ruby_parser_t *parser = ZSV_ALLOC(zsv_ruby_parser_t);
101
- memset(parser, 0, sizeof(zsv_ruby_parser_t));
102
-
103
- /* Open file */
104
- parser->file = fopen(path, "rb");
105
- if (!parser->file) {
106
- xfree(parser);
107
- rb_sys_fail(path);
310
+ /* row_builder is set once setup has run, even when the open that follows
311
+ * failed: a second initialize would otherwise leak the first builder */
312
+ if (parser->source_kind != ZSV_SOURCE_NONE || parser->row_builder) {
313
+ rb_raise(rb_eRuntimeError, "ZSV::Parser is already initialized");
108
314
  }
109
315
 
110
- zsv_parser_init_common(parser, opts_hash);
111
- return parser;
316
+ zsv_options_parse(opts_hash, &parser->options);
317
+ parser->row_builder = zsv_row_builder_new(parser->options.encoding);
318
+ zsv_parser_reset_state(parser);
112
319
  }
113
320
 
114
- /* Create parser from Ruby IO */
115
- zsv_ruby_parser_t *zsv_parser_new_from_io(VALUE io, VALUE opts_hash)
321
+ void zsv_parser_init_path(zsv_ruby_parser_t *parser, VALUE path, VALUE opts_hash)
116
322
  {
117
- zsv_ruby_parser_t *parser = ZSV_ALLOC(zsv_ruby_parser_t);
118
- memset(parser, 0, sizeof(zsv_ruby_parser_t));
323
+ FilePathValue(path);
324
+ zsv_parser_setup(parser, opts_hash);
119
325
 
120
- parser->io = io;
121
- zsv_parser_init_common(parser, opts_hash);
326
+ parser->file = fopen(RSTRING_PTR(path), "rb");
327
+ RB_GC_GUARD(path);
328
+ if (!parser->file) {
329
+ rb_sys_fail_str(path);
330
+ }
331
+ parser->source_kind = ZSV_SOURCE_FILE;
332
+ zsv_parser_create_zsv(parser);
333
+ }
122
334
 
123
- return parser;
335
+ void zsv_parser_init_string(zsv_ruby_parser_t *parser, VALUE string, VALUE opts_hash)
336
+ {
337
+ StringValue(string);
338
+ zsv_parser_setup(parser, opts_hash);
339
+
340
+ /* A frozen copy (sharing the buffer) so mutating the caller's string
341
+ * during the parse cannot free or change the bytes zsv is reading */
342
+ parser->source = rb_str_new_frozen(string);
343
+ parser->source_kind = ZSV_SOURCE_STRING;
344
+ zsv_parser_create_zsv(parser);
124
345
  }
125
346
 
126
- /* Create parser from string */
127
- zsv_ruby_parser_t *zsv_parser_new_from_string(VALUE string, VALUE opts_hash)
347
+ void zsv_parser_init_io(zsv_ruby_parser_t *parser, VALUE io, VALUE opts_hash)
128
348
  {
129
- Check_Type(string, T_STRING);
349
+ if (!rb_respond_to(io, id_read)) {
350
+ rb_raise(rb_eTypeError, "expected an IO-like object responding to #read, got %s",
351
+ rb_obj_classname(io));
352
+ }
353
+ zsv_parser_setup(parser, opts_hash);
130
354
 
131
- zsv_ruby_parser_t *parser = ZSV_ALLOC(zsv_ruby_parser_t);
132
- memset(parser, 0, sizeof(zsv_ruby_parser_t));
355
+ parser->source = io;
356
+ parser->source_kind = ZSV_SOURCE_IO;
357
+ zsv_parser_create_zsv(parser);
358
+ }
133
359
 
134
- /* Create memory-backed file */
135
- const char *str_ptr = RSTRING_PTR(string);
136
- size_t str_len = RSTRING_LEN(string);
360
+ /* ---- teardown --------------------------------------------------------------- */
137
361
 
138
- /* Handle empty string - fmemopen(ptr, 0, ...) fails on macOS */
139
- if (str_len == 0) {
140
- parser->file = NULL;
141
- parser->closed = true;
142
- parser->eof_reached = true;
143
- zsv_options_parse(opts_hash, &parser->options);
144
- parser->row_builder = zsv_row_builder_new(parser->options.encoding);
145
- parser->row_buffer = rb_ary_new();
146
- parser->headers = Qnil;
147
- parser->current_row = Qnil;
148
- parser->in_cleanup = false;
149
- return parser;
150
- }
362
+ /* Release zsv and the FILE*. Never calls into Ruby: runs from dfree during GC. */
363
+ static void zsv_parser_release(zsv_ruby_parser_t *parser)
364
+ {
365
+ parser->closed = true;
151
366
 
152
- parser->file = fmemopen((void *)str_ptr, str_len, "rb");
153
- if (!parser->file) {
154
- xfree(parser);
155
- rb_raise(rb_eRuntimeError, "Failed to create memory stream");
367
+ if (parser->zsv) {
368
+ zsv_delete(parser->zsv);
369
+ parser->zsv = NULL;
156
370
  }
157
371
 
158
- zsv_parser_init_common(parser, opts_hash);
159
- return parser;
372
+ if (parser->file) {
373
+ fclose(parser->file);
374
+ parser->file = NULL;
375
+ }
160
376
  }
161
377
 
162
- /* Free parser */
163
378
  void zsv_parser_free(zsv_ruby_parser_t *parser)
164
379
  {
165
380
  if (!parser)
166
381
  return;
167
382
 
168
- zsv_parser_close(parser);
169
-
170
- if (parser->row_builder) {
171
- zsv_row_builder_free(parser->row_builder);
172
- }
173
-
174
- if (parser->error_message) {
175
- xfree(parser->error_message);
176
- }
177
-
178
- zsv_options_free(&parser->options);
383
+ zsv_parser_release(parser);
384
+ zsv_row_builder_free(parser->row_builder);
179
385
  xfree(parser);
180
386
  }
181
387
 
182
- /* Parse next row - pull-based interface */
183
- VALUE zsv_parser_shift(zsv_ruby_parser_t *parser)
388
+ static void zsv_parser_ensure_not_parsing(zsv_ruby_parser_t *parser)
184
389
  {
185
- if (parser->closed) {
186
- return Qnil;
390
+ if (parser->parsing) {
391
+ rb_raise(eZSVError, "ZSV::Parser is in use (re-entered from a callback or another thread)");
187
392
  }
393
+ }
188
394
 
189
- /* If we have buffered rows, return the first one */
190
- if (RARRAY_LEN(parser->row_buffer) > 0) {
191
- return rb_ary_shift(parser->row_buffer);
192
- }
395
+ void zsv_parser_close(zsv_ruby_parser_t *parser)
396
+ {
397
+ zsv_parser_ensure_not_parsing(parser);
398
+ zsv_parser_release(parser);
399
+ }
193
400
 
194
- /* If we've reached EOF, no more rows */
195
- if (parser->eof_reached) {
196
- return Qnil;
197
- }
401
+ /* ---- parsing ------------------------------------------------------------------ */
198
402
 
199
- /* Parse more data */
403
+ /* Feed zsv one buffer of input; at EOF flush the final row with zsv_finish(),
404
+ * exactly once. Ruby code only runs under rb_protect() in here. */
405
+ static enum zsv_status zsv_parser_parse_chunk(zsv_ruby_parser_t *parser)
406
+ {
407
+ parser->parsing = true;
200
408
  enum zsv_status status = zsv_parse_more(parser->zsv);
201
-
202
- /* Check for errors */
203
- if (status != zsv_status_ok && status != zsv_status_no_more_input) {
204
- RAISE_MALFORMED_CSV("CSV parsing error");
205
- }
206
-
207
- /* If EOF reached, finish to flush final row */
208
- if (status == zsv_status_no_more_input && !parser->eof_reached) {
209
- /* Call finish() BEFORE marking EOF to flush any pending row */
210
- zsv_parser_finish_safe(parser);
409
+ if (status == zsv_status_no_more_input && !parser->exception_state) {
410
+ enum zsv_status finish_status = zsv_finish(parser->zsv);
211
411
  parser->eof_reached = true;
412
+ if (finish_status != zsv_status_ok) {
413
+ status = finish_status;
414
+ }
212
415
  }
213
-
214
- /* Return first buffered row, or nil if buffer is empty */
215
- if (RARRAY_LEN(parser->row_buffer) > 0) {
216
- return rb_ary_shift(parser->row_buffer);
217
- }
218
-
219
- return Qnil; /* EOF or no rows yet */
416
+ parser->parsing = false;
417
+ return status;
220
418
  }
221
419
 
222
- /* Parse all rows with block */
223
- void zsv_parser_each(zsv_ruby_parser_t *parser)
420
+ static void zsv_parser_raise_on_error(zsv_ruby_parser_t *parser, enum zsv_status status)
224
421
  {
225
- VALUE row;
226
- while (!NIL_P(row = zsv_parser_shift(parser))) {
227
- rb_yield(row);
422
+ if (parser->exception_state) {
423
+ int state = parser->exception_state;
424
+ zsv_parser_release(parser);
425
+ rb_jump_tag(state);
426
+ }
427
+
428
+ if (status != zsv_status_ok && status != zsv_status_no_more_input) {
429
+ zsv_parser_release(parser);
430
+ rb_raise(eMalformedCSVError, "CSV parsing error: %s", zsv_parse_status_desc(status));
228
431
  }
229
432
  }
230
433
 
231
- /* Rewind parser */
232
- void zsv_parser_rewind(zsv_ruby_parser_t *parser)
434
+ static void zsv_parser_fill(zsv_ruby_parser_t *parser)
233
435
  {
234
- if (!parser->file) {
235
- rb_raise(rb_eIOError, "Cannot rewind non-file parser");
436
+ /* A chunk can end without completing a row (long rows, skipped or header
437
+ * rows, no trailing newline), so keep going until a row or EOF */
438
+ while (!parser->closed && !parser->eof_reached && RARRAY_LEN(parser->row_buffer) == 0) {
439
+ enum zsv_status status = zsv_parser_parse_chunk(parser);
440
+ zsv_parser_raise_on_error(parser, status);
441
+ rb_thread_check_ints(); /* outside zsv: safe to raise Interrupt here */
236
442
  }
237
-
238
- rewind(parser->file);
239
- zsv_finish(parser->zsv);
240
- zsv_delete(parser->zsv);
241
-
242
- /* Reinitialize parser */
243
- struct zsv_opts zopts = {0};
244
- zopts.delimiter = parser->options.delimiter;
245
- zopts.row_handler = zsv_row_handler;
246
- zopts.ctx = parser;
247
- zopts.stream = parser->file;
248
-
249
- parser->zsv = zsv_new(&zopts);
250
-
251
- parser->row_count = 0;
252
- parser->lines_skipped = 0;
253
- parser->header_row_processed = false;
254
- parser->eof_reached = false;
255
- parser->in_cleanup = false;
256
- parser->row_buffer = rb_ary_new();
257
- parser->current_row = Qnil;
258
443
  }
259
444
 
260
- /* Finish parsing safely (flush final row if needed) */
261
- static void zsv_parser_finish_safe(zsv_ruby_parser_t *parser)
445
+ VALUE zsv_parser_shift(zsv_ruby_parser_t *parser)
262
446
  {
263
- if (!parser->zsv) {
264
- return; /* No parser */
447
+ zsv_parser_ensure_not_parsing(parser);
448
+ if (parser->closed) {
449
+ return Qnil;
265
450
  }
266
451
 
267
- /* Only finish if we can allocate (not in GC) */
268
- if (!parser->in_cleanup) {
269
- zsv_finish(parser->zsv);
452
+ zsv_parser_fill(parser);
453
+
454
+ if (!parser->closed && RARRAY_LEN(parser->row_buffer) > 0) {
455
+ return rb_ary_shift(parser->row_buffer);
270
456
  }
457
+ return Qnil;
271
458
  }
272
459
 
273
- /* Close parser */
274
- void zsv_parser_close(zsv_ruby_parser_t *parser)
460
+ void zsv_parser_rewind(zsv_ruby_parser_t *parser)
275
461
  {
276
- if (!parser || parser->closed)
277
- return;
278
-
279
- /* Mark as closed and in_cleanup FIRST to prevent Ruby allocations
280
- * during GC phase. This is critical because dfree may be called
281
- * during GC, and zsv_finish/zsv_delete can trigger row callbacks. */
282
- parser->closed = true;
283
- parser->in_cleanup = true;
284
-
285
- if (parser->zsv) {
286
- /* Delete parser - this calls zsv_finish internally and frees buffers.
287
- * Row callbacks may fire but in_cleanup flag prevents allocations. */
288
- zsv_delete(parser->zsv);
289
- parser->zsv = NULL;
462
+ zsv_parser_ensure_not_parsing(parser);
463
+ if (parser->closed) {
464
+ rb_raise(rb_eIOError, "closed parser");
290
465
  }
291
466
 
292
- if (parser->file) {
293
- fclose(parser->file);
294
- parser->file = NULL;
467
+ switch (parser->source_kind) {
468
+ case ZSV_SOURCE_FILE:
469
+ if (fseek(parser->file, 0, SEEK_SET) != 0) {
470
+ rb_sys_fail("rewind");
471
+ }
472
+ break;
473
+ case ZSV_SOURCE_STRING:
474
+ parser->source_offset = 0;
475
+ break;
476
+ case ZSV_SOURCE_IO:
477
+ rb_funcall(parser->source, id_rewind, 0);
478
+ break;
479
+ case ZSV_SOURCE_NONE:
480
+ rb_raise(eZSVError, "parser has no input source");
295
481
  }
482
+
483
+ zsv_parser_reset_state(parser);
484
+ zsv_delete(parser->zsv);
485
+ parser->zsv = NULL;
486
+ zsv_parser_create_zsv(parser);
296
487
  }
297
488
 
298
- /* Get headers */
299
489
  VALUE zsv_parser_headers(zsv_ruby_parser_t *parser)
300
490
  {
301
491
  return parser->headers;
302
492
  }
303
493
 
304
- /* Check if closed */
305
494
  bool zsv_parser_closed(zsv_ruby_parser_t *parser)
306
495
  {
307
496
  return parser->closed;
308
497
  }
309
498
 
310
- /* Get row count */
311
- size_t zsv_parser_row_count(zsv_ruby_parser_t *parser)
499
+ void Init_zsv_parser(void)
312
500
  {
313
- return parser->row_count;
501
+ id_read = rb_intern("read");
502
+ id_rewind = rb_intern("rewind");
314
503
  }