278 : out(&_out), quote_minimal(_quote_minimal) {}
281#if CSV_EXCEPTIONS_ENABLED
282 template<
typename T = OutputStream,
283 csv::enable_if_t<std::is_same<T, std::ofstream>::value,
int> = 0>
284 DelimWriter(
const std::string& filename,
bool _quote_minimal =
true)
285 :
DelimWriter(std::unique_ptr<OutputStream>(new OutputStream(filename, std::ios::out)),
287 if (!owned_out->is_open())
288 internals::throw_failed_open_for_writing(filename);
295 template<
typename T = OutputStream,
296 csv::enable_if_t<std::is_same<T, std::ofstream>::value,
int> = 0>
298 const std::string& filename,
CSVError& error,
bool quote_minimal =
true
301 std::unique_ptr<OutputStream> stream(
new OutputStream(filename, std::ios::out));
302 if (!stream->is_open()) {
304 std::string(internals::ERROR_FAILED_OPEN_WRITE) + filename);
307 return std::unique_ptr<DelimWriter>(
new DelimWriter(std::move(stream), quote_minimal));
314 : owned_out(std::move(other.owned_out)),
316 quote_minimal(other.quote_minimal),
317 auto_flush_(other.auto_flush_),
318 batch_buffer_(std::move(other.batch_buffer_)) {
319 if (owned_out && out) {
320 out = owned_out.get();
323 other.quote_minimal =
true;
326 DelimWriter& operator=(DelimWriter&& other)
noexcept {
327 if (
this == &other)
return *
this;
329 owned_out = std::move(other.owned_out);
331 quote_minimal = other.quote_minimal;
332 auto_flush_ = other.auto_flush_;
333 batch_buffer_ = std::move(other.batch_buffer_);
335 if (owned_out && out) {
336 out = owned_out.get();
340 other.quote_minimal =
true;
346 this->auto_flush_ = value;
352 this->auto_flush_ = value;
353 return std::move(*
this);
358 return this->auto_flush_;
365 if (!out || !ready_for_destruction(*out, 0))
return;
377 template<
typename T,
size_t N>
379 write_range_impl(record);
384 template<
typename T,
size_t N>
386 write_range_impl(record);
395#if CSV_EXCEPTIONS_ENABLED
396 template<
typename KeyType>
398 append_range_fields(frame.
columns());
400 flush_batch_if_needed();
406 for (
const auto& row : frame) {
407 append_range_fields(std::vector<std::string>(row));
409 flush_batch_if_needed();
432 csv::enable_if_t<!internals::is_data_frame<typename std::decay<T>::type>::value,
int> = 0>
433 auto write_row(T&& record) ->
decltype(*this << std::forward<T>(record)) {
434 return *this << std::forward<T>(record);
446 template<
typename T,
typename U,
typename... Rest>
448 this->write_tuple<0>(std::forward_as_tuple(
449 std::forward<T>(first), std::forward<U>(second), std::forward<Rest>(rest)...));
469 template<std::ranges::input_range Rows>
472 for (
auto&& row : rows) {
473 append_row_like(row);
474 flush_batch_if_needed();
487 template<std::ranges::input_range Range>
489 requires std::ranges::input_range<Range>
490 && std::convertible_to<std::ranges::range_reference_t<Range>,
csv::string_view> {
491 write_range_impl(container);
496 template<
typename RowLike>
500 append_row_like(row);
513 template<
typename Range>
514 typename std::enable_if<
517 && !std::is_same<Range, std::string>::value
518 && !std::is_same<Range, csv::string_view>::value,
521 write_range_impl(record);
527 template<
typename... T>
529 this->write_tuple<0, T...>(record);
549 csv::enable_if_t<internals::has_checked_csv_fields<T>::value,
int> = 0>
551 return this->checked_write(error, std::forward<T>(record));
554 template<
typename... Args>
556 ->
decltype(this->
write_row(std::forward<Args>(args)...), bool()) {
557 return this->checked_write(error, std::forward<Args>(args)...);
564 template<
typename KeyType>
566 return this->checked_write(error, frame);
571 template<std::ranges::input_range Rows>
575 return this->checked_operation(error, [
this, &rows, &error]() {
576 for (
auto&& row : rows) {
577 if (!this->append_checked_row(row, error, 0))
return false;
578 this->flush_batch_if_needed();
579 if (!this->check_write_status(error))
return false;
581 this->finish_write_call();
589 return this->checked_operation(error, [
this]() {
599 template<
typename T = OutputStream,
600 csv::enable_if_t<std::is_same<T, std::ofstream>::value,
int> = 0>
603 if (!owned_out || !out) {
605 "try_close() requires an open, owned output file.");
608 const bool flushed = this->
try_flush(error);
615 CSV_CATCH((
const std::ios_base::failure& failure), {
619 if (!flushed)
return false;
620 if (owned_out->fail()) {
627 DelimWriter(std::unique_ptr<OutputStream> stream,
bool quote_minimal)
628 : owned_out(std::move(stream)), out(owned_out.get()), quote_minimal(quote_minimal) {}
632 template<
typename Stream>
633 static auto exceptions_disabled(
const Stream& stream,
int)
634 ->
decltype(stream.exceptions(), bool()) {
635 return stream.exceptions() == std::ios_base::goodbit;
638 template<
typename Stream>
639 static bool exceptions_disabled(
const Stream&,
long) {
return true; }
641 template<
typename Stream>
642 static auto ready_for_destruction(
const Stream& stream,
int)
643 ->
decltype(stream.fail(), bool()) {
644#if CSV_EXCEPTIONS_ENABLED
645 return !stream.fail();
647 return !stream.fail() && exceptions_disabled(stream, 0);
651 template<
typename Stream>
652 static bool ready_for_destruction(
const Stream&,
long) {
return true; }
654 template<
typename Fn>
655 bool checked_operation(CSVError& error, Fn&& operation) {
660#if !CSV_EXCEPTIONS_ENABLED
661 if (!exceptions_disabled(*out, 0)) {
663 "Checked CSV output requires a stream with exceptions disabled.");
670 if (!std::forward<Fn>(operation)())
return false;
672 CSV_CATCH((
const std::ios_base::failure& failure), {
675 return this->check_write_status(error);
678 bool check_write_status(CSVError& error)
const {
680 "CSV output stream has failed.");
683 template<
typename... Args>
684 bool checked_write(CSVError& error, Args&&... args) {
685 return this->checked_operation(error, [&]() {
686 return this->checked_write_call(error, std::forward<Args>(args)...);
691 bool checked_write_call(CSVError& error, T&& record) {
692 return this->checked_write_record(std::forward<T>(record), error, 0);
695 template<
typename T,
typename U,
typename... Rest>
696 bool checked_write_call(CSVError&, T&& first, U&& second, Rest&&... rest) {
697 this->
write_row(std::forward<T>(first), std::forward<U>(second), std::forward<Rest>(rest)...);
701 template<
typename KeyType>
702 bool checked_write_record(
const DataFrame<KeyType>& frame, CSVError& error,
int) {
703 append_range_fields(frame.columns());
705 flush_batch_if_needed();
706 if (!this->check_write_status(error))
return false;
707 for (
const auto& row : frame) {
708 if (!this->append_checked_row(row, error, 0))
return false;
709 flush_batch_if_needed();
710 if (!this->check_write_status(error))
return false;
716 template<
typename Row>
717 auto checked_write_record(Row&& row, CSVError& error,
int)
718 ->
decltype(row.try_field(
size_t{0}, error).get_sv(), bool()) {
719 if (!this->append_checked_row(row, error, 0))
return false;
724 template<
typename Row>
725 bool checked_write_record(Row&& row, CSVError&,
long) {
730 template<
typename Row>
731 auto append_checked_row(Row&& row, CSVError& error,
int)
732 ->
decltype(row.try_field(
size_t{0}, error).get_sv(), bool()) {
733 const size_t row_start = batch_buffer_.size();
734 append_range_fields(internals::checked_field_range(row, error));
738 batch_buffer_.resize(row_start);
746 template<
typename Row>
747 bool append_checked_row(Row&& row, CSVError&,
long) {
748 append_row_like(std::forward<Row>(row));
758 template<
typename Range>
759 inline void append_range_fields(Range&& record) {
760 auto it = std::begin(record);
761 auto end = std::end(record);
764 const size_t field_start = batch_buffer_.size();
767 if (it == end) quote_lone_empty_field(field_start);
770 for (; it != end; ++it) {
771 batch_buffer_.push_back(Delim);
779 void quote_lone_empty_field(
size_t field_start) {
780 if (batch_buffer_.size() == field_start) {
781 batch_buffer_.push_back(Quote);
782 batch_buffer_.push_back(Quote);
788 size_t pos = internals::find_next_non_special(in, 0, simd_sentinels_);
790 for (; pos < in.size(); ++pos) {
792 if (ch == Quote || ch == Delim || ch ==
'\r' || ch ==
'\n')
802 template<
typename Range>
803 inline void write_range_impl(
const Range& record) {
804 append_range_fields(record);
811 template<
typename Row>
812 void append_row_like(Row&& row) {
814 append_range_fields(std::forward<Row>(row));
817 append_range_fields(row.to_sv_range());
826 template<
typename Field>
827 void write_field(
const internals::CheckedFieldValue<Field>& in) {
828 in.with_view([
this](
csv::string_view value) { write_escaped_field(value); });
834 !std::is_convertible<T, std::string>::value
835 && !std::is_convertible<T, csv::string_view>::value
838 void write_field(T in) {
839 const std::string serialized = internals::to_string(in);
840 write_raw(serialized);
846 std::is_convertible<T, std::string>::value
847 || std::is_convertible<T, csv::string_view>::value
850 void write_field(T in) {
851 IF_CONSTEXPR(std::is_convertible<T, csv::string_view>::value) {
852 write_escaped_field(in);
855 const std::string serialized(in);
856 write_escaped_field(serialized);
862 batch_buffer_.append(in.data(), in.size());
866 const size_t first_special = find_first_special_for_writer(in);
868 if (first_special == in.size()) {
869 if (!quote_minimal) {
870 batch_buffer_.push_back(Quote);
872 batch_buffer_.push_back(Quote);
879 write_quoted_field(in, first_special);
883 batch_buffer_.push_back(Quote);
885 size_t chunk_start = 0;
886 size_t pos = first_special;
887 while (pos < in.size()) {
888 if (in[pos] == Quote) {
889 write_raw(in.substr(chunk_start, pos - chunk_start));
890 batch_buffer_.push_back(Quote);
891 batch_buffer_.push_back(Quote);
892 chunk_start = pos + 1;
898 write_raw(in.substr(chunk_start));
899 batch_buffer_.push_back(Quote);
903 template<
size_t Index = 0,
typename... T>
904 typename std::enable_if<Index <
sizeof...(T),
void>::type write_tuple(
const std::tuple<T...>& record) {
905 const size_t field_start = batch_buffer_.size();
906 write_field(std::get<Index>(record));
908 CSV_MSVC_PUSH_DISABLE(4127)
909 IF_CONSTEXPR (sizeof...(T) == 1) quote_lone_empty_field(field_start);
912 CSV_MSVC_PUSH_DISABLE(4127)
913 IF_CONSTEXPR (Index + 1 < sizeof...(T)) batch_buffer_.push_back(Delim);
916 this->write_tuple<Index + 1>(record);
920 template<
size_t Index = 0, typename... T>
921 typename std::enable_if<Index == sizeof...(T),
void>::type write_tuple(const std::tuple<T...>& record) {
929 batch_buffer_.push_back(
'\n');
932 void finish_write_call() {
933 if (this->auto_flush_) {
939 flush_batch_if_needed();
943 if (batch_buffer_.empty())
return;
945 out->write(batch_buffer_.data(),
static_cast<std::streamsize
>(batch_buffer_.size()));
946 batch_buffer_.clear();
949 void flush_batch_if_needed() {
950 if (batch_buffer_.size() >= batch_flush_threshold_)
959 std::unique_ptr<OutputStream> owned_out;
965 bool auto_flush_ =
true;
966 static constexpr size_t batch_flush_threshold_ = 64 * 1024;
967 std::string batch_buffer_;
968 internals::SentinelVecs simd_sentinels_{Delim, Quote};