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/zsv_ext.c CHANGED
@@ -12,98 +12,170 @@ VALUE eZSVError = Qnil;
12
12
  VALUE eMalformedCSVError = Qnil;
13
13
  VALUE eInvalidEncodingError = Qnil;
14
14
 
15
- /* GC marking function for Parser */
16
- static void zsv_parser_mark(void *ptr)
15
+ static ID id_file_p;
16
+ static ID id_read;
17
+ static ID id_to_path;
18
+ static ID id_eof_p;
19
+
20
+ static void zsv_parser_gc_mark(void *ptr)
21
+ {
22
+ zsv_parser_mark((zsv_ruby_parser_t *)ptr);
23
+ }
24
+
25
+ static void zsv_parser_gc_compact(void *ptr)
17
26
  {
18
- zsv_ruby_parser_t *parser = (zsv_ruby_parser_t *)ptr;
19
- if (!parser)
20
- return;
21
-
22
- rb_gc_mark(parser->io);
23
- rb_gc_mark(parser->headers);
24
- rb_gc_mark(parser->current_row);
25
- rb_gc_mark(parser->row_buffer);
26
- rb_gc_mark(parser->options.header_array);
27
+ zsv_parser_compact((zsv_ruby_parser_t *)ptr);
27
28
  }
28
29
 
29
- /* GC freeing function for Parser */
30
30
  static void zsv_parser_gc_free(void *ptr)
31
31
  {
32
32
  zsv_parser_free((zsv_ruby_parser_t *)ptr);
33
33
  }
34
34
 
35
- /* Size function for GC */
36
- static size_t zsv_parser_memsize(const void *ptr)
35
+ static size_t zsv_parser_gc_memsize(const void *ptr)
37
36
  {
38
- return ptr ? sizeof(zsv_ruby_parser_t) : 0;
37
+ return zsv_parser_memsize((const zsv_ruby_parser_t *)ptr);
39
38
  }
40
39
 
41
- /* Data type definition */
40
+ /* Not write-barrier protected: the parser stores VALUEs (row cells, headers)
41
+ * in C memory without RB_OBJ_WRITE, so it is always rescanned by the GC. */
42
42
  static const rb_data_type_t zsv_parser_type = {
43
43
  .wrap_struct_name = "ZSV::Parser",
44
44
  .function =
45
45
  {
46
- .dmark = zsv_parser_mark,
46
+ .dmark = zsv_parser_gc_mark,
47
47
  .dfree = zsv_parser_gc_free,
48
- .dsize = zsv_parser_memsize,
48
+ .dsize = zsv_parser_gc_memsize,
49
+ .dcompact = zsv_parser_gc_compact,
49
50
  },
50
51
  .flags = RUBY_TYPED_FREE_IMMEDIATELY,
51
52
  };
52
53
 
53
- /* Unwrap parser from Ruby object */
54
- static zsv_ruby_parser_t *get_parser(VALUE self)
54
+ /* Unwrap the parser struct without checking that it was initialized */
55
+ static zsv_ruby_parser_t *get_parser_struct(VALUE self)
55
56
  {
56
57
  zsv_ruby_parser_t *parser;
57
58
  TypedData_Get_Struct(self, zsv_ruby_parser_t, &zsv_parser_type, parser);
58
59
  return parser;
59
60
  }
60
61
 
61
- /* Wrap parser in Ruby object */
62
- static VALUE wrap_parser(zsv_ruby_parser_t *parser)
62
+ /* Unwrap parser from Ruby object */
63
+ static zsv_ruby_parser_t *get_parser(VALUE self)
63
64
  {
64
- return TypedData_Wrap_Struct(cParser, &zsv_parser_type, parser);
65
+ zsv_ruby_parser_t *parser = get_parser_struct(self);
66
+ if (parser->source_kind == ZSV_SOURCE_NONE) {
67
+ rb_raise(eZSVError, "uninitialized ZSV::Parser");
68
+ }
69
+ return parser;
65
70
  }
66
71
 
