summaryrefslogtreecommitdiffstats
path: root/contrib/libs/apache/arrow_next/cpp/src/arrow/csv/chunker.cc
blob: 4f6abb2dc21753c03ae7d5181c60d56ac0233da0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include "contrib/libs/apache/arrow_next/cpp/src/arrow/csv/chunker.h"

#include <algorithm>
#include <cstdint>
#include <memory>
#include <string_view>
#include <utility>

#include "contrib/libs/apache/arrow_next/cpp/src/arrow/csv/lexing_internal.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/status.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/logging.h"

namespace arrow20 {
namespace csv {

namespace {

// NOTE: csvmonkey (https://github.com/dw/csvmonkey) has optimization ideas

template <typename SpecializedOptions>
class Lexer {
 public:
  enum State {
    FIELD_START,
    IN_FIELD,
    AT_ESCAPE,
    IN_QUOTED_FIELD,
    AT_QUOTED_QUOTE,
    AT_QUOTED_ESCAPE
  };

  explicit Lexer(const ParseOptions& options)
      : options_(options), bulk_filter_(options_) {
    DCHECK_EQ(SpecializedOptions::quoting, options_.quoting);
    DCHECK_EQ(SpecializedOptions::escaping, options_.escaping);
  }

  void Reset() { state_ = FIELD_START; }

  // Decide whether it's worth using a bulk filter over the given data area
  bool ShouldUseBulkFilter(const char* data, const char* data_end) {
    constexpr int32_t kWordSize = static_cast<int32_t>(sizeof(BulkWordType));

    // Only probe the 32 first words and assume they are representative of the rest
    const int64_t n_words = std::min<int64_t>(32, (data_end - data) / kWordSize);
    int64_t n_skips = 0;
    const auto words = reinterpret_cast<const BulkWordType*>(data);
    for (int64_t i = 0; i < n_words - 3; i += 4) {
      const auto a = words[i + 0];
      const auto b = words[i + 1];
      const auto c = words[i + 2];
      const auto d = words[i + 3];
      n_skips += !bulk_filter_.Matches(a) + !bulk_filter_.Matches(b) +
                 !bulk_filter_.Matches(c) + !bulk_filter_.Matches(d);
    }
    return (n_skips * 4 + 1 >= n_words);
  }

