zsv 1.4.4-x86_64-linux-gnu

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 (77) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +187 -0
  3. data/LICENSE +21 -0
  4. data/README.md +203 -0
  5. data/ext/zsv/ZSV_UPSTREAM +7 -0
  6. data/ext/zsv/common.h +22 -0
  7. data/ext/zsv/extconf.rb +102 -0
  8. data/ext/zsv/options.c +126 -0
  9. data/ext/zsv/options.h +28 -0
  10. data/ext/zsv/options_internal.h +8 -0
  11. data/ext/zsv/parser.c +503 -0
  12. data/ext/zsv/parser.h +75 -0
  13. data/ext/zsv/row.c +169 -0
  14. data/ext/zsv/row.h +45 -0
  15. data/ext/zsv/upstream.rb +55 -0
  16. data/ext/zsv/vendor/zsv/LICENSE +21 -0
  17. data/ext/zsv/vendor/zsv/VENDORED_FROM +2 -0
  18. data/ext/zsv/vendor/zsv/configure +1212 -0
  19. data/ext/zsv/vendor/zsv/include/zsv/api.h +375 -0
  20. data/ext/zsv/vendor/zsv/include/zsv/common.h +397 -0
  21. data/ext/zsv/vendor/zsv/include/zsv/ext/implementation.h +62 -0
  22. data/ext/zsv/vendor/zsv/include/zsv/ext/implementation_private.h +113 -0
  23. data/ext/zsv/vendor/zsv/include/zsv/ext/sheet.h +80 -0
  24. data/ext/zsv/vendor/zsv/include/zsv/ext.h +333 -0
  25. data/ext/zsv/vendor/zsv/include/zsv/utils/appname.h +51 -0
  26. data/ext/zsv/vendor/zsv/include/zsv/utils/arg.h +139 -0
  27. data/ext/zsv/vendor/zsv/include/zsv/utils/cache.h +49 -0
  28. data/ext/zsv/vendor/zsv/include/zsv/utils/clock.h +36 -0
  29. data/ext/zsv/vendor/zsv/include/zsv/utils/compiler.h +69 -0
  30. data/ext/zsv/vendor/zsv/include/zsv/utils/db.h +19 -0
  31. data/ext/zsv/vendor/zsv/include/zsv/utils/dirs.h +149 -0
  32. data/ext/zsv/vendor/zsv/include/zsv/utils/dl.h +22 -0
  33. data/ext/zsv/vendor/zsv/include/zsv/utils/emcc/fs_api.h +28 -0
  34. data/ext/zsv/vendor/zsv/include/zsv/utils/err.h +22 -0
  35. data/ext/zsv/vendor/zsv/include/zsv/utils/file-mem.h +18 -0
  36. data/ext/zsv/vendor/zsv/include/zsv/utils/file.h +125 -0
  37. data/ext/zsv/vendor/zsv/include/zsv/utils/jq.h +65 -0
  38. data/ext/zsv/vendor/zsv/include/zsv/utils/json.h +19 -0
  39. data/ext/zsv/vendor/zsv/include/zsv/utils/mem.h +19 -0
  40. data/ext/zsv/vendor/zsv/include/zsv/utils/memmem.h +13 -0
  41. data/ext/zsv/vendor/zsv/include/zsv/utils/os.h +145 -0
  42. data/ext/zsv/vendor/zsv/include/zsv/utils/output.h +34 -0
  43. data/ext/zsv/vendor/zsv/include/zsv/utils/overwrite.h +71 -0
  44. data/ext/zsv/vendor/zsv/include/zsv/utils/overwrite_writer.h +53 -0
  45. data/ext/zsv/vendor/zsv/include/zsv/utils/prop.h +119 -0
  46. data/ext/zsv/vendor/zsv/include/zsv/utils/rng.h +35 -0
  47. data/ext/zsv/vendor/zsv/include/zsv/utils/signal.h +25 -0
  48. data/ext/zsv/vendor/zsv/include/zsv/utils/sql.h +13 -0
  49. data/ext/zsv/vendor/zsv/include/zsv/utils/string.h +173 -0
  50. data/ext/zsv/vendor/zsv/include/zsv/utils/utf8.h +41 -0
  51. data/ext/zsv/vendor/zsv/include/zsv/utils/win/dl.h +25 -0
  52. data/ext/zsv/vendor/zsv/include/zsv/utils/writer.h +109 -0
  53. data/ext/zsv/vendor/zsv/include/zsv/zsv_export.h +33 -0
  54. data/ext/zsv/vendor/zsv/include/zsv.h.in +18 -0
  55. data/ext/zsv/vendor/zsv/src/Makefile +238 -0
  56. data/ext/zsv/vendor/zsv/src/vector_delim.c +60 -0
  57. data/ext/zsv/vendor/zsv/src/zsv.c +622 -0
  58. data/ext/zsv/vendor/zsv/src/zsv_internal.c +789 -0
  59. data/ext/zsv/vendor/zsv/src/zsv_scan_delim.c +285 -0
  60. data/ext/zsv/vendor/zsv/src/zsv_scan_delim_fast.c +741 -0
  61. data/ext/zsv/vendor/zsv/src/zsv_scan_fixed.c +88 -0
  62. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_avx2.h +89 -0
  63. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_neon.h +80 -0
  64. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_sse2.h +93 -0
  65. data/ext/zsv/vendor/zsv/src/zsv_scan_simd_wasm.h +79 -0
  66. data/ext/zsv/vendor/zsv/src/zsv_strencode.c +84 -0
  67. data/ext/zsv/zsv_ext.c +417 -0
  68. data/lib/zsv/3.3/zsv.so +0 -0
  69. data/lib/zsv/3.4/zsv.so +0 -0
  70. data/lib/zsv/4.0/zsv.so +0 -0
  71. data/lib/zsv/errors.rb +32 -0
  72. data/lib/zsv/input.rb +88 -0
  73. data/lib/zsv/options.rb +132 -0
  74. data/lib/zsv/strict_validator.rb +124 -0
  75. data/lib/zsv/version.rb +5 -0
  76. data/lib/zsv.rb +183 -0
  77. metadata +196 -0