67
- /* Allocate function for Parser class */
72
+ /* Allocate function for Parser class: the struct is owned by the object from
73
+ * the start, so an exception during initialize cannot leak it */
68
74
  static VALUE zsv_parser_alloc(VALUE klass)
69
75
  {
70
- return TypedData_Wrap_Struct(klass, &zsv_parser_type, NULL);
76
+ zsv_ruby_parser_t *parser;
77
+ VALUE obj = TypedData_Make_Struct(klass, zsv_ruby_parser_t, &zsv_parser_type, parser);
78
+ zsv_parser_init_struct(parser);
79
+ return obj;
80
+ }
81
+
82
+ /* A String with a line break is CSV data. Without one it is a path when such
83
+ * a file exists, or when it has no comma (so "data.csv" missing still raises
84
+ * Errno::ENOENT); otherwise it is a single CSV line such as "a,b". */
85
+ static bool zsv_string_is_csv_data(VALUE string)
86
+ {
87
+ const char *ptr = RSTRING_PTR(string);
88
+ long len = RSTRING_LEN(string);
89
+
90
+ if (memchr(ptr, '\n', len) || memchr(ptr, '\r', len) || memchr(ptr, '\0', len)) {
91
+ return true;
92
+ }
93
+ if (RTEST(rb_funcall(rb_cFile, id_file_p, 1, string))) {
94
+ return false;
95
+ }
96
+ /* File.file? allocates: re-read the pointer, the bytes may have moved */
97
+ return memchr(RSTRING_PTR(string), ',', len) != NULL;
71
98
  }
72
99
 
73
100
  /*
74
101
  * call-seq:
75
- * ZSV::Parser.new(io, **options) -> parser
102
+ * ZSV::Parser.new(source, **options) -> parser
76
103
  *
77
- * Creates a new parser for the given IO object.
104
+ * Creates a new parser. +source+ is a path-like object (#to_path, such as a
105
+ * Pathname), an IO-like object (anything responding to #read), a file path,
106
+ * or CSV data. A File answers both #to_path and #read and is read as a
107
+ * stream, from its current position; a Pathname also answers #read (the
108
+ * whole file on every call) and is opened as a path. A String is treated as
109
+ * CSV data when it contains a line break, or a comma and no such file
110
+ * exists; use Parser.from_string or Parser.from_path to avoid the guess.
78
111
  */
79
112
  static VALUE rb_zsv_parser_initialize(int argc, VALUE *argv, VALUE self)