  template <bool UseBulkFilter = true>
  const char* ReadLine(const char* data, const char* data_end) {
    // The parsing state machine
    char c;
    DCHECK_GT(data_end - data, 0);
    if (ARROW_PREDICT_TRUE(state_ == FIELD_START)) {
      goto FieldStart;
    }
    switch (state_) {
      case FIELD_START:
        goto FieldStart;
      case IN_FIELD:
        goto InField;
      case AT_ESCAPE:
        // will never reach here if escaping = false
        // just to hint the compiler to remove dead code
        if (!SpecializedOptions::escaping) return nullptr;
        goto AtEscape;
      case IN_QUOTED_FIELD:
        if (!SpecializedOptions::quoting) return nullptr;
        goto InQuotedField;
      case AT_QUOTED_QUOTE:
        if (!SpecializedOptions::quoting) return nullptr;
        goto AtQuotedQuote;
      case AT_QUOTED_ESCAPE:
        if (!SpecializedOptions::quoting) return nullptr;
        goto AtQuotedEscape;
    }

  FieldStart:
    if (!SpecializedOptions::quoting) {
      goto InField;
    } else {
      // At the start of a field
      if (ARROW_PREDICT_FALSE(data == data_end)) {
        state_ = FIELD_START;
        goto AbortLine;
      }
      // Quoting is only recognized at start of field
      if (*data == options_.quote_char) {
        data++;
        goto InQuotedField;
      } else {
        goto InField;
      }
    }

  InField:
    // Inside a non-quoted part of a field
    if (UseBulkFilter) {
      const char* bulk_end = RunBulkFilter(data, data_end);
      if (ARROW_PREDICT_FALSE(bulk_end == nullptr)) {
        state_ = IN_FIELD;
        goto AbortLine;
      }
      data = bulk_end;
    } else {
      if (ARROW_PREDICT_FALSE(data == data_end)) {
        state_ = IN_FIELD;
        goto AbortLine;
      }
    }
    c = *data++;
    if (SpecializedOptions::escaping && ARROW_PREDICT_FALSE(c == options_.escape_char)) {
      if (ARROW_PREDICT_FALSE(data == data_end)) {
        state_ = AT_ESCAPE;
        goto AbortLine;
      }
      data++;
      goto InField;
    }
    if (ARROW_PREDICT_FALSE(c == '\r')) {
      if (ARROW_PREDICT_TRUE(data != data_end) && *data == '\n') {
        data++;
      }
      goto LineEnd;
    }
    if (ARROW_PREDICT_FALSE(c == '\n')) {
      goto LineEnd;
    }
    // treat delimiter as a normal token if quoting is disabled
    if (ARROW_PREDICT_FALSE(SpecializedOptions::quoting && c == options_.delimiter)) {
      goto FieldEnd;
    }
    goto InField;

  AtEscape:
    // Coming here if last block ended on a non-quoted escape
    data++;
    goto InField;

  InQuotedField:
    // Inside a quoted part of a field
    if (UseBulkFilter) {
      const char* bulk_end = RunBulkFilter(data, data_end);
      if (ARROW_PREDICT_FALSE(bulk_end == nullptr)) {
        state_ = IN_QUOTED_FIELD;
        goto AbortLine;
      }
      data = bulk_end;
    } else {
      if (ARROW_PREDICT_FALSE(data == data_end)) {
        state_ = IN_QUOTED_FIELD;
        goto AbortLine;
      }
    }
    c = *data++;
    if (SpecializedOptions::escaping && ARROW_PREDICT_FALSE(c == options_.escape_char)) {
      if (ARROW_PREDICT_FALSE(data == data_end)) {
        state_ = AT_QUOTED_ESCAPE;
        goto AbortLine;
      }
      data++;
      goto InQuotedField;
    }
    if (ARROW_PREDICT_FALSE(c == options_.quote_char)) {
      if (ARROW_PREDICT_FALSE(data == data_end)) {
        state_ = AT_QUOTED_QUOTE;
        goto AbortLine;
      }
      if (options_.double_quote && *data == options_.quote_char) {
        // Double-quoting
        data++;
      } else {
        // End of single-quoting
        goto InField;
      }
    }
    goto InQuotedField;

  AtQuotedEscape:
    // Coming here if last block ended on a quoted escape
    data++;
    goto InQuotedField;

  AtQuotedQuote:
    // Coming here if last block ended on a quoted quote
    if (options_.double_quote && *data == options_.quote_char) {
      // Double-quoting
      data++;
      goto InQuotedField;
    } else {
      // End of single-quoting
      goto InField;
    }

  FieldEnd:
    // At the end of a field
    goto FieldStart;

  LineEnd:
    state_ = FIELD_START;
    return data;

  AbortLine:
    // Truncated line
    return nullptr;
  }

 protected:
  using BulkFilterType = internal::PreferredBulkFilterType<SpecializedOptions>;
  using BulkWordType = typename BulkFilterType::WordType;

  const char* RunBulkFilter(const char* data, const char* data_end) {
    while (true) {
      if (ARROW_PREDICT_FALSE(static_cast<size_t>(data_end - data) <
                              sizeof(BulkWordType))) {
        if (ARROW_PREDICT_FALSE(data == data_end)) {
          return nullptr;
        }
        return data;
      }
      BulkWordType word;
      memcpy(&word, data, sizeof(BulkWordType));
      if (bulk_filter_.Matches(word)) {
        return data;
      }
      // No special chars
      data += sizeof(BulkWordType);
    }
  }

  const ParseOptions& options_;
  const BulkFilterType bulk_filter_;
  State state_ = FIELD_START;
};

// A BoundaryFinder implementation that assumes CSV cells can contain raw newlines,
// and uses actual CSV lexing to delimit them.
template <typename SpecializedOptions>
class LexingBoundaryFinder : public BoundaryFinder {
 public:
  explicit LexingBoundaryFinder(ParseOptions options)
      : options_(std::move(options)), lexer_(options_) {}