data/ext/zsv/zsv_ext.c ADDED
@@ -0,0 +1,417 @@
1
+ /* Main entry point for zsv Ruby extension */
2
+ #include "common.h"
3
+ #include "options.h"
4
+ #include "options_internal.h"
5
+ #include "parser.h"
6
+ #include "row.h"
7
+
8
+ /* Module and class definitions */
9
+ VALUE mZSV = Qnil;
10
+ VALUE cParser = Qnil;
11
+ VALUE eZSVError = Qnil;
12
+ VALUE eMalformedCSVError = Qnil;
13
+ VALUE eInvalidEncodingError = Qnil;
14
+
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)
26
+ {
27
+ zsv_parser_compact((zsv_ruby_parser_t *)ptr);
28
+ }
29
+
30
+ static void zsv_parser_gc_free(void *ptr)
31
+ {
32
+ zsv_parser_free((zsv_ruby_parser_t *)ptr);
33
+ }
34
+
35
+ static size_t zsv_parser_gc_memsize(const void *ptr)
36
+ {
37
+ return zsv_parser_memsize((const zsv_ruby_parser_t *)ptr);
38
+ }
39
+
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
+ static const rb_data_type_t zsv_parser_type = {
43
+ .wrap_struct_name = "ZSV::Parser",
44
+ .function =
45
+ {
46
+ .dmark = zsv_parser_gc_mark,
47
+ .dfree = zsv_parser_gc_free,
48
+ .dsize = zsv_parser_gc_memsize,
49
+ .dcompact = zsv_parser_gc_compact,
50
+ },
51
+ .flags = RUBY_TYPED_FREE_IMMEDIATELY,
52
+ };
53
+
54
+ /* Unwrap the parser struct without checking that it was initialized */
55
+ static zsv_ruby_parser_t *get_parser_struct(VALUE self)
56
+ {
57
+ zsv_ruby_parser_t *parser;
58
+ TypedData_Get_Struct(self, zsv_ruby_parser_t, &zsv_parser_type, parser);
59
+ return parser;
60
+ }
61
+
62
+ /* Unwrap parser from Ruby object */
63
+ static zsv_ruby_parser_t *get_parser(VALUE self)
64
+ {
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;
70
+ }
71
+
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 */
74
+ static VALUE zsv_parser_alloc(VALUE klass)
75
+ {
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;
98
+ }
99
+
100
+ /*
101
+ * call-seq:
102
+ * ZSV::Parser.new(source, **options) -> parser
103
+ *
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.
111
+ */
112
+ static VALUE rb_zsv_parser_initialize(int argc, VALUE *argv, VALUE self)
113
+ {
114
+ VALUE source, opts;
115
+ rb_scan_args(argc, argv, "11", &source, &opts);
116
+
117
+ zsv_ruby_parser_t *parser = get_parser_struct(self);
118
+
119
+ if (RB_TYPE_P(source, T_STRING)) {
120
+ if (zsv_string_is_csv_data(source)) {
121
+ zsv_parser_init_string(parser, source, opts);
122
+ } else {
123
+ zsv_parser_init_path(parser, source, opts);
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);
129
+ } else {
130
+ rb_raise(rb_eTypeError, "expected a String, path or IO-like object, got %s",
131
+ rb_obj_classname(source));
132
+ }
133
+
134
+ return self;
135
+ }
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
+
179
+ /*
180
+ * call-seq:
181
+ * parser.shift -> array or hash or nil
182
+ *
183
+ * Reads and returns the next row. Returns nil at EOF.
184
+ */
185
+ static VALUE rb_zsv_parser_shift(VALUE self)
186
+ {
187
+ return zsv_parser_shift(get_parser(self));
188
+ }
189
+
190
+ /*
191
+ * call-seq:
192
+ * parser.each {|row| block } -> parser
193
+ * parser.each -> enumerator
194
+ *
195
+ * Iterates over the remaining rows. Aliased as #each_row.
196
+ */
197
+ static VALUE rb_zsv_parser_each(VALUE self)
198
+ {
199
+ RETURN_ENUMERATOR(self, 0, 0);
200
+
201
+ zsv_ruby_parser_t *parser = get_parser(self);
202
+ VALUE row;
203
+ while (!NIL_P(row = zsv_parser_shift(parser))) {
204
+ rb_yield(row);
205
+ }
206
+ return self;
207
+ }
208
+
209
+ /*
210
+ * call-seq:
211
+ * parser.rewind -> nil
212
+ *
213
+ * Rewinds the parser to the beginning.
214
+ */
215
+ static VALUE rb_zsv_parser_rewind(VALUE self)
216
+ {
217
+ zsv_parser_rewind(get_parser(self));
218
+ return Qnil;
219
+ }
220
+
221
+ /*
222
+ * call-seq:
223
+ * parser.close -> nil
224
+ *
225
+ * Closes the parser and releases resources.
226
+ */
227
+ static VALUE rb_zsv_parser_close(VALUE self)
228
+ {
229
+ zsv_parser_close(get_parser(self));
230
+ return Qnil;
231
+ }
232
+
233
+ /*
234
+ * call-seq:
235
+ * parser.headers -> array or nil
236
+ *
237
+ * Returns the headers if header mode is enabled.
238
+ */
239
+ static VALUE rb_zsv_parser_headers_get(VALUE self)
240
+ {
241
+ return zsv_parser_headers(get_parser(self));
242
+ }
243
+
244
+ /*
245
+ * call-seq:
246
+ * parser.closed? -> bool
247
+ *
248
+ * Returns true if the parser is closed.
249
+ */
250
+ static VALUE rb_zsv_parser_closed_p(VALUE self)
251
+ {
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;
272
+ }
273
+
274
+ /*
275
+ * call-seq:
276
+ * ZSV.foreach(path, **options) {|row| block } -> nil
277
+ * ZSV.foreach(path, **options) -> enumerator
278
+ *
279
+ * Efficiently streams rows from a CSV file.
280
+ */
281
+ static VALUE rb_zsv_foreach(int argc, VALUE *argv, VALUE klass)
282
+ {
283
+ VALUE path, opts;
284
+ rb_scan_args(argc, argv, "11", &path, &opts);
285
+
286
+ RETURN_ENUMERATOR(klass, argc, argv);
287
+
288
+ zsv_ruby_parser_t *parser;
289
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
290
+ zsv_parser_init_path(parser, path, opts);
291
+
292
+ rb_ensure(rb_zsv_parser_each, parser_obj, zsv_close_parser_object, parser_obj);
293
+ return Qnil;
294
+ }
295
+
296
+ /*
297
+ * call-seq:
298
+ * ZSV.parse(string, **options) -> array
299
+ *
300
+ * Parses a CSV string and returns all rows as an array.
301
+ */
302
+ static VALUE rb_zsv_parse(int argc, VALUE *argv, VALUE klass)
303
+ {
304
+ VALUE string, opts;
305
+ (void)klass;
306
+ rb_scan_args(argc, argv, "11", &string, &opts);
307
+
308
+ Check_Type(string, T_STRING);
309
+
310
+ zsv_ruby_parser_t *parser;
311
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
312
+ zsv_parser_init_string(parser, string, opts);
313
+
314
+ return rb_ensure(zsv_read_all, parser_obj, zsv_close_parser_object, parser_obj);
315
+ }
316
+
317
+ /*
318
+ * call-seq:
319
+ * ZSV.read(path, **options) -> array
320
+ *
321
+ * Reads entire CSV file into an array of rows.
322
+ */
323
+ static VALUE rb_zsv_read(int argc, VALUE *argv, VALUE klass)
324
+ {
325
+ VALUE path, opts;
326
+ (void)klass;
327
+ rb_scan_args(argc, argv, "11", &path, &opts);
328
+
329
+ zsv_ruby_parser_t *parser;
330
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
331
+ zsv_parser_init_path(parser, path, opts);
332
+
333
+ return rb_ensure(zsv_read_all, parser_obj, zsv_close_parser_object, parser_obj);
334
+ }
335
+
336
+ /*
337
+ * call-seq:
338
+ * ZSV.open(path, mode="r", **options) -> parser
339
+ * ZSV.open(path, mode="r", **options) {|parser| block } -> result
340
+ *
341
+ * Opens a CSV file for reading. If a block is given, the parser is
342
+ * automatically closed after the block completes.
343
+ */
344
+ static VALUE rb_zsv_open(int argc, VALUE *argv, VALUE klass)
345
+ {
346
+ VALUE path, mode, opts;
347
+ (void)klass;
348
+ rb_scan_args(argc, argv, "11:", &path, &mode, &opts);
349
+
350
+ /* If mode is a hash, it's actually the options */
351
+ if (!NIL_P(mode) && RB_TYPE_P(mode, T_HASH)) {
352
+ opts = mode;
353
+ mode = Qnil;
354
+ }
355
+
356
+ /* Currently only support read mode */
357
+ if (!NIL_P(mode) && strcmp(StringValueCStr(mode), "r") != 0) {
358
+ rb_raise(rb_eNotImpError, "Only read mode is currently supported");
359
+ }
360
+
361
+ zsv_ruby_parser_t *parser;
362
+ VALUE parser_obj = zsv_new_parser_object(cParser, &parser);
363
+ zsv_parser_init_path(parser, path, opts);
364
+
365
+ if (rb_block_given_p()) {
366
+ return rb_ensure(rb_yield, parser_obj, zsv_close_parser_object, parser_obj);
367
+ }
368
+
369
+ return parser_obj;
370
+ }
371
+
372
+ /* Initialize the extension */
373
+ void Init_zsv(void)
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
+
385
+ /* Define module */
386
+ mZSV = rb_define_module("ZSV");
387
+
388
+ /* Define Parser class */
389
+ cParser = rb_define_class_under(mZSV, "Parser", rb_cObject);
390
+ rb_include_module(cParser, rb_mEnumerable);
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);
394
+ rb_define_method(cParser, "initialize", rb_zsv_parser_initialize, -1);
395
+ rb_define_method(cParser, "shift", rb_zsv_parser_shift, 0);
396
+ rb_define_method(cParser, "each", rb_zsv_parser_each, 0);
397
+ rb_define_alias(cParser, "each_row", "each");
398
+ rb_define_method(cParser, "rewind", rb_zsv_parser_rewind, 0);
399
+ rb_define_method(cParser, "close", rb_zsv_parser_close, 0);
400
+ rb_define_method(cParser, "headers", rb_zsv_parser_headers_get, 0);
401
+ rb_define_method(cParser, "closed?", rb_zsv_parser_closed_p, 0);
402
+
403
+ /* Define module methods */
404
+ rb_define_module_function(mZSV, "foreach", rb_zsv_foreach, -1);
405
+ rb_define_module_function(mZSV, "parse", rb_zsv_parse, -1);
406
+ rb_define_module_function(mZSV, "read", rb_zsv_read, -1);
407
+ rb_define_module_function(mZSV, "open", rb_zsv_open, -1);
408
+
409
+ /* Define exceptions */
410
+ eZSVError = rb_define_class_under(mZSV, "Error", rb_eStandardError);
411
+ eMalformedCSVError = rb_define_class_under(mZSV, "MalformedCSVError", eZSVError);
412
+ eInvalidEncodingError = rb_define_class_under(mZSV, "InvalidEncodingError", eZSVError);
413
+
414
+ /* Initialize submodules */
415
+ Init_zsv_options();
416
+ Init_zsv_parser();
417
+ }
Binary file
Binary file
Binary file
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