80
113
  {
81
- VALUE io, opts;
82
- rb_scan_args(argc, argv, "11", &io, &opts);
83
-
84
- zsv_ruby_parser_t *parser;
114
+ VALUE source, opts;
115
+ rb_scan_args(argc, argv, "11", &source, &opts);
85
116
 
86
- if (TYPE(io) == T_STRING) {
87
- const char *str = StringValueCStr(io);
117
+ zsv_ruby_parser_t *parser = get_parser_struct(self);
88
118
 
89
- /* Detect if it's a file path or CSV content */
90
- /* If it contains newlines or commas and doesn't exist as a file, treat as CSV data */
91
- if (strchr(str, '\n') != NULL || strchr(str, ',') != NULL) {
92
- /* Looks like CSV content, parse as string */
93
- parser = zsv_parser_new_from_string(io, opts);
119
+ if (RB_TYPE_P(source, T_STRING)) {
120
+ if (zsv_string_is_csv_data(source)) {
121
+ zsv_parser_init_string(parser, source, opts);
94
122
  } else {
95
- /* Try as file path */
96
- parser = zsv_parser_new_from_path(str, opts);
123
+ zsv_parser_init_path(parser, source, opts);
97
124
  }
125
+ } else if (rb_respond_to(source, id_to_path) && !rb_respond_to(source, id_eof_p)) {
126
+ zsv_parser_init_path(parser, source, opts);
127
+ } else if (rb_respond_to(source, id_read)) {
128
+ zsv_parser_init_io(parser, source, opts);
98
129
  } else {
99
- /* IO object */
100
- parser = zsv_parser_new_from_io(io, opts);
130
+ rb_raise(rb_eTypeError, "expected a String, path or IO-like object, got %s",
131
+ rb_obj_classname(source));
101
132
  }
102
133
 
103
- DATA_PTR(self) = parser;
104
134
  return self;
105
135
  }
106
136
 
137
+ /* Allocate a parser object of +klass+; it frees itself if init raises */
138
+ static VALUE zsv_new_parser_object(VALUE klass, zsv_ruby_parser_t **parser)
139
+ {
140
+ VALUE obj = zsv_parser_alloc(klass);
141
+ *parser = get_parser_struct(obj);
142
+ return obj;
143
+ }
144
+
145
+ /*
146
+ * call-seq:
147
+ * ZSV::Parser.from_string(csv, **options) -> parser
148
+ *
149
+ * Creates a parser over CSV data held in a String (never a file path).
150
+ */
151
+ static VALUE rb_zsv_parser_s_from_string(int argc, VALUE *argv, VALUE klass)
152
+ {
153
+ VALUE string, opts;
154
+ rb_scan_args(argc, argv, "11", &string, &opts);
155
+
156
+ zsv_ruby_parser_t *parser;
157
+ VALUE obj = zsv_new_parser_object(klass, &parser);
158
+ zsv_parser_init_string(parser, string, opts);
159
+ return obj;
160
+ }
161
+
162
+ /*
163
+ * call-seq:
164
+ * ZSV::Parser.from_path(path, **options) -> parser
165
+ *
166
+ * Creates a parser over the file at +path+ (a String or Pathname).
167
+ */
168
+ static VALUE rb_zsv_parser_s_from_path(int argc, VALUE *argv, VALUE klass)
169
+ {
170
+ VALUE path, opts;
171
+ rb_scan_args(argc, argv, "11", &path, &opts);
172
+
173
+ zsv_ruby_parser_t *parser;
174
+ VALUE obj = zsv_new_parser_object(klass, &parser);
175
+ zsv_parser_init_path(parser, path, opts);
176
+ return obj;
177
+ }
178
+
107
179
  /*
108
180
  * call-seq:
109
181
  * parser.shift -> array or hash or nil
@@ -112,24 +184,26 @@ static VALUE rb_zsv_parser_initialize(int argc, VALUE *argv, VALUE self)
112
184
  */
113
185
  static VALUE rb_zsv_parser_shift(VALUE self)
114
186
  {
115
- zsv_ruby_parser_t *parser = get_parser(self);
116
- return zsv_parser_shift(parser);
187
+ return zsv_parser_shift(get_parser(self));
117
188
  }
118
189
 
119
190
  /*
120
191
  * call-seq:
121
- * parser.each {|row| block } -> nil
192
+ * parser.each {|row| block } -> parser
122
193
  * parser.each -> enumerator
123
194
  *
124
- * Iterates over all rows.
195
+ * Iterates over the remaining rows. Aliased as #each_row.
125
196
  */
126
197
  static VALUE rb_zsv_parser_each(VALUE self)
127
198
  {
128
199
  RETURN_ENUMERATOR(self, 0, 0);
129
200
 
130
201
  zsv_ruby_parser_t *parser = get_parser(self);
131
- zsv_parser_each(parser);
132
- return Qnil;
202
+ VALUE row;
203
+ while (!NIL_P(row = zsv_parser_shift(parser))) {
204
+ rb_yield(row);
205
+ }
206
+ return self;
133
207
  }
134
208
 
135
209
  /*
@@ -140,8 +214,7 @@ static VALUE rb_zsv_parser_each(VALUE self)
140
214
  */
141
215
  static VALUE rb_zsv_parser_rewind(VALUE self)
142
216
  {
143
- zsv_ruby_parser_t *parser = get_parser(self);
144
- zsv_parser_rewind(parser);
217
+ zsv_parser_rewind(get_parser(self));
145
218
  return Qnil;
146
219
  }
147
220
 
@@ -153,8 +226,7 @@ static VALUE rb_zsv_parser_rewind(VALUE self)
153
226
  */
154
227
  static VALUE rb_zsv_parser_close(VALUE self)
155
228
  {
156
- zsv_ruby_parser_t *parser = get_parser(self);
157
- zsv_parser_close(parser);
229
+ zsv_parser_close(get_parser(self));
158
230
  return Qnil;
159
231
  }
160
232
 
@@ -166,8 +238,7 @@ static VALUE rb_zsv_parser_close(VALUE self)
166
238
  */
167
239
  static VALUE rb_zsv_parser_headers_get(VALUE self)
168
240
  {
169
- zsv_ruby_parser_t *parser = get_parser(self);
170
- return zsv_parser_headers(parser);
241
+ return zsv_parser_headers(get_parser(self));
171
242
  }
172
243
 
173
244
  /*
@@ -178,8 +249,26 @@ static VALUE rb_zsv_parser_headers_get(VALUE self)
178
249
  */
179
250
  static VALUE rb_zsv_parser_closed_p(VALUE self)
180
251
  {
181
- zsv_ruby_parser_t *parser = get_parser(self);
182
- return zsv_parser_closed(parser) ? Qtrue : Qfalse;
252
+ return zsv_parser_closed(get_parser(self)) ? Qtrue : Qfalse;
253
+ }
254
+
255
+ static VALUE zsv_read_all(VALUE parser_obj)
256
+ {
257
+ zsv_ruby_parser_t *parser = get_parser(parser_obj);
258
+ VALUE result = rb_ary_new();
259
+ VALUE row;
260
+
261
+ while (!NIL_P(row = zsv_parser_shift(parser))) {
262
+ rb_ary_push(result, row);
263
+ }
264
+ return result;
265
+ }
266
+
267
+ /* rb_ensure callback: close the parser even if parsing or the block raised */
268
+ static VALUE zsv_close_parser_object(VALUE parser_obj)
269
+ {
270
+ zsv_parser_close(get_parser(parser_obj));
271
+ return Qnil;
183
272
  }
184
273
 
185
274
  /*
@@ -196,21 +285,11 @@ static VALUE rb_zsv_foreach(int argc, VALUE *argv, VALUE klass)
196
285
 
197
286
  RETURN_ENUMERATOR(klass, argc, argv);
198
287
 
199
- Check_Type(path, T_STRING);
200
-
201
- zsv_ruby_parser_t *parser = zsv_parser_new_from_path(StringValueCStr(path), opts);
202
- VALUE parser_obj = wrap_parser(parser);
203
-
204
- /* Ensure cleanup even if exception occurs */
205
- int state;
206
- rb_protect((VALUE(*)(VALUE))rb_zsv_parser_each, parser_obj, &state);
207
-
208
- zsv_parser_close(parser);
209
-
210
- if (state) {
211
- rb_jump_tag(state);
212
- }
288
+ zsv_ruby_parser_t *parser;
289
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
290
+ zsv_parser_init_path(parser, path, opts);
213
291
 
292
+ rb_ensure(rb_zsv_parser_each, parser_obj, zsv_close_parser_object, parser_obj);
214
293
  return Qnil;
215
294
  }
216
295
 
@@ -228,16 +307,11 @@ static VALUE rb_zsv_parse(int argc, VALUE *argv, VALUE klass)
228
307
 
229
308
  Check_Type(string, T_STRING);
230
309
 
231
- zsv_ruby_parser_t *parser = zsv_parser_new_from_string(string, opts);
232
- VALUE result = rb_ary_new();
233
-
234
- VALUE row;
235
- while (!NIL_P(row = zsv_parser_shift(parser))) {
236
- rb_ary_push(result, row);
237
- }
310
+ zsv_ruby_parser_t *parser;
311
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
312
+ zsv_parser_init_string(parser, string, opts);
238
313
 
239
- zsv_parser_free(parser);
240
- return result;
314
+ return rb_ensure(zsv_read_all, parser_obj, zsv_close_parser_object, parser_obj);
241
315
  }
