comparison data/fileio/CSVStreamWriter.h @ 1434:0684c6698e3f streaming-csv-writer

Added utility function for splitting a model selection into chunks and writing to a stream.
author Lucas Thompson <dev@lucas.im>
date Tue, 17 Apr 2018 10:03:49 +0100
parents b5283878cca2
children 09c2ba31a711
comparison
equal deleted inserted replaced
1433:c0f69bddea12 1434:0684c6698e3f
14 */ 14 */
15 15
16 #ifndef _CSV_STREAM_WRITER_H_ 16 #ifndef _CSV_STREAM_WRITER_H_
17 #define _CSV_STREAM_WRITER_H_ 17 #define _CSV_STREAM_WRITER_H_
18 18
19 class CSVStreamWriter 19 #include "base/BaseTypes.h"
20 #include "base/Selection.h"
21 #include "base/ProgressReporter.h"
22 #include "base/DataExportOptions.h"
23 #include "data/model/Model.h"
24 #include <QString>
25 #include <algorithm>
26
27 namespace CSV
20 { 28 {
29 using Completed = bool;
21 30
22 }; 31 template <class OutStream>
32 auto writeToStreamInChunks(
33 OutStream& oss,
34 const Model& model,
35 const Selection& extents,
36 ProgressReporter* reporter = nullptr,
37 QString delimiter = ",",
38 DataExportOptions options = DataExportDefaults,
39 const sv_frame_t blockSize = 16384
40 ) -> Completed
41 {
42 if (blockSize <= 0) return false;
43 sv_frame_t readPtr = extents.isEmpty() ?
44 model.getStartFrame() : extents.getStartFrame();
45 sv_frame_t endFrame = extents.isEmpty() ?
46 model.getEndFrame() : extents.getEndFrame();
47 int previousPercentagePoint = 0;
23 48
49 const auto wasCancelled = [&reporter]() {
50 return reporter && reporter->wasCancelled();
51 };
52
53 while (readPtr < endFrame) {
54 if (wasCancelled()) return false;
55
56 const auto start = readPtr;
57 const auto end = std::min(start + blockSize, endFrame);
58
59 oss << model.toDelimitedDataStringSubsetWithOptions(
60 delimiter,
61 options,
62 start,
63 end
64 ) << (end < endFrame ? "\n" : "");
65
66 const auto currentPercentage = 100 * end / endFrame;
67 const bool hasIncreased = currentPercentage > previousPercentagePoint;
68
69 if (hasIncreased) {
70 if (reporter) reporter->setProgress(currentPercentage);
71 previousPercentagePoint = currentPercentage;
72 }
73 readPtr = end;
74 }
75 return !wasCancelled(); // setProgress could process event loop
76 }
77
78 template <class OutStream>
79 auto writeToStreamInChunks(
80 OutStream& oss,
81 const Model& model,
82 ProgressReporter* reporter = nullptr,
83 QString delimiter = ",",
84 DataExportOptions options = DataExportDefaults,
85 const sv_frame_t blockSize = 16384
86 ) -> Completed
87 {
88 const Selection empty;
89 return CSV::writeToStreamInChunks(
90 oss,
91 model,
92 empty,
93 reporter,
94 delimiter,
95 options,
96 blockSize
97 );
98 }
99 } // namespace
24 #endif 100 #endif
25
26