#include "ctxstream.hpp" #include 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 plan(const std::string& text, const ManifestOptions& opt) { std::vector 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