242
316
 
243
317
  /*
@@ -252,18 +326,11 @@ static VALUE rb_zsv_read(int argc, VALUE *argv, VALUE klass)
252
326
  (void)klass;
253
327
  rb_scan_args(argc, argv, "11", &path, &opts);
254
328
 
255
- Check_Type(path, T_STRING);
256
-
257
- zsv_ruby_parser_t *parser = zsv_parser_new_from_path(StringValueCStr(path), opts);
258
- VALUE result = rb_ary_new();
259
-
260
- VALUE row;
261
- while (!NIL_P(row = zsv_parser_shift(parser))) {
262
- rb_ary_push(result, row);
263
- }
329
+ zsv_ruby_parser_t *parser;
330
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
331
+ zsv_parser_init_path(parser, path, opts);
264
332
 
265
- zsv_parser_free(parser);
266
- return result;
333
+ return rb_ensure(zsv_read_all, parser_obj, zsv_close_parser_object, parser_obj);
267
334
  }
268
335
 
269
336
  /*
@@ -280,10 +347,8 @@ static VALUE rb_zsv_open(int argc, VALUE *argv, VALUE klass)
280
347
  (void)klass;
281
348
  rb_scan_args(argc, argv, "11:", &path, &mode, &opts);
282
349
 
283
- Check_Type(path, T_STRING);
284
-
285
350
  /* If mode is a hash, it's actually the options */
