emkornfield commented on a change in pull request #9504:
URL: https://github.com/apache/arrow/pull/9504#discussion_r577324567



##########
File path: cpp/src/arrow/csv/writer.cc
##########
@@ -0,0 +1,398 @@
+// 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 "arrow/csv/writer.h"
+#include "arrow/array.h"
+#include "arrow/compute/cast.h"
+#include "arrow/io/interfaces.h"
+#include "arrow/record_batch.h"
+#include "arrow/result.h"
+#include "arrow/result_internal.h"
+#include "arrow/stl_allocator.h"
+#include "arrow/util/make_unique.h"
+
+#include "arrow/visitor_inline.h"
+
+namespace arrow {
+namespace csv {
+// This implementation is intentionally light on configurability to minimize 
the size of
+// the initial PR. Aditional features can be added as there is demand and 
interest to
+// implement them.
+//
+// The algorithm used here at a high level is to break RecordBatches/Tables 
into slices
+// and convert each slice independently.  A slice is then converted to CSV by 
first
+// scanning each column to determine the size of its contents when rendered as 
a string in
+// CSV. For non-string types this requires casting the value to string (which 
is cached).
+// This data is used to understand the precise length of each row and a single 
allocation
+// for the final CSV data buffer. Once the final size is known each column is 
then
+// iterated over again to place its contents into the CSV data buffer. The 
rationale for
+// choosing this approach is it allows for reuse of the cast functionality in 
the compute
+// module // and inline data visiting functionality in the core library. A 
performance
+// comparison has not been done using a naive single-pass approach. This 
approach might
+// still be competitive due to reduction in the number of per row branches 
necessary with
+// a single pass approach. Profiling would likely yield further opportunities 
for
+// optimization with this approach.
+
+namespace {
+
+// Counts the number of characters that need escaping in s.
+int64_t CountEscapes(util::string_view s) {
+  return static_cast<int64_t>(std::count(s.begin(), s.end(), '"'));
+}
+
+// Matching quote pair character length.
+constexpr int64_t kQuoteCount = 2;
+
+// Interface for generating CSV data per column.
+// The intended usage is to iteratively call UpdateRowLengths for a column and
+// then PopulateColumns.
+class ColumnPopulator {
+ public:
+  ColumnPopulator(MemoryPool* pool, char end_char) : end_char_(end_char), 
pool_(pool) {}
+  virtual ~ColumnPopulator() = default;
+  // Adds the number of characters each entry in data will add to to elements
+  // in row_lengths.
+  Status UpdateRowLengths(const Array& data, int32_t* row_lengths) {
+    compute::ExecContext ctx(pool_);
+    // Populators are intented to be applied to reasonably small data.  In 
most cases
+    // threading overhead would not be justified.
+    ctx.set_use_threads(false);
+    ASSIGN_OR_RAISE(
+        std::shared_ptr<Array> casted,
+        compute::Cast(data, /*to_type=*/utf8(), compute::CastOptions(), &ctx));
+    casted_array_ = internal::checked_pointer_cast<StringArray>(casted);
+    return UpdateRowLengths(row_lengths);
+  }
+
+  // Places string data onto each row in output and updates the corresponding 
row
+  // row pointers in preparation for calls to other ColumnPopulators.
+  virtual void PopulateColumns(char** output) const = 0;
+
+ protected:
+  virtual Status UpdateRowLengths(int32_t* row_lengths) = 0;
+  std::shared_ptr<StringArray> casted_array_;
+  const char end_char_;
+
+ private:
+  MemoryPool* const pool_;
+};
+
+// Copies the contents of to out properly escaping any necessary charaters.
+char* Escape(arrow::util::string_view s, char* out) {
+  for (const char* val = s.data(); val < s.data() + s.length(); val++, out++) {
+    if (*val == '"') {
+      *out = *val;
+      out++;
+    }
+    *out = *val;
+  }
+  return out;
+}
+
+// Populator for non-string types.  This populator relies on compute Cast 
functionality to
+// String if it doesn't exist it will be an error.  it also assumes the 
resulting string
+// from a cast does not require quoting or escaping.
+class UnquotedColumnPopulator : public ColumnPopulator {
+ public:
+  explicit UnquotedColumnPopulator(MemoryPool* memory_pool, char end_char)
+      : ColumnPopulator(memory_pool, end_char) {}
+  Status UpdateRowLengths(int32_t* row_lengths) override {
+    for (int x = 0; x < casted_array_->length(); x++) {
+      row_lengths[x] += casted_array_->value_length(x);
+    }
+    return Status::OK();
+  }
+
+  void PopulateColumns(char** rows) const override {
+    VisitArrayDataInline<StringType>(
+        *casted_array_->data(),
+        [&](arrow::util::string_view s) {
+          int64_t next_column_offset = s.length() + /*end_char*/ 1;
+          memcpy(*rows, s.data(), s.length());
+          *(*rows + s.length()) = end_char_;
+          *rows += next_column_offset;
+          rows++;
+        },
+        [&]() {
+          // Nulls are empty (unquoted) to distinguish with empty string.
+          **rows = end_char_;
+          *rows += 1;
+          rows++;
+        });
+  }
+};
+
+// Strings need special handling to ensure they are escaped properly.
+// This class handles escaping assuming that all strings will be quoted
+// and that the only character within the string that needs to escaped is
+// a quote character (") and escaping is done my adding another quote.
+class QuotedColumnPopulator : public ColumnPopulator {
+ public:
+  QuotedColumnPopulator(MemoryPool* pool, char end_char)
+      : ColumnPopulator(pool, end_char) {}
+
+  Status UpdateRowLengths(int32_t* row_lengths) override {
+    const StringArray& input = *casted_array_;
+    extra_chars_count_.resize(input.length());
+    auto extra_chars = extra_chars_count_.begin();
+    VisitArrayDataInline<StringType>(
+        *input.data(),
+        [&](arrow::util::string_view s) {
+          int64_t escaped_count = CountEscapes(s);
+          // TODO: Maybe use 64 bit row lengths or safe cast?
+          *extra_chars = static_cast<int>(escaped_count) + kQuoteCount;
+          extra_chars++;
+        },
+        [&]() {
+          *extra_chars = 0;
+          extra_chars++;
+        });
+
+    for (int x = 0; x < input.length(); x++) {
+      row_lengths[x] += extra_chars_count_[x] + input.value_length(x);
+    }
+    return Status::OK();
+  }
+
+  void PopulateColumns(char** rows) const override {
+    const int32_t* extra_chars = extra_chars_count_.data();
+    VisitArrayDataInline<StringType>(
+        *(casted_array_->data()),
+        [&](arrow::util::string_view s) {
+          int64_t next_column_offset = *extra_chars + s.length() + 
/*end_char*/ 1;
+          **rows = '"';
+          if (*extra_chars == kQuoteCount) {

Review comment:
       yes, that is potentially simpler.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to