  Status FindFirst(std::string_view partial, std::string_view block,
                   int64_t* out_pos) override {
    lexer_.Reset();
    if (lexer_.ShouldUseBulkFilter(block.data(), block.data() + block.size())) {
      return FindFirstInternal<true>(partial, block, out_pos);
    } else {
      return FindFirstInternal<false>(partial, block, out_pos);
    }
  }

  template <bool UseBulkFilter>
  Status FindFirstInternal(std::string_view partial, std::string_view block,
                           int64_t* out_pos) {
    const char* line_end = lexer_.template ReadLine<UseBulkFilter>(
        partial.data(), partial.data() + partial.size());
    DCHECK_EQ(line_end, nullptr);  // Otherwise `partial` is a whole CSV line
    line_end = lexer_.template ReadLine<UseBulkFilter>(block.data(),
                                                       block.data() + block.size());

    if (line_end == nullptr) {
      // No complete CSV line
      *out_pos = -1;
    } else {
      *out_pos = static_cast<int64_t>(line_end - block.data());
      DCHECK_GT(*out_pos, 0);
    }
    return Status::OK();
  }

  Status FindLast(std::string_view block, int64_t* out_pos) override {
    lexer_.Reset();
    if (lexer_.ShouldUseBulkFilter(block.data(), block.data() + block.size())) {
      return FindLastInternal<true>(block, out_pos);
    } else {
      return FindLastInternal<false>(block, out_pos);
    }
  }

  template <bool UseBulkFilter>
  Status FindLastInternal(std::string_view block, int64_t* out_pos) {
    const char* data = block.data();
    const char* const data_end = block.data() + block.size();

    while (data < data_end) {
      const char* line_end = lexer_.template ReadLine<UseBulkFilter>(data, data_end);
      if (line_end == nullptr) {
        // Cannot read any further
        break;
      }
      DCHECK_GT(line_end, data);
      data = line_end;
    }
    if (data == block.data()) {
      // No complete CSV line
      *out_pos = -1;
    } else {
      *out_pos = static_cast<int64_t>(data - block.data());
      DCHECK_GT(*out_pos, 0);
    }
    return Status::OK();
  }

  Status FindNth(std::string_view partial, std::string_view block, int64_t count,
                 int64_t* out_pos, int64_t* num_found) override {
    lexer_.Reset();

    int64_t found = 0;
    const char* data = block.data();
    const char* const data_end = block.data() + block.size();

    const char* line_end;
    if (partial.size()) {
      line_end = lexer_.ReadLine(partial.data(), partial.data() + partial.size());
      DCHECK_EQ(line_end, nullptr);  // Otherwise `partial` is a whole CSV line
    }

    for (; data < data_end && found < count; ++found) {
      line_end = lexer_.ReadLine(data, data_end);
      if (line_end == nullptr) {
        // Cannot read any further
        break;
      }
      DCHECK_GT(line_end, data);
      data = line_end;
    }

    if (data == block.data()) {
      // No complete CSV line
      *out_pos = kNoDelimiterFound;
    } else {
      *out_pos = static_cast<int64_t>(data - block.data());
    }
    *num_found = found;
    return Status::OK();
  }

 protected:
  ParseOptions options_;
  Lexer<SpecializedOptions> lexer_;
};

}  // namespace

std::unique_ptr<Chunker> MakeChunker(const ParseOptions& options) {
  std::shared_ptr<BoundaryFinder> delimiter;
  if (!options.newlines_in_values) {
    delimiter = MakeNewlineBoundaryFinder();
  } else {
    if (options.quoting) {
      if (options.escaping) {
        delimiter = std::make_shared<
            LexingBoundaryFinder<internal::SpecializedOptions<true, true>>>(options);
      } else {
        delimiter = std::make_shared<
            LexingBoundaryFinder<internal::SpecializedOptions<true, false>>>(options);
      }
    } else {
      if (options.escaping) {
        delimiter = std::make_shared<
            LexingBoundaryFinder<internal::SpecializedOptions<false, true>>>(options);
      } else {
        delimiter = std::make_shared<
            LexingBoundaryFinder<internal::SpecializedOptions<false, false>>>(options);
      }
    }
  }
  return std::make_unique<Chunker>(std::move(delimiter));
}

}  // namespace csv
}  // namespace arrow20