286
- if (!NIL_P(mode) && TYPE(mode) == T_HASH) {
351
+ if (!NIL_P(mode) && RB_TYPE_P(mode, T_HASH)) {
287
352
  opts = mode;
288
353
  mode = Qnil;
289
354
  }
@@ -293,19 +358,12 @@ static VALUE rb_zsv_open(int argc, VALUE *argv, VALUE klass)
293
358
  rb_raise(rb_eNotImpError, "Only read mode is currently supported");
294
359
  }
295
360
 
296
- zsv_ruby_parser_t *parser = zsv_parser_new_from_path(StringValueCStr(path), opts);
297
- VALUE parser_obj = wrap_parser(parser);
361
+ zsv_ruby_parser_t *parser;
362
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
363
+ zsv_parser_init_path(parser, path, opts);
298
364
 
299
365
  if (rb_block_given_p()) {
300
- int state;
301
- VALUE result = rb_protect(rb_yield, parser_obj, &state);
302
- zsv_parser_close(parser);
303
-
304
- if (state) {
305
- rb_jump_tag(state);
306
- }
307
-
308
- return result;
366
+ return rb_ensure(rb_yield, parser_obj, zsv_close_parser_object, parser_obj);
309
367
  }
310
368
 
311
369
  return parser_obj;
@@ -314,6 +372,16 @@ static VALUE rb_zsv_open(int argc, VALUE *argv, VALUE klass)
314
372
  /* Initialize the extension */
315
373
  void Init_zsv(void)
316
374
  {
375
+ /* No mutable global state: parsers are per-object and never shareable */
376
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
377
+ rb_ext_ractor_safe(true);
378
+ #endif
379
+
380
+ id_file_p = rb_intern("file?");
381
+ id_read = rb_intern("read");
382
+ id_to_path = rb_intern("to_path");
383
+ id_eof_p = rb_intern("eof?");
384
+
317
385
  /* Define module */
318
386
  mZSV = rb_define_module("ZSV");
319
387
 
@@ -321,6 +389,8 @@ void Init_zsv(void)
321
389
  cParser = rb_define_class_under(mZSV, "Parser", rb_cObject);
322
390
  rb_include_module(cParser, rb_mEnumerable);
323
391
  rb_define_alloc_func(cParser, zsv_parser_alloc);
392
+ rb_define_singleton_method(cParser, "from_string", rb_zsv_parser_s_from_string, -1);
393
+ rb_define_singleton_method(cParser, "from_path", rb_zsv_parser_s_from_path, -1);
324
394
  rb_define_method(cParser, "initialize", rb_zsv_parser_initialize, -1);
325
395
  rb_define_method(cParser, "shift", rb_zsv_parser_shift, 0);
326
396
  rb_define_method(cParser, "each", rb_zsv_parser_each, 0);
@@ -343,4 +413,5 @@ void Init_zsv(void)
343
413
 
344
414
  /* Initialize submodules */
345
415
  Init_zsv_options();
416
+ Init_zsv_parser();
346
417
  }
