File size: 1,971 Bytes
829dbce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#include "ctxstream.hpp"

#include <algorithm>

namespace ctxstream {

// Walk back from the target cut to the nearest record delimiter, so a segment
// never ends mid-row. A row split across two segments is counted twice or not
// at all, and both are silent corruption of the tally.
static std::size_t snap_to_boundary(const std::string& text, std::size_t target,
                                    const ManifestOptions& opt) {
    if (target >= text.size()) return text.size();
    const std::size_t floor =
        target > opt.boundary_slack ? target - opt.boundary_slack : 0;
    const std::size_t hit = text.rfind(opt.record_delim, target);
    if (hit != std::string::npos && hit >= floor) {
        return hit + opt.record_delim.size();
    }
    // No delimiter within slack: the data is not row-shaped, cut where asked.
    return target;
}

std::vector<Segment> plan(const std::string& text, const ManifestOptions& opt) {
    std::vector<Segment> out;
    if (text.empty() || opt.segment_chars == 0) return out;

    std::size_t pos = 0;
    int index = 0;
    while (pos < text.size()) {
        const std::size_t want = std::min(pos + opt.segment_chars, text.size());
        const std::size_t end = snap_to_boundary(text, want, opt);
        // snap_to_boundary can land at or before pos on pathological input
        // (a single row longer than the segment); force progress.
        const std::size_t stop = end > pos ? end : want;

        Segment s;
        s.index = index++;
        s.overlap_prefix = std::min(pos, opt.overlap_chars);
        s.offset = pos - s.overlap_prefix;
        s.length = stop - s.offset;
        out.push_back(s);

        if (stop >= text.size()) break;
        pos = stop;
    }
    return out;
}

std::string segment_text(const std::string& text, const Segment& s) {
    if (s.offset >= text.size()) return {};
    return text.substr(s.offset, std::min(s.length, text.size() - s.offset));
}

}  // namespace ctxstream