data/lib/zsv/errors.rb ADDED
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ZSV
4
+ # Raised for malformed CSV, mirroring CSV::MalformedCSVError: the message
5
+ # ends with "in line N." and the line is available as #line_number.
6
+ #
7
+ # ZSV parses leniently by default; this error is raised for quoting
8
+ # problems only when +liberal_parsing: false+ is given.
9
+ class MalformedCSVError < Error
10
+ # @return [Integer, nil] 1-based number of the offending record, as in CSV
11
+ attr_reader :line_number
12
+ alias lineno line_number
13
+
14
+ def initialize(message = nil, line_number = nil)
15
+ @line_number = line_number
16
+ super(line_number ? "#{message} in line #{line_number}." : message)
17
+ end
18
+ end
19
+
20
+ # Raised by strict parsing (+liberal_parsing: false+) when the input is not
21
+ # valid in its encoding, mirroring CSV::InvalidEncodingError.
22
+ class InvalidEncodingError < Error
23
+ # @return [Integer, nil] 1-based number of the offending record, as in CSV
24
+ attr_reader :line_number
25
+ alias lineno line_number
26
+
27
+ def initialize(message = nil, line_number = nil)
28
+ @line_number = line_number
29
+ super(line_number ? "#{message} in line #{line_number}." : message)
30
+ end
31
+ end
32
+ end
data/lib/zsv/input.rb ADDED
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ZSV
4
+ # Turns what the caller passed (CSV text, a path, an IO) plus its options
5
+ # into the arguments of the C extension, running the strict check when
6
+ # +liberal_parsing: false+ asks for it.
7
+ module Input
8
+ READ_MODE = /\Ar[bt]?(?::(?<encoding>.+))?\z/
9
+
10
+ module_function
11
+
12
+ # @param string [String] CSV data
13
+ # @param options [Hash] keyword options given by the caller
14
+ # @return [Array(String, Hash)] data and options for the C extension
15
+ def data(string, options)
16
+ raise TypeError, "no implicit conversion of #{string.class} into String" unless string.is_a?(String)
17
+
18
+ native = Options.normalize(options)
19
+ string = string.encode(Encoding::UTF_8) unless string.encoding.ascii_compatible?
20
+ native[:encoding] ||= string.encoding
21
+ StrictValidator.validate_string(string, col_sep: Options.col_sep(options)) if Options.strict?(options)
22
+ [string, native]
23
+ end
24
+
25
+ # @param path [String, #to_path] file to parse
26
+ # @param mode [String] read mode, as given to CSV.open ("r", "rb", "r:bom|utf-8")
27
+ # @param options [Hash] keyword options given by the caller
28
+ # @return [Array(String, Hash)] path and options for the C extension
29
+ def path(path, mode, options)
30
+ path = File.path(path)
31
+ native = Options.normalize(mode_options(mode).merge(options))
32
+ encoding = native[:encoding] || Encoding::UTF_8
33
+ check_ascii_compatible(encoding)
34
+
35
+ if Options.strict?(options)
36
+ StrictValidator.validate_file(path, col_sep: Options.col_sep(options), encoding: encoding)
37
+ end
38
+ [path, native]
39
+ end
40
+
41
+ # @param io [#read] source to parse as it is read
42
+ # @param options [Hash] keyword options given by the caller
43
+ # @return [Array(Object, Hash)] the IO and options for the C extension;
44
+ # fields are labelled with the IO's external encoding, as CSV does
45
+ def io(io, options)
46
+ native = Options.normalize(options)
47
+ check_ascii_compatible(native[:encoding]) if native[:encoding]
48
+ encoding = io.external_encoding if io.respond_to?(:external_encoding)
49
+ native[:encoding] ||= encoding if encoding&.ascii_compatible?
50
+ [io, native]
51
+ end
52
+
53
+ # The parser works on bytes: it cannot find separators in UTF-16 or UTF-32.
54
+ def check_ascii_compatible(encoding)
55
+ return if encoding.ascii_compatible?
56
+
57
+ raise ArgumentError, "encoding must be ASCII-compatible for files and IOs, got #{encoding}"
58
+ end
59
+
60
+ # Decides what a String given to ZSV.new is: data when it is empty or
61
+ # holds a line ending or a NUL byte, else the path of an existing file,
62
+ # else data when it holds the column separator, else a path (which will
63
+ # not be found).
64
+ #
65
+ # @return [Boolean] true for CSV data, false for a path
66
+ def data?(string, col_sep)
67
+ return true if string.empty? || string.match?(/[\r\n\0]/)
68
+ return false if File.file?(string)
69
+
70
+ string.include?(col_sep)
71
+ end
72
+
73
+ # A Pathname answers #read too, with the whole file each time: it is a
74
+ # path, while a File (which has both) is a stream.
75
+ #
76
+ # @return [Boolean] true for a path-like object that is not a stream
77
+ def path?(source)
78
+ source.respond_to?(:to_path) && !source.respond_to?(:eof?)
79
+ end
80
+
81
+ def mode_options(mode)
82
+ match = READ_MODE.match((mode || 'r').to_s)
83
+ raise ArgumentError, "ZSV only reads CSV: unsupported mode #{mode.inspect}" unless match
84
+
85
+ match[:encoding] ? { encoding: match[:encoding] } : {}
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ZSV
4
+ # Validates the keyword options of the public API and converts them into
5
+ # the hash the C extension understands, so that an unsupported or misspelled
6
+ # option raises instead of being silently ignored.
7
+ module Options
8
+ # Options interpreted (or validated) by the Ruby layer
9
+ RUBY_KEYS = %i[headers col_sep quote_char row_sep skip_lines liberal_parsing encoding buffer_size].freeze
10
+ # Options handed to the C extension untouched
11
+ NATIVE_KEYS = %i[max_columns max_row_size].freeze
12
+ KNOWN_KEYS = (RUBY_KEYS + NATIVE_KEYS).freeze
13
+
14
+ ROW_SEPARATORS = [:auto, "\n", "\r\n", "\r"].freeze
15
+ QUOTE_CHAR = '"'
16
+ DEFAULT_COL_SEP = ','
17
+
18
+ module_function
19
+
20
+ # @param options [Hash] keyword options given by the caller
21
+ # @return [Hash] options for the C extension
22
+ # @raise [ArgumentError] for unknown keys and unsupported values
23
+ def normalize(options)
24
+ check(options)
25
+ col_sep = col_sep(options)
26
+
27
+ options.slice(*NATIVE_KEYS).merge(
28
+ col_sep: col_sep,
29
+ headers: headers(options[:headers], col_sep),
30
+ skip_lines: skip_lines(options[:skip_lines]),
31
+ encoding: encoding(options[:encoding]),
32
+ buffer_size: buffer_size(options[:buffer_size])
33
+ ).compact
34
+ end
35
+
36
+ # Rejects the options ZSV cannot honour.
37
+ def check(options)
38
+ reject_unknown_keys(options)
39
+ check_quote_char(options[:quote_char]) if options.key?(:quote_char)
40
+ check_row_sep(options[:row_sep]) if options.key?(:row_sep)
41
+ check_liberal_parsing(options[:liberal_parsing])
42
+ end
43
+
44
+ # @return [Boolean] true when quoting errors must raise (liberal_parsing: false)
45
+ def strict?(options)
46
+ options[:liberal_parsing] == false
47
+ end
48
+
49
+ # @return [String] the validated single-byte column separator
50
+ def col_sep(options)
51
+ col_sep = options.fetch(:col_sep, nil) || DEFAULT_COL_SEP
52
+ raise ArgumentError, "col_sep must be a String, got #{col_sep.inspect}" unless col_sep.is_a?(String)
53
+
54
+ unless col_sep.bytesize == 1 && col_sep.ascii_only?
55
+ raise ArgumentError, "col_sep must be a single ASCII character (zsv limitation), got #{col_sep.inspect}"
56
+ end
57
+ if [QUOTE_CHAR, "\n", "\r"].include?(col_sep)
58
+ raise ArgumentError, "col_sep cannot be a quote or a line ending, got #{col_sep.inspect}"
59
+ end
60
+
61
+ col_sep
62
+ end
63
+
64
+ def reject_unknown_keys(options)
65
+ unknown = options.keys - KNOWN_KEYS
66
+ return if unknown.empty?
67
+
68
+ raise ArgumentError, "unknown keyword#{'s' if unknown.size > 1}: #{unknown.map(&:inspect).join(', ')}"
69
+ end
70
+
71
+ def check_quote_char(quote_char)
72
+ return if quote_char == QUOTE_CHAR
73
+
74
+ raise ArgumentError, "quote_char must be '\"': zsv supports no other quote character, got #{quote_char.inspect}"
75
+ end
76
+
77
+ def check_row_sep(row_sep)
78
+ return if ROW_SEPARATORS.include?(row_sep)
79
+
80
+ raise ArgumentError,
81
+ 'row_sep must be :auto, "\n", "\r\n" or "\r": zsv always auto-detects these line endings, ' \
82
+ "got #{row_sep.inspect}"
83
+ end
84
+
85
+ def check_liberal_parsing(liberal_parsing)
86
+ return if [nil, true, false].include?(liberal_parsing)
87
+
88
+ raise ArgumentError, "liberal_parsing must be true or false, got #{liberal_parsing.inspect}"
89
+ end
90
+
91
+ def headers(headers, col_sep)
92
+ case headers
93
+ when nil, false then nil
94
+ when true, :first_row then true
95
+ when Array then headers
96
+ when String then header_line(headers, col_sep)
97
+ else raise ArgumentError, "headers must be true, false, an Array or a String, got #{headers.inspect}"
98
+ end
99
+ end
100
+
101
+ # CSV accepts the header names as one CSV line
102
+ def header_line(line, col_sep)
103
+ ZSV.parse_line(line, col_sep: col_sep) || []
104
+ end
105
+
106
+ def skip_lines(skip_lines)
107
+ return skip_lines if skip_lines.nil? || (skip_lines.is_a?(Integer) && !skip_lines.negative?)
108
+
109
+ raise ArgumentError,
110
+ 'skip_lines must be a non-negative Integer (the number of leading rows to drop); ' \
111
+ "CSV-style matchers are not supported, got #{skip_lines.inspect}"
112
+ end
113
+
114
+ # Accepts an Encoding, a name, and the CSV forms "bom|utf-8" (zsv always
115
+ # strips a UTF-8 BOM) and "ext:int" when no transcoding is asked for.
116
+ def encoding(encoding)
117
+ return encoding if encoding.nil? || encoding.is_a?(Encoding)
118
+
119
+ external, internal = encoding.to_s.sub(/\Abom\|/i, '').split(':', 2)
120
+ found = Encoding.find(external)
121
+ return found if internal.nil? || internal == '-' || Encoding.find(internal) == found
122
+
123
+ raise ArgumentError, "transcoding (#{encoding.inspect}) is not supported: fields keep the source bytes"
124
+ end
125
+
126
+ def buffer_size(buffer_size)
127
+ return buffer_size if buffer_size.nil? || (buffer_size.is_a?(Integer) && buffer_size.positive?)
128
+
129
+ raise ArgumentError, "buffer_size must be a positive Integer, got #{buffer_size.inspect}"
130
+ end
131
+ end
132
+ end