• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

llnl-asr / dftracer-utils / 38350517275

13 Oct 2026 05:15AM UTC coverage: 63.708% (+1.1%) from 62.623%
38350517275

push

github

rayandrew
feat(python): fill the pandas api gaps and print frames like pandas

Adds normalize, translate, wrap and a sketch_quantile group aggregate as
engine kernels, and the rest as compositions of existing ops.

Merging stored sketches now skips every sketch whose accuracy is not the
default, in duql too: keeping the first accuracy seen made the result
depend on row order once a group was split across partial states.

128013 of 248204 branches covered (51.58%)

Branch coverage included in aggregate %.

652 of 696 new or added lines in 15 files covered. (93.68%)

376 existing lines in 32 files now uncovered.

106752 of 120300 relevant lines covered (88.74%)

3382973.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.3
/src/dftracer/utils/dataframe/kernels/string_ops.cpp
1
#include <dftracer/utils/core/common/hash/fnv1a.h>
2
#include <dftracer/utils/core/common/hash/hex64.h>
3
#include <dftracer/utils/dataframe/abi.h>
4
#include <dftracer/utils/dataframe/internal/column_data.h>
5
#include <dftracer/utils/dataframe/internal/string_reader.h>
6
#include <dftracer/utils/dataframe/internal/string_simd.h>
7
#include <dftracer/utils/dataframe/internal/varwidth_offsets.h>
8
#include <dftracer/utils/dataframe/kernels/string_ops.h>
9
#include <dftracer/utils/dataframe/parallel.h>
10
#include <dftracer/utils/duql/pattern_engine.h>
11
#include <dftracer/utils/duql/substr_simd.h>
12
#include <utf8proc.h>
13

14
#include <algorithm>
15
#include <bit>
16
#include <cstdint>
17
#include <cstring>
18
#include <limits>
19
#include <memory>
20
#include <mutex>
21
#include <optional>
22
#include <string>
23
#include <string_view>
24
#include <type_traits>
25
#include <unordered_set>
26
#include <vector>
27

28
// Highway static dispatch (baseline target): only the two
29
// naturally-vectorizable string ops use it - str_len_bytes (adjacent int32
30
// offset difference) and the ASCII case folds (byte compare + conditional add).
31
// Every other op is variable-length per row and is legitimately scalar.
32
#include <hwy/highway.h>
33
namespace hn = hwy::HWY_NAMESPACE;
34

35
namespace duql = dftracer::utils::duql;
36
using duql::detail::substr_find;
37

38
namespace dftracer::utils::dataframe {
39

40
Series str_eq(const Series& v, std::string_view rhs) {
6 ✔
41
    return Series{dftu_series_str_eq(v.handle(), rhs.data(),
9 ✔
42
                                     static_cast<std::int32_t>(rhs.size()))};
9 ✔
43
}
44
Series str_contains(const Series& v, std::string_view needle) {
2 ✔
45
    return Series{dftu_series_str_contains(
1 ✔
46
        v.handle(), needle.data(), static_cast<std::int32_t>(needle.size()))};
2 ✔
47
}
48
Series str_starts_with(const Series& v, std::string_view prefix) {
2 ✔
49
    return Series{dftu_series_str_starts_with(
1 ✔
50
        v.handle(), prefix.data(), static_cast<std::int32_t>(prefix.size()))};
2 ✔
51
}
52

53
}  // namespace dftracer::utils::dataframe
54

55
namespace {
56
using dftracer::utils::dataframe::Buffer;
57
using dftracer::utils::dataframe::buffer_bytes;
58
using dftracer::utils::dataframe::Encoding;
59
using dftracer::utils::dataframe::is_wide_offset_type;
60
using dftracer::utils::dataframe::narrow_varwidth_type;
61
using dftracer::utils::dataframe::offsets_of;
62
using dftracer::utils::dataframe::parallel_backend_installed;
63
using dftracer::utils::dataframe::parallel_for;
64
using dftracer::utils::dataframe::string_int64;
65
using dftracer::utils::dataframe::string_mask;
66
using dftracer::utils::dataframe::TypeId;
67

68
// String or Binary, at either offset width (narrow_varwidth_type folds the
69
// Large variants into the same case).
70
bool is_string_kind(TypeId t) {
20,056 ✔
71
    const TypeId n = narrow_varwidth_type(t);
20,056 ✔
72
    return n == TypeId::String || n == TypeId::Binary;
20,056 ✔
73
}
74

75
// A VIEW or CHUNKED column, or a DICTIONARY over a non-FLAT base, is read
76
// through its FLAT copy.
77
bool needs_flat_copy(const dftu_series& v) {
2,036 ✔
78
    return v.encoding == Encoding::View || v.is_chunked() ||
4,072 !
79
           (v.encoding == Encoding::Dictionary && v.child() &&
2,036 !
80
            v.child()->encoding != Encoding::Flat);
1,018 !
81
}
82

83
// Per-row byte reader over a String/Binary(/Large) column that transparently
84
// resolves a DICTIONARY input (row i -> dictionary entry codes[i]). Reads its
85
// offsets at width `Off`. Nullness comes from the top-level validity bitmap
86
// in both encodings.
87
template <class Off>
88
class RowReader {
89
   public:
90
    explicit RowReader(const dftu_series* v) : v_(v) {
3,915 ✔
91
        if (!is_string_kind(v->type)) return;
2,610 !
92
        if (needs_flat_copy(*v)) {
2,036 !
93
            own_.reset(dftu_series_materialize(v));
×
94
            if (!own_) return;
×
95
            v_ = v = own_.get();
×
96
        }
97
        if (v->encoding == Encoding::Flat && offsets_of<Off>(*v) && v->data) {
2,036 !
98
            off_ = reinterpret_cast<const Off*>(offsets_of<Off>(*v)->data());
2,036 !
99
            data_ = reinterpret_cast<const char*>(v->data->data());
2,036 ✔
100
            ok_ = true;
2,036 ✔
101
        } else if (v->encoding == Encoding::Dictionary && v->child() &&
1,018 !
102
                   offsets_of<Off>(*v->child()) && v->child()->data &&
×
103
                   v->data) {
104
            off_ = reinterpret_cast<const Off*>(
×
105
                offsets_of<Off>(*v->child())->data());
×
106
            data_ = reinterpret_cast<const char*>(v->child()->data->data());
×
107
            codes_ = reinterpret_cast<const std::int32_t*>(v->data->data());
×
108
            ok_ = true;
×
109
        }
110
    }
2,610 ✔
111
    bool ok() const { return ok_; }
2,610 ✔
112
    bool is_null(std::int64_t i) const {
13,000 ✔
113
        if (!v_->validity) return false;
13,000 ✔
114
        const std::uint8_t* bm = v_->validity->data();
11,780 ✔
115
        return ((bm[i >> 3] >> (i & 7)) & 1) == 0;
11,780 ✔
116
    }
6,500 ✔
117
    std::string_view at(std::int64_t i) const {
11,056 ✔
118
        std::int64_t k = codes_ ? codes_[i] : i;
11,056 !
119
        return std::string_view(
16,584 ✔
120
            data_ + off_[k], static_cast<std::size_t>(off_[k + 1] - off_[k]));
11,056 ✔
121
    }
122

123
   private:
124
    std::shared_ptr<dftu_series> own_;
125
    const dftu_series* v_;
126
    const Off* off_ = nullptr;
1,305 ✔
127
    const char* data_ = nullptr;
1,305 ✔
128
    const std::int32_t* codes_ = nullptr;
1,305 ✔
129
    bool ok_ = false;
1,305 ✔
130
};
131

132
// Int64 output column with the same length/validity as `v` (nulls preserved).
133
dftu_series* make_i64(const dftu_series* v,
248 ✔
134
                      const std::vector<std::int64_t>& vals) {
135
    auto* out = new dftu_series();
248 ✔
136
    out->type = TypeId::Int64;
248 ✔
137
    out->encoding = Encoding::Flat;
248 ✔
138
    out->length = v->length;
248 ✔
139
    out->null_count = v->null_count;
248 ✔
140
    out->validity = v->validity;
248 ✔
141
    std::size_t bytes = buffer_bytes(TypeId::Int64, v->length);
248 ✔
142
    out->data = Buffer::allocate(bytes);
248 ✔
143
    if (bytes != 0) std::memcpy(out->data->data(), vals.data(), bytes);
248 ✔
144
    return out;
247 ✔
145
}
146

147
// UInt64 output column with the same length as `v`. `validity` is a fresh
148
// Arrow-layout bitmap the caller owns, or NULL to share `v`'s nulls.
149
dftu_series* make_u64(const dftu_series* v,
102 ✔
150
                      const std::vector<std::uint64_t>& vals,
151
                      const std::uint8_t* validity) {
152
    auto* out = new dftu_series();
102 ✔
153
    out->type = TypeId::Uint64;
102 ✔
154
    out->encoding = Encoding::Flat;
102 ✔
155
    out->length = v->length;
102 ✔
156
    std::size_t bytes = buffer_bytes(TypeId::Uint64, v->length);
102 ✔
157
    out->data = Buffer::allocate(bytes);
102 ✔
158
    if (bytes != 0) std::memcpy(out->data->data(), vals.data(), bytes);
102 ✔
159
    if (validity) {
102 ✔
160
        std::size_t vb = static_cast<std::size_t>((v->length + 7) / 8);
44 ✔
161
        out->validity = Buffer::allocate(vb);
44 ✔
162
        if (vb != 0) std::memcpy(out->validity->data(), validity, vb);
44 ✔
163
    } else {
22 ✔
164
        out->null_count = v->null_count;
58 ✔
165
        out->validity = v->validity;
58 ✔
166
    }
167
    return out;
102 ✔
168
}
169

170
// Flat String output column from one string per row (size == v->length); shares
171
// v's validity so null rows stay null (their bytes are ignored). Always
172
// narrow (int32 offsets): a derived per-row transform's total size is its own
173
// fresh sizing question, not a width the source column forces on it. nullptr
174
// when the bytes pass INT32_MAX.
175
dftu_series* make_string(const dftu_series* v,
266 ✔
176
                         const std::vector<std::string>& parts) {
177
    std::size_t total = 0;
266 ✔
178
    for (const std::string& p : parts) total += p.size();
1,374 ✔
179
    if (!fits_int32_offsets(total)) return nullptr;
266 ✔
180
    auto* out = new dftu_series();
266 ✔
181
    out->type = TypeId::String;
266 ✔
182
    out->encoding = Encoding::Flat;
266 ✔
183
    out->length = v->length;
266 ✔
184
    out->null_count = v->null_count;
266 ✔
185
    out->validity = v->validity;
266 ✔
186
    std::size_t off_bytes =
266 ✔
187
        static_cast<std::size_t>(v->length + 1) * sizeof(std::int32_t);
266 ✔
188
    out->offsets = Buffer::allocate(off_bytes);
266 ✔
189
    out->data = Buffer::allocate(total);
266 ✔
190
    std::int32_t* od = reinterpret_cast<std::int32_t*>(out->offsets->data());
266 ✔
191
    char* bd =
133 ✔
192
        total != 0 ? reinterpret_cast<char*>(out->data->data()) : nullptr;
266 ✔
193
    std::int32_t pos = 0;
266 ✔
194
    od[0] = 0;
266 ✔
195
    for (std::int64_t i = 0; i < v->length; ++i) {
1,374 ✔
196
        const std::string& p = parts[static_cast<std::size_t>(i)];
1,108 ✔
197
        if (!p.empty()) std::memcpy(bd + pos, p.data(), p.size());
1,108 ✔
198
        pos += static_cast<std::int32_t>(p.size());
1,108 ✔
199
        od[i + 1] = pos;
1,108 ✔
200
    }
554 ✔
201
    return out;
266 ✔
202
}
133 ✔
203

204
// ---- SIMD helpers --------------------------------------------------------
205

206
// out[i] = off[i+1] - off[i], widened to int64. Highway over the int32 offsets.
207
void len_bytes_simd(const std::int32_t* off, std::int64_t* out, std::size_t n) {
92 ✔
208
    const hn::ScalableTag<std::int64_t> d64;
209
    const hn::Rebind<std::int32_t, decltype(d64)> d32;
210
    const std::size_t lanes = hn::Lanes(d64);
92 ✔
211
    std::size_t i = 0;
92 ✔
212
    for (; i + lanes <= n; i += lanes) {
3,312 ✔
213
        const auto a = hn::LoadU(d32, off + i + 1);
3,220 !
214
        const auto b = hn::LoadU(d32, off + i);
3,220 !
215
        hn::StoreU(hn::PromoteTo(d64, hn::Sub(a, b)), d64, out + i);
3,220 !
216
    }
1,610 ✔
217
    for (; i < n; ++i) out[i] = static_cast<std::int64_t>(off[i + 1] - off[i]);
122 ✔
218
}
92 ✔
219

220
// UTF-8 character count of a byte range: every byte that is not a continuation
221
// byte ((c & 0xC0) != 0x80) starts a character. Highway compares a block and
222
// folds the mask with CountTrue.
223
std::int64_t count_char_starts(const std::uint8_t* p, std::size_t len) {
1,095,871 ✔
224
    const hn::ScalableTag<std::uint8_t> d;
225
    const auto vc0 = hn::Set(d, 0xC0);
1,095,871 ✔
226
    const auto v80 = hn::Set(d, 0x80);
1,095,893 ✔
227
    const std::size_t lanes = hn::Lanes(d);
1,095,885 ✔
228
    std::int64_t count = 0;
1,095,868 ✔
229
    std::size_t i = 0;
1,095,868 ✔
230
    for (; i + lanes <= len; i += lanes) {
1,659,524 ✔
231
        const auto m = hn::Ne(hn::And(hn::LoadU(d, p + i), vc0), v80);
563,656 !
232
        count += static_cast<std::int64_t>(hn::CountTrue(d, m));
563,656 !
233
    }
281,828 ✔
234
    for (; i < len; ++i)
5,421,614 ✔
235
        if ((p[i] & 0xC0) != 0x80) ++count;
4,325,746 ✔
236
    return count;
1,095,868 ✔
237
}
238

239
// ASCII case fold of a byte buffer: `add` is +32 (upper->lower) or -32
240
// (lower->upper); `lo`/`hi` bound the source case. Non-matching bytes pass
241
// through unchanged (ASCII-only fold).
242
void ascii_fold_simd(const std::uint8_t* in, std::uint8_t* out, std::size_t n,
1,000 ✔
243
                     std::uint8_t lo, std::uint8_t hi, int add) {
244
    const hn::ScalableTag<std::uint8_t> d;
245
    const auto vlo = hn::Set(d, lo);
1,000 ✔
246
    const auto vhi = hn::Set(d, hi);
1,000 ✔
247
    const auto vadd = hn::Set(d, static_cast<std::uint8_t>(add));
1,000 ✔
248
    const std::size_t lanes = hn::Lanes(d);
1,000 ✔
249
    std::size_t i = 0;
1,000 ✔
250
    for (; i + lanes <= n; i += lanes) {
6,702,420 ✔
251
        const auto v = hn::LoadU(d, in + i);
6,701,420 ✔
252
        const auto m = hn::And(hn::Ge(v, vlo), hn::Le(v, vhi));
6,701,420 !
253
        hn::StoreU(hn::IfThenElse(m, hn::Add(v, vadd), v), d, out + i);
6,701,420 !
254
    }
3,350,710 ✔
255
    for (; i < n; ++i) {
8,014 ✔
256
        const std::uint8_t c = in[i];
7,014 ✔
257
        out[i] = (c >= lo && c <= hi) ? static_cast<std::uint8_t>(c + add) : c;
7,014 ✔
258
    }
3,507 ✔
259
}
1,000 ✔
260

261
// Fold that keeps offsets/validity and rewrites only the (byte-length
262
// preserving) data buffer. Fast path SIMD for a FLAT input, preserving the
263
// source's own offset width and buffer (no copy of the offsets); a
264
// DICTIONARY input falls back through make_string (always narrow) per row.
265
template <class Off>
266
dftu_series* ascii_fold_w(const dftu_series* v, std::uint8_t lo,
1,128 ✔
267
                          std::uint8_t hi, int add) {
268
    RowReader<Off> r(v);
1,128 !
269
    if (!r.ok()) return nullptr;
1,128 ✔
270
    if (v->encoding == Encoding::Flat) {
1,016 !
271
        auto* out = new dftu_series();
1,016 !
272
        out->type = v->type;
1,016 ✔
273
        out->encoding = Encoding::Flat;
1,016 ✔
274
        out->length = v->length;
1,016 ✔
275
        out->null_count = v->null_count;
1,016 ✔
276
        out->validity = v->validity;
1,016 ✔
277
        offsets_of<Off>(*out) = offsets_of<Off>(*v);  // byte lengths unchanged
1,016 ✔
278
        const std::size_t data_len = v->data ? v->data->size() : 0;
1,016 !
279
        out->data = Buffer::allocate(data_len);
1,016 !
280
        if (data_len != 0)
1,016 ✔
281
            ascii_fold_simd(v->data->data(), out->data->data(), data_len, lo,
1,500 !
282
                            hi, add);
500 ✔
283
        return out;
1,016 ✔
284
    }
285
    std::vector<std::string> parts(static_cast<std::size_t>(v->length));
×
286
    for (std::int64_t i = 0; i < v->length; ++i) {
×
287
        if (r.is_null(i)) continue;
×
288
        std::string s(r.at(i));
×
289
        for (char& c : s)
×
290
            if (static_cast<std::uint8_t>(c) >= lo &&
×
291
                static_cast<std::uint8_t>(c) <= hi)
×
292
                c = static_cast<char>(c + add);
×
293
        parts[static_cast<std::size_t>(i)] = std::move(s);
×
294
    }
295
    return make_string(v, parts);
×
296
}
1,128 ✔
297

298
dftu_series* ascii_fold(const dftu_series* v, std::uint8_t lo, std::uint8_t hi,
1,128 ✔
299
                        int add) {
300
    return is_wide_offset_type(v->type)
1,128 !
301
               ? ascii_fold_w<std::int64_t>(v, lo, hi, add)
564 !
302
               : ascii_fold_w<std::int32_t>(v, lo, hi, add);
1,128 ✔
303
}
304

305
// Per-row string transform (scalar) at offset width `Off`; null rows pass
306
// through as null. Output is always narrow (see make_string).
307
template <class Off, class Fn>
308
dftu_series* string_transform_w(const dftu_series* v, Fn fn) {
546 ✔
309
    RowReader<Off> r(v);
546 !
310
    if (!r.ok()) return nullptr;
546 !
311
    std::vector<std::string> parts(static_cast<std::size_t>(v->length));
266 !
312
    for (std::int64_t i = 0; i < v->length; ++i) {
1,374 !
313
        if (r.is_null(i)) continue;
1,108 !
314
        parts[static_cast<std::size_t>(i)] = fn(r.at(i));
918 !
315
    }
459 ✔
316
    return make_string(v, parts);
266 !
317
}
546 ✔
318

319
template <class Fn>
320
dftu_series* string_transform(const dftu_series* v, Fn fn) {
546 ✔
321
    return is_wide_offset_type(v->type)
546 !
322
               ? string_transform_w<std::int64_t>(v, fn)
273 !
323
               : string_transform_w<std::int32_t>(v, fn);
546 ✔
324
}
325

326
bool is_ascii_ws(char c) {
780 ✔
327
    return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' ||
780 !
328
           c == '\v';
732 ✔
329
}
330

331
std::string_view lstrip_ws(std::string_view s) {
344 ✔
332
    std::size_t b = 0;
344 ✔
333
    while (b < s.size() && is_ascii_ws(s[b])) ++b;
396 ✔
334
    return s.substr(b);
344 ✔
335
}
336
std::string_view rstrip_ws(std::string_view s) {
344 ✔
337
    std::size_t e = s.size();
344 ✔
338
    while (e > 0 && is_ascii_ws(s[e - 1])) --e;
388 ✔
339
    return s.substr(0, e);
344 ✔
340
}
341

342
std::string replace_literal(std::string_view s, std::string_view pat,
426 ✔
343
                            std::string_view repl, bool all) {
344
    // An empty pattern has no well-defined occurrence; leave the row unchanged
345
    // (also avoids a zero-advance loop in the all-occurrences case).
346
    if (pat.empty()) return std::string(s);
426 !
347
    std::string out;
426 ✔
348
    std::size_t pos = 0;
426 ✔
349
    while (true) {
283 ✔
350
        std::size_t hit = s.find(pat, pos);
566 ✔
351
        if (hit == std::string_view::npos) break;
566 ✔
352
        out.append(s.substr(pos, hit - pos));
194 !
353
        out.append(repl);
194 !
354
        pos = hit + pat.size();
194 ✔
355
        if (!all) break;
194 ✔
356
    }
70 ✔
357
    out.append(s.substr(pos));
426 !
358
    return out;
426 ✔
359
}
639 !
360

361
// The strings whose regex match reached its work limit; their rows turn null.
362
class LimitedRows {
363
   public:
364
    void add(std::string_view s) {
×
365
        std::lock_guard<std::mutex> lock(mu_);
×
366
        rows_.emplace(s);
×
367
    }
×
368

369
    // `out` with every row of `v` whose string is listed made null.
370
    dftu_series* apply(dftu_series* out, const dftu_series* v) const {
724 ✔
371
        if (!out || rows_.empty()) return out;
724 !
372
        dftu_series* ok = string_mask(v, [this](std::string_view s) {
×
373
            return !rows_.contains(std::string(s));
×
374
        });
375
        if (!ok) return out;
×
376
        const std::size_t bytes = buffer_bytes(TypeId::Bool, v->length);
×
377
        auto valid = Buffer::allocate(bytes);
×
378
        for (std::size_t k = 0; k < bytes; ++k) {
×
379
            const std::uint8_t have =
380
                out->validity ? out->validity->data()[k] : std::uint8_t{0xFF};
×
381
            valid->data()[k] =
×
382
                static_cast<std::uint8_t>(ok->data->data()[k] & have);
×
383
        }
384
        std::int64_t nulls = 0;
×
385
        for (std::int64_t i = 0; i < v->length; ++i)
×
386
            if (!((valid->data()[i >> 3] >> (i & 7)) & 1)) ++nulls;
×
387
        delete ok;
×
388
        out->validity = std::move(valid);
×
389
        out->null_count = nulls;
×
390
        return out;
×
391
    }
362 ✔
392

393
   private:
394
    std::mutex mu_;
395
    std::unordered_set<std::string> rows_;
396
};
397

398
// Bool mask of `p` over `v`; a row whose match reached the work limit is null.
399
dftu_series* pattern_predicate(const dftu_series* v,
1,091 ✔
400
                               const duql::CompiledPattern& p) {
401
    DFTU_PER_CHUNK(v, pattern_predicate, p);
1,373 !
402
    // A literal pattern runs inline, with no call per row.
403
    if (const auto t = duql::literal_test(p); t && !t->icase) {
1,014 ✔
404
        const std::string_view lit = t->text;
334 ✔
405
        switch (t->op) {
334 ✔
406
            case duql::LiteralTest::Op::EQUALS:
63 ✔
407
                return string_mask(
126 !
408
                    v, [lit](std::string_view s) { return s == lit; });
450 ✔
409
            case duql::LiteralTest::Op::STARTS_WITH:
67 ✔
410
                return string_mask(v, [lit](std::string_view s) {
7,734 !
411
                    return s.starts_with(lit);
15,200 ✔
412
                });
67 ✔
413
            case duql::LiteralTest::Op::ENDS_WITH:
4 ✔
414
                return string_mask(
8 !
415
                    v, [lit](std::string_view s) { return s.ends_with(lit); });
208 ✔
416
            case duql::LiteralTest::Op::CONTAINS:
33 ✔
417
                return string_mask(v, [lit](std::string_view s) {
1,371 !
418
                    return substr_find(
5,220 ✔
419
                               s.data(), static_cast<std::int64_t>(s.size()),
2,610 ✔
420
                               lit.data(),
1,305 ✔
421
                               static_cast<std::int64_t>(lit.size())) >= 0;
5,220 ✔
422
                });
33 ✔
423
        }
424
    }
425
    // Case-sensitive globs run inline too; SEGMENTS search long strings.
426
    if (!p.icase && p.kind == duql::detail::Kind::GLOB)
679 ✔
427
        return string_mask(v, [toks = p.glob](std::string_view s) {
90 !
428
            return duql::detail::glob_match_t<false, true>(toks, s);
144 ✔
429
        });
6 ✔
430
    if (!p.icase && p.kind == duql::detail::Kind::SEGMENTS)
667 ✔
431
        return string_mask(v, [&p, toks = p.glob](std::string_view s) {
7 !
432
            return s.size() < duql::detail::SIMD_MIN_HAY
8 !
433
                       ? duql::detail::glob_match_t<false, false>(toks, s)
8 !
434
                       : duql::detail::segments_match(p, s);
4 ✔
435
        });
1 ✔
436
    LimitedRows limited;
998 ✔
437
    dftu_series* out = string_mask(v, [&](std::string_view s) {
16,304 !
438
        const auto r = duql::match(p, s);
31,276 ✔
439
        if (r == duql::MatchResult::LIMIT) limited.add(s);
31,276 ✔
440
        return r == duql::MatchResult::YES;
31,275 ✔
441
    });
442
    return limited.apply(out, v);
666 !
443
}
546 ✔
444

445
}  // namespace
446

447
namespace dftracer::utils::dataframe {
448

449
Series str_pattern(const Series& v, const duql::CompiledPattern& p) {
28 ✔
450
    if (!v.valid()) return {};
28 !
451
    return Series{pattern_predicate(v.handle(), p)};
28 ✔
452
}
14 ✔
453

454
}  // namespace dftracer::utils::dataframe
455

456
namespace {
457

458
template <class Off>
459
dftu_series* regex_replace_w(const dftu_series* v,
194 ✔
460
                             const duql::CompiledPattern& re,
461
                             const duql::Substitution& sub) {
462
    RowReader<Off> r(v);
194 !
463
    if (!r.ok()) return nullptr;
194 !
464
    const std::size_t n = static_cast<std::size_t>(v->length);
138 ✔
465
    std::vector<std::int32_t> offsets(n + 1, 0);
138 !
466
    std::string data;
138 ✔
467
    std::string buf;
138 ✔
468
    std::vector<std::uint8_t> valid((n + 7) / 8, 0);
138 !
469
    bool any_null = false;
138 ✔
470
    for (std::size_t i = 0; i < n; ++i) {
856 ✔
471
        bool hit = false;
718 ✔
472
        if (!r.is_null(static_cast<std::int64_t>(i))) {
718 !
473
            const std::string_view s = r.at(static_cast<std::int64_t>(i));
598 !
474
            if (duql::regex_replace(re, sub, s, buf) !=
598 !
475
                duql::MatchResult::LIMIT) {
476
                data.append(buf);
598 !
477
                hit = true;
598 ✔
478
                if (!fits_int32_offsets(data.size())) return nullptr;
598 !
479
            }
299 ✔
480
        }
299 ✔
481
        if (hit)
718 ✔
482
            valid[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
598 ✔
483
        else
484
            any_null = true;
120 ✔
485
        offsets[i + 1] = static_cast<std::int32_t>(data.size());
718 ✔
486
    }
359 ✔
487
    return dftu_series_new_string(DFTU_TYPE_STRING, offsets.data(), data.data(),
263 !
488
                                  static_cast<int64_t>(n),
69 ✔
489
                                  any_null ? valid.data() : nullptr);
194 !
490
}
194 ✔
491

492
dftu_series* regex_replace_flat(const dftu_series* v,
194 ✔
493
                                const duql::CompiledPattern& re,
494
                                const duql::Substitution& sub) {
495
    return is_wide_offset_type(v->type)
194 !
496
               ? regex_replace_w<std::int64_t>(v, re, sub)
97 !
497
               : regex_replace_w<std::int32_t>(v, re, sub);
194 ✔
498
}
499

500
}  // namespace
501

502
namespace dftracer::utils::dataframe {
503

504
Series str_regex_replace(const Series& v, const duql::CompiledPattern& p,
18 ✔
505
                         const duql::Substitution& sub) {
506
    if (!v.valid()) return {};
18 !
507
    const Series flat = v.materialize();
18 !
508
    return Series{regex_replace_flat(flat.handle(), p, sub)};
18 !
509
}
18 ✔
510

511
}  // namespace dftracer::utils::dataframe
512

513
namespace {
514

515
duql::PatternPtr compiled(duql::PatternResult r) {
1,164 ✔
516
    return r ? std::move(*r) : nullptr;
1,164 ✔
517
}
518

519
std::string_view pattern_text(const char* pattern, int32_t len) {
1,164 ✔
520
    return {pattern, static_cast<std::size_t>(len)};
1,164 ✔
521
}
522

523
}  // namespace
524

525
dftu_series* dftu_series_str_eq(const dftu_series* v, const char* rhs,
276 ✔
526
                                int32_t rhs_len) {
527
    std::string_view r(rhs, static_cast<std::size_t>(rhs_len));
276 ✔
528
    return string_mask(v, [r](std::string_view s) { return s == r; });
5,890 !
529
}
530

531
dftu_series* dftu_series_str_contains(const dftu_series* v, const char* needle,
426 ✔
532
                                      int32_t needle_len) {
533
    std::string_view n(needle, static_cast<std::size_t>(needle_len));
426 ✔
534
    return string_mask(v, [n](std::string_view s) {
874,861 !
535
        return substr_find(s.data(), static_cast<std::int64_t>(s.size()),
3,497,726 ✔
536
                           n.data(), static_cast<std::int64_t>(n.size())) >= 0;
3,497,708 ✔
537
    });
426 ✔
538
}
539

540
dftu_series* dftu_series_str_starts_with(const dftu_series* v,
212 ✔
541
                                         const char* prefix,
542
                                         int32_t prefix_len) {
543
    std::string_view p(prefix, static_cast<std::size_t>(prefix_len));
212 ✔
544
    return string_mask(v, [p](std::string_view s) { return s.starts_with(p); });
6,523 !
545
}
546

547
dftu_series* dftu_series_str_ends_with(const dftu_series* v, const char* suffix,
178 ✔
548
                                       int32_t suffix_len) {
549
    std::string_view p(suffix, static_cast<std::size_t>(suffix_len));
178 ✔
550
    return string_mask(v, [p](std::string_view s) { return s.ends_with(p); });
3,071 !
551
}
552

553
dftu_series* dftu_series_str_matches(const dftu_series* v, const char* pattern,
204 ✔
554
                                     int32_t pattern_len) {
555
    const auto p = compiled(duql::compile_regex(
204 !
556
        pattern_text(pattern, pattern_len), false, /*whole=*/true));
204 !
557
    if (!p) return nullptr;
204 ✔
558
    return pattern_predicate(v, *p);
204 !
559
}
204 ✔
560

561
namespace {
562

563
// The capture `group` of the first `re` match in each row, null where the row
564
// is null or does not match: a String column with its own validity.
565
template <class Off>
566
dftu_series* str_extract_w(const dftu_series* v,
32 ✔
567
                           const duql::CompiledPattern& re, std::size_t group) {
568
    RowReader<Off> r(v);
32 !
569
    if (!r.ok()) return nullptr;
32 !
570
    const std::size_t n = static_cast<std::size_t>(v->length);
32 ✔
571
    std::vector<std::int32_t> offsets(n + 1, 0);
32 !
572
    std::string data;
32 ✔
573
    std::vector<std::uint8_t> valid((n + 7) / 8, 0);
32 !
574
    bool any_null = false;
32 ✔
575
    for (std::size_t i = 0; i < n; ++i) {
4,432 ✔
576
        bool hit = false;
4,400 ✔
577
        if (!r.is_null(static_cast<std::int64_t>(i))) {
4,400 ✔
578
            const std::string_view s = r.at(static_cast<std::int64_t>(i));
3,772 ✔
579
            std::string_view m;
3,772 ✔
580
            if (duql::extract(re, s, group, m) == duql::MatchResult::YES) {
3,772 !
581
                data.append(m);
3,176 !
582
                hit = true;
3,176 ✔
583
                if (!fits_int32_offsets(data.size())) return nullptr;
3,176 !
584
            }
1,588 ✔
585
        }
1,886 ✔
586
        if (hit)
4,400 ✔
587
            valid[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
3,176 ✔
588
        else
589
            any_null = true;
1,224 ✔
590
        offsets[i + 1] = static_cast<std::int32_t>(data.size());
4,400 ✔
591
    }
2,200 ✔
592
    return dftu_series_new_string(DFTU_TYPE_STRING, offsets.data(), data.data(),
60 !
593
                                  static_cast<int64_t>(n),
16 ✔
594
                                  any_null ? valid.data() : nullptr);
44 !
595
}
32 ✔
596

597
}  // namespace
598

599
dftu_series* dftu_series_str_extract(const dftu_series* v, const char* pattern,
154 ✔
600
                                     int32_t pattern_len, int64_t group) {
601
    if (!v || !pattern || group < 0) return nullptr;
154 !
602
    DFTU_FLAT_OPERAND(
154 !
603
        v, flat_v,
604
        dftu_series_str_extract(flat_v, pattern, pattern_len, group));
605
    const auto re = compiled(
63 !
606
        duql::compile_regex(pattern_text(pattern, pattern_len), false));
126 !
607
    if (!re) return nullptr;
126 ✔
608
    const auto g = static_cast<std::size_t>(group);
124 ✔
609
    if (g > duql::capture_count(*re)) return nullptr;
124 !
610
    return is_wide_offset_type(v->type)
48 !
611
               ? str_extract_w<std::int64_t>(v, *re, g)
16 !
612
               : str_extract_w<std::int32_t>(v, *re, g);
32 !
613
}
140 ✔
614

615
dftu_series* dftu_series_str_regex_replace(const dftu_series* v,
220 ✔
616
                                           const char* pattern,
617
                                           int32_t pattern_len, const char* to,
618
                                           int32_t to_len) {
619
    if (!v || !pattern || !to) return nullptr;
220 !
620
    DFTU_FLAT_OPERAND(v, flat_v,
220 !
621
                      dftu_series_str_regex_replace(flat_v, pattern,
622
                                                    pattern_len, to, to_len));
623
    const auto re = compiled(
96 !
624
        duql::compile_regex(pattern_text(pattern, pattern_len), false));
192 !
625
    if (!re) return nullptr;
192 ✔
626
    auto sub = duql::compile_substitution(
93 !
627
        *re, std::string_view(to, static_cast<std::size_t>(to_len)));
186 !
628
    if (!sub) return nullptr;
186 ✔
629
    return regex_replace_flat(v, *re, *sub);
176 !
630
}
206 ✔
631

632
dftu_series* dftu_series_str_search(const dftu_series* v, const char* pattern,
310 ✔
633
                                    int32_t pattern_len) {
634
    const auto p = compiled(
155 !
635
        duql::compile_regex(pattern_text(pattern, pattern_len), false));
310 !
636
    if (!p) return nullptr;
310 ✔
637
    return pattern_predicate(v, *p);
310 !
638
}
310 ✔
639

640
dftu_series* dftu_series_str_like(const dftu_series* v, const char* pattern,
270 ✔
641
                                  int32_t pattern_len) {
642
    const auto p = compiled(
135 !
643
        duql::compile_like(pattern_text(pattern, pattern_len), false, '\\'));
270 !
644
    if (!p) return nullptr;
270 ✔
645
    return pattern_predicate(v, *p);
268 !
646
}
270 ✔
647

648
dftu_series* dftu_series_str_len_bytes(const dftu_series* v) {
224 ✔
649
    // FLAT, narrow offsets: adjacent int32 offset difference, vectorized.
650
    // Every other case (DICTIONARY, or a wide-offset FLAT column) is scalar;
651
    // a Large* column's row count is bounded by int32 either way, only its
652
    // byte offsets are not, so the SIMD int32 path stays narrow-only.
653
    if (v->encoding == Encoding::Flat && v->offsets && !v->wide_offsets()) {
224 ✔
654
        std::vector<std::int64_t> vals(static_cast<std::size_t>(v->length), 0);
96 !
655
        if (v->length > 0)
96 ✔
656
            len_bytes_simd(
92 !
657
                reinterpret_cast<const std::int32_t*>(v->offsets->data()),
92 ✔
658
                vals.data(), static_cast<std::size_t>(v->length));
92 ✔
659
        // Null rows keep 0 length regardless; validity marks them null.
660
        return make_i64(v, vals);
96 !
661
    }
96 ✔
662
    return string_int64(v, [](std::string_view s) {
917 ✔
663
        return static_cast<std::int64_t>(s.size());
1,576 ✔
664
    });
64 ✔
665
}
112 ✔
666

667
dftu_series* dftu_series_str_len_chars(const dftu_series* v) {
334 ✔
668
    // FLAT, narrow offsets: count non-continuation bytes per row with the
669
    // vectorized scan. DICTIONARY and wide-offset columns take the scalar
670
    // per-row path.
671
    if (v->encoding == Encoding::Flat && v->offsets && !v->wide_offsets() &&
410 !
672
        v->data) {
152 ✔
673
        const std::int32_t* off =
76 ✔
674
            reinterpret_cast<const std::int32_t*>(v->offsets->data());
152 ✔
675
        const std::uint8_t* data = v->data->data();
151 ✔
676
        std::vector<std::int64_t> vals(static_cast<std::size_t>(v->length), 0);
152 !
677
        for (std::int64_t i = 0; i < v->length; ++i)
1,096,026 ✔
678
            vals[static_cast<std::size_t>(i)] = count_char_starts(
1,095,884 !
679
                data + off[i], static_cast<std::size_t>(off[i + 1] - off[i]));
1,095,880 !
680
        return make_i64(v, vals);
146 !
681
    }
151 ✔
682
    return string_int64(v, [](std::string_view s) {
59,412 ✔
683
        std::int64_t count = 0;
118,460 ✔
684
        for (unsigned char c : s)
1,792,667 ✔
685
            if ((c & 0xC0) != 0x80) ++count;  // non-continuation byte
1,674,207 ✔
686
        return count;
118,459 ✔
687
    });
91 ✔
688
}
167 ✔
689

690
dftu_series* dftu_series_str_find(const dftu_series* v, const char* needle,
194 ✔
691
                                  int32_t needle_len) {
692
    std::string_view n(needle, static_cast<std::size_t>(needle_len));
194 ✔
693
    return string_int64(v, [n](std::string_view s) {
71,379 !
694
        return substr_find(s.data(), static_cast<std::int64_t>(s.size()),
213,449 ✔
695
                           n.data(), static_cast<std::int64_t>(n.size()));
213,426 ✔
696
    });
194 ✔
697
}
698

699
namespace {
700
template <class Off>
701
dftu_series* fnv1a_w(const dftu_series* v) {
124 ✔
702
    RowReader<Off> r(v);
124 !
703
    if (!r.ok()) return nullptr;
124 ✔
704
    std::vector<std::uint64_t> vals(static_cast<std::size_t>(v->length), 0);
54 !
705
    for (std::int64_t i = 0; i < v->length; ++i) {
318 ✔
706
        if (r.is_null(i)) continue;
264 ✔
707
        vals[static_cast<std::size_t>(i)] =
232 ✔
708
            dftracer::utils::hash::fnv1a_hash(r.at(i));
232 !
709
    }
116 ✔
710
    return make_u64(v, vals, nullptr);
54 !
711
}
124 ✔
712
}  // namespace
713

714
dftu_series* dftu_series_fnv1a(const dftu_series* v) {
156 ✔
715
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_fnv1a(flat_v));
156 ✔
716

717
    return is_wide_offset_type(v->type) ? fnv1a_w<std::int64_t>(v)
124 ✔
718
                                        : fnv1a_w<std::int32_t>(v);
121 ✔
719
}
78 ✔
720

721
namespace {
722
template <class Off>
723
dftu_series* hex64_parse_w(const dftu_series* v) {
104 ✔
724
    RowReader<Off> r(v);
104 !
725
    if (!r.ok()) return nullptr;
104 ✔
726
    std::vector<std::uint64_t> vals(static_cast<std::size_t>(v->length), 0);
48 !
727
    std::size_t bitmap_bytes = static_cast<std::size_t>((v->length + 7) / 8);
48 ✔
728
    std::vector<std::uint8_t> valid(bitmap_bytes, 0);
48 !
729
    std::int64_t nulls = 0;
48 ✔
730
    for (std::int64_t i = 0; i < v->length; ++i) {
246 ✔
731
        std::optional<std::uint64_t> parsed;
198 ✔
732
        if (!r.is_null(i)) parsed = dftracer::utils::hash::parse_hex64(r.at(i));
198 !
733
        if (!parsed) {
198 ✔
734
            ++nulls;
182 ✔
735
            continue;
182 ✔
736
        }
737
        vals[static_cast<std::size_t>(i)] = *parsed;
16 ✔
738
        valid[static_cast<std::size_t>(i >> 3)] |=
16 ✔
739
            static_cast<std::uint8_t>(1u << (i & 7));
16 ✔
740
    }
8 ✔
741
    dftu_series* out = make_u64(v, vals, valid.data());
48 !
742
    out->null_count = nulls;
48 ✔
743
    return out;
48 ✔
744
}
104 ✔
745
}  // namespace
746

747
dftu_series* dftu_series_hex64_parse(const dftu_series* v) {
132 ✔
748
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_hex64_parse(flat_v));
132 ✔
749

750
    return is_wide_offset_type(v->type) ? hex64_parse_w<std::int64_t>(v)
104 !
751
                                        : hex64_parse_w<std::int32_t>(v);
104 ✔
752
}
66 ✔
753

754
dftu_series* dftu_series_hex64_format(const dftu_series* v) {
126 ✔
755
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_hex64_format(flat_v));
126 ✔
756

757
    using dftracer::utils::hash::format_hex64;
758
    using dftracer::utils::hash::HEX64_DIGITS;
759
    if (!v || (v->type != TypeId::Uint64 && v->type != TypeId::Int64)) {
98 !
760
        return nullptr;
64 ✔
761
    }
762
    if (v->encoding != Encoding::Flat || !v->data) return nullptr;
34 !
763

764
    const std::size_t n = static_cast<std::size_t>(v->length);
34 ✔
765
    const std::size_t total = n * HEX64_DIGITS;
34 ✔
766
    // Every row is exactly HEX64_DIGITS bytes, so the byte total is known up
767
    // front; refuse rather than overflow the int32 offsets Arrow uses here.
768
    if (total > static_cast<std::size_t>(INT32_MAX)) return nullptr;
34 !
769

770
    const std::uint64_t* src =
17 ✔
771
        reinterpret_cast<const std::uint64_t*>(v->data->data());
34 ✔
772
    auto* out = new dftu_series();
34 ✔
773
    out->type = TypeId::String;
34 ✔
774
    out->encoding = Encoding::Flat;
34 ✔
775
    out->length = v->length;
34 ✔
776
    out->null_count = v->null_count;
34 ✔
777
    out->validity = v->validity;
34 ✔
778
    out->offsets = Buffer::allocate((n + 1) * sizeof(std::int32_t));
34 ✔
779
    out->data = Buffer::allocate(total);
34 ✔
780
    std::int32_t* od = reinterpret_cast<std::int32_t*>(out->offsets->data());
34 ✔
781
    char* bd =
17 ✔
782
        total != 0 ? reinterpret_cast<char*>(out->data->data()) : nullptr;
34 ✔
783
    for (std::size_t i = 0; i < n; ++i) {
164 ✔
784
        od[i] = static_cast<std::int32_t>(i * HEX64_DIGITS);
130 ✔
785
        format_hex64(src[i], bd + i * HEX64_DIGITS);
130 ✔
786
    }
65 ✔
787
    od[n] = static_cast<std::int32_t>(total);
34 ✔
788
    return out;
34 ✔
789
}
63 ✔
790

791
dftu_series* dftu_series_to_lowercase(const dftu_series* v) {
1,780 ✔
792
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_to_lowercase(flat_v));
1,780 ✔
793

794
    return ascii_fold(v, 'A', 'Z', 32);
946 ✔
795
}
890 ✔
796

797
dftu_series* dftu_series_to_uppercase(const dftu_series* v) {
270 ✔
798
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_to_uppercase(flat_v));
270 ✔
799

800
    return ascii_fold(v, 'a', 'z', -32);
182 ✔
801
}
135 ✔
802

803
dftu_series* dftu_series_str_strip(const dftu_series* v) {
142 ✔
804
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_strip(flat_v));
142 ✔
805

806
    return string_transform(v, [](std::string_view s) {
212 ✔
807
        return std::string(rstrip_ws(lstrip_ws(s)));
294 !
808
    });
57 ✔
809
}
71 ✔
810
dftu_series* dftu_series_str_lstrip(const dftu_series* v) {
128 ✔
811
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_lstrip(flat_v));
128 ✔
812

813
    return string_transform(
100 ✔
814
        v, [](std::string_view s) { return std::string(lstrip_ws(s)); });
322 !
815
}
64 ✔
816
dftu_series* dftu_series_str_rstrip(const dftu_series* v) {
128 ✔
817
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_rstrip(flat_v));
128 ✔
818

819
    return string_transform(
100 ✔
820
        v, [](std::string_view s) { return std::string(rstrip_ws(s)); });
322 !
821
}
64 ✔
822

823
dftu_series* dftu_series_str_replace(const dftu_series* v, const char* pat,
134 ✔
824
                                     int32_t pat_len, const char* repl,
825
                                     int32_t repl_len) {
826
    DFTU_FLAT_OPERAND(
134 !
827
        v, flat_v,
828
        dftu_series_str_replace(flat_v, pat, pat_len, repl, repl_len));
829

830
    std::string_view p(pat, static_cast<std::size_t>(pat_len));
106 ✔
831
    std::string_view r(repl, static_cast<std::size_t>(repl_len));
106 ✔
832
    return string_transform(v, [p, r](std::string_view s) {
186 !
833
        return replace_literal(s, p, r, false);
160 ✔
834
    });
53 ✔
835
}
67 ✔
836
dftu_series* dftu_series_str_replace_all(const dftu_series* v, const char* pat,
154 ✔
837
                                         int32_t pat_len, const char* repl,
838
                                         int32_t repl_len) {
839
    DFTU_FLAT_OPERAND(
154 !
840
        v, flat_v,
841
        dftu_series_str_replace_all(flat_v, pat, pat_len, repl, repl_len));
842

843
    std::string_view p(pat, static_cast<std::size_t>(pat_len));
126 ✔
844
    std::string_view r(repl, static_cast<std::size_t>(repl_len));
126 ✔
845
    return string_transform(v, [p, r](std::string_view s) {
259 !
846
        return replace_literal(s, p, r, true);
266 ✔
847
    });
63 ✔
848
}
77 ✔
849

850
namespace {
851
// Splits every row of `v` on `s_sep`, producing a List<String> (always
852
// narrow, both levels: the per-row part count and total byte count are the
853
// source column's own data, already known to fit an int32 row count).
854
// A List<String> column over `v`'s rows (always narrow, both levels): row i
855
// holds the parts `fn(row)` yields, a null input row a null list.
856
template <class Off, class Fn>
857
dftu_series* list_transform_w(const dftu_series* v, Fn fn) {
58 ✔
858
    RowReader<Off> r(v);
58 !
859
    if (!r.ok()) return nullptr;
58 !
860

861
    std::vector<std::string> all_parts;
58 ✔
862
    std::vector<std::int32_t> list_off(static_cast<std::size_t>(v->length + 1),
87 !
863
                                       0);
58 !
864
    for (std::int64_t i = 0; i < v->length; ++i) {
4,594 ✔
865
        if (!r.is_null(i)) fn(r.at(i), all_parts);
4,536 !
866
        if (!fits_int32_offsets(all_parts.size())) return nullptr;
4,536 !
867
        list_off[static_cast<std::size_t>(i + 1)] =
4,536 ✔
868
            static_cast<std::int32_t>(all_parts.size());
4,536 ✔
869
    }
2,268 ✔
870
    std::size_t ctotal = 0;
58 ✔
871
    for (const std::string& p : all_parts) ctotal += p.size();
55,522 ✔
872
    if (!fits_int32_offsets(ctotal)) return nullptr;
58 !
873

874
    auto* child = new dftu_series();
58 !
875
    child->type = TypeId::String;
58 ✔
876
    child->encoding = Encoding::Flat;
58 ✔
877
    child->length = static_cast<std::int64_t>(all_parts.size());
58 ✔
878
    std::size_t coff_bytes =
58 ✔
879
        static_cast<std::size_t>(all_parts.size() + 1) * sizeof(std::int32_t);
58 ✔
880
    child->offsets = Buffer::allocate(coff_bytes);
58 !
881
    child->data = Buffer::allocate(ctotal);
58 !
882
    std::int32_t* cod = reinterpret_cast<std::int32_t*>(child->offsets->data());
58 ✔
883
    char* cbd =
58 ✔
884
        ctotal != 0 ? reinterpret_cast<char*>(child->data->data()) : nullptr;
58 ✔
885
    std::int32_t cpos = 0;
58 ✔
886
    cod[0] = 0;
58 ✔
887
    for (std::size_t k = 0; k < all_parts.size(); ++k) {
55,522 ✔
888
        const std::string& p = all_parts[k];
55,464 ✔
889
        if (!p.empty()) std::memcpy(cbd + cpos, p.data(), p.size());
55,464 !
890
        cpos += static_cast<std::int32_t>(p.size());
55,464 ✔
891
        cod[k + 1] = cpos;
55,464 ✔
892
    }
27,732 ✔
893

894
    auto* out = new dftu_series();
58 !
895
    out->type = TypeId::List;
58 ✔
896
    out->encoding = Encoding::Flat;
58 ✔
897
    out->length = v->length;
58 ✔
898
    out->null_count = v->null_count;
58 ✔
899
    out->validity = v->validity;  // a null input row stays a null list
58 ✔
900
    std::size_t loff_bytes =
58 ✔
901
        static_cast<std::size_t>(v->length + 1) * sizeof(std::int32_t);
58 ✔
902
    out->offsets = Buffer::allocate(loff_bytes);
58 !
903
    std::memcpy(out->offsets->data(), list_off.data(), loff_bytes);
58 ✔
904
    out->set_child(std::shared_ptr<dftu_series>(child));
58 !
905
    return out;
58 ✔
906
}
58 ✔
907

908
template <class Fn>
909
dftu_series* list_transform(const dftu_series* v, Fn fn) {
58 ✔
910
    if (!v || !is_string_kind(v->type)) return nullptr;
58 !
911
    return is_wide_offset_type(v->type) ? list_transform_w<std::int64_t>(v, fn)
58 !
912
                                        : list_transform_w<std::int32_t>(v, fn);
58 ✔
913
}
29 ✔
914

915
}  // namespace
916

917
dftu_series* dftu_series_list_len(const dftu_series* v) {
3,820 ✔
918
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_list_len(flat_v));
3,820 !
919

920
    if (!v || v->type != TypeId::List || v->encoding != Encoding::Flat)
3,792 !
921
        return nullptr;
92 ✔
922
    const std::int32_t* off = dftu_series_offsets(v);
3,700 !
923
    if (!off) return nullptr;
3,700 ✔
924
    const std::size_t n = static_cast<std::size_t>(v->length);
3,700 ✔
925
    std::vector<std::int64_t> len(n);
3,700 !
926
    for (std::size_t i = 0; i < n; ++i) len[i] = off[i + 1] - off[i];
107,196 ✔
927
    auto* out = new dftu_series();
3,700 !
928
    out->type = TypeId::Int64;
3,700 ✔
929
    out->encoding = Encoding::Flat;
3,700 ✔
930
    out->length = v->length;
3,700 ✔
931
    out->null_count = v->null_count;
3,700 ✔
932
    out->validity = v->validity;
3,700 ✔
933
    out->data = Buffer::allocate(n * sizeof(std::int64_t));
3,700 !
934
    if (n != 0)
3,700 ✔
935
        std::memcpy(out->data->data(), len.data(), n * sizeof(std::int64_t));
3,700 ✔
936
    return out;
3,700 ✔
937
}
3,760 ✔
938

939
dftu_series* dftu_series_list_get(const dftu_series* v, int64_t index) {
208 ✔
940
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_list_get(flat_v, index));
208 !
941

942
    if (!v || v->type != TypeId::List || v->encoding != Encoding::Flat)
180 !
943
        return nullptr;
92 ✔
944
    const std::int32_t* off = dftu_series_offsets(v);
88 !
945
    if (!off || dftu_series_num_children(v) != 1) return nullptr;
88 !
946
    const std::size_t n = static_cast<std::size_t>(v->length);
88 ✔
947
    // A gather of the element at `index` (from the end when negative) per
948
    // row; -1 marks a null row or one whose list is too short.
949
    std::vector<std::int64_t> idx(n, -1);
88 !
950
    for (std::size_t i = 0; i < n; ++i) {
606 ✔
951
        if (v->validity && !((v->validity->data()[i >> 3] >> (i & 7)) & 1))
518 ✔
952
            continue;
72 ✔
953
        const std::int64_t len = off[i + 1] - off[i];
446 ✔
954
        const std::int64_t k = index < 0 ? len + index : index;
446 ✔
955
        if (k >= 0 && k < len) idx[i] = off[i] + k;
446 ✔
956
    }
223 ✔
957
    dftu_series* child = dftu_series_child(v, 0);
88 !
958
    if (!child) return nullptr;
88 ✔
959
    dftu_series* out =
44 ✔
960
        dftu_series_take(child, idx.data(), static_cast<int64_t>(n));
88 !
961
    dftu_series_free(child);
88 !
962
    return out;
88 ✔
963
}
148 ✔
964

965
// The pandas `.str` batch. Every op below works on the column's buffers
966
// directly (no per-row std::string): the SIMD primitives of strsimd scan the
967
// whole data buffer, the builders size the output in one pass and fill it in a
968
// second.
969
namespace {
970

971
namespace simd = dftracer::utils::dataframe::strsimd;
972

973
// A FLAT String/Binary column read at offset width `Off`. Offsets are
974
// absolute positions in `data`; a column cut from a larger one starts past 0.
975
template <class Off>
976
struct FlatStr {
977
    const Off* off = nullptr;
3,440 ✔
978
    const std::uint8_t* data = nullptr;
3,440 ✔
979
    const std::uint8_t* validity = nullptr;
3,440 ✔
980
    std::int64_t n = 0;
3,440 ✔
981
    bool ok = false;
3,440 ✔
982

983
    explicit FlatStr(const dftu_series* v) {
10,320 ✔
984
        if (!v || v->encoding != Encoding::Flat || !is_string_kind(v->type) ||
10,320 !
985
            is_wide_offset_type(v->type) != std::is_same_v<Off, std::int64_t>)
6,880 !
986
            return;
×
987
        const auto& ob = offsets_of<Off>(*v);
6,880 ✔
988
        if (!ob) return;
6,880 !
989
        off = reinterpret_cast<const Off*>(ob->data());
6,880 ✔
990
        data = v->data ? v->data->data() : nullptr;
6,880 !
991
        validity = v->validity ? v->validity->data() : nullptr;
6,880 ✔
992
        n = v->length;
6,880 ✔
993
        ok = true;
6,880 ✔
994
    }
6,880 ✔
995
    bool is_null(std::int64_t i) const {
2,260,012 ✔
996
        return validity != nullptr && ((validity[i >> 3] >> (i & 7)) & 1) == 0;
2,260,012 ✔
997
    }
998
    std::int64_t lo() const {
1,262 ✔
999
        return n != 0 ? static_cast<std::int64_t>(off[0]) : 0;
1,262 ✔
1000
    }
1001
    std::int64_t hi() const {
1,262 ✔
1002
        return n != 0 ? static_cast<std::int64_t>(off[n]) : 0;
1,262 ✔
1003
    }
1004
    std::int64_t len(std::int64_t i) const {
2,088,745 ✔
1005
        return static_cast<std::int64_t>(off[i + 1]) - off[i];
2,088,745 ✔
1006
    }
1007
    const std::uint8_t* row(std::int64_t i) const { return data + off[i]; }
814,096 ✔
1008
};
1009

1010
template <class Fn>
1011
dftu_series* with_flat(const dftu_series* v, Fn&& fn) {
2,782 ✔
1012
    if (!v || !is_string_kind(v->type) || v->encoding != Encoding::Flat)
2,782 !
1013
        return nullptr;
56 ✔
1014
    if (is_wide_offset_type(v->type)) {
2,726 !
1015
        FlatStr<std::int64_t> f(v);
×
1016
        return f.ok ? fn(f) : nullptr;
×
1017
    }
1018
    FlatStr<std::int32_t> f(v);
2,726 !
1019
    return f.ok ? fn(f) : nullptr;
2,726 !
1020
}
1,391 ✔
1021

1022
void share_nulls(dftu_series* out, const dftu_series* v) {
1,720 ✔
1023
    if (!out) return;
1,720 ✔
1024
    out->validity = v->validity;
1,718 ✔
1025
    out->null_count = v->null_count;
1,718 ✔
1026
}
860 ✔
1027

1028
void copy_bytes(std::uint8_t* dst, const std::uint8_t* src, std::int64_t n) {
1,759,722 ✔
1029
    if (n > 0) std::memcpy(dst, src, static_cast<std::size_t>(n));
1,759,722 ✔
1030
}
1,759,722 ✔
1031

1032
constexpr std::int64_t BUILD_GRAIN = 1 << 14;
1033

1034
// A narrow String column of `n` rows: row i is `len_of(i)` bytes that
1035
// `fill_of(i, dst)` writes (a null row is empty and never asked). Sizes the
1036
// output in one pass and fills it in a second, across the pool for a large
1037
// column. nullptr when the bytes pass what an int32 offset reaches.
1038
template <class IsNull, class LenFn, class FillFn>
1039
dftu_series* build_flat_string(std::int64_t n, IsNull is_null, LenFn len_of,
3,554 ✔
1040
                               FillFn fill_of) {
1041
    auto offb = Buffer::allocate(static_cast<std::size_t>(n + 1) *
3,554 !
1042
                                 sizeof(std::int32_t));
1043
    auto* od = reinterpret_cast<std::int32_t*>(offb->data());
3,554 ✔
1044
    std::int64_t total = 0;
3,554 ✔
1045
    od[0] = 0;
3,554 ✔
1046
    for (std::int64_t i = 0; i < n; ++i) {
700,870 !
1047
        if (!is_null(i)) {
697,318 !
1048
            const std::int64_t l = len_of(i);
644,600 !
1049
            if (l < 0 || __builtin_add_overflow(total, l, &total) ||
966,900 !
1050
                total > std::numeric_limits<std::int32_t>::max())
644,600 ✔
1051
                return nullptr;
2 ✔
1052
        }
322,299 ✔
1053
        od[i + 1] = static_cast<std::int32_t>(total);
697,316 ✔
1054
    }
348,658 ✔
1055
    auto datab = Buffer::allocate(static_cast<std::size_t>(total));
3,552 !
1056
    std::uint8_t* d = datab->data();
3,552 ✔
1057
    auto body = [&](std::int64_t b, std::int64_t e) {
627,343 ✔
1058
        for (std::int64_t i = b; i < e; ++i)
637,939 !
1059
            if (!is_null(i)) fill_of(i, d + od[i]);
636,873 !
1060
    };
1,780 ✔
1061
    if (n > BUILD_GRAIN && parallel_backend_installed())
3,552 !
1062
        parallel_for(n, BUILD_GRAIN, body);
4 !
1063
    else
1064
        body(0, n);
3,548 !
1065
    auto* out = new dftu_series();
3,552 !
1066
    out->type = TypeId::String;
3,552 ✔
1067
    out->encoding = Encoding::Flat;
3,552 ✔
1068
    out->length = n;
3,552 ✔
1069
    out->offsets = std::move(offb);
3,552 ✔
1070
    out->data = std::move(datab);
3,552 ✔
1071
    return out;
3,552 ✔
1072
}
3,554 ✔
1073

1074
// One string op over a single column: the output shares its nulls.
1075
template <class LenFn, class FillFn>
1076
dftu_series* map_strings(const dftu_series* v, LenFn len_of, FillFn fill_of) {
1,464 ✔
1077
    dftu_series* out = with_flat(v, [&](const auto& f) {
2,928 !
1078
        return build_flat_string(
1,464 ✔
1079
            f.n, [&](std::int64_t i) { return f.is_null(i); },
949,516 ✔
1080
            [&](std::int64_t i) { return len_of(f, i); },
467,574 ✔
1081
            [&](std::int64_t i, std::uint8_t* dst) { fill_of(f, i, dst); });
407,353 ✔
1082
    });
1083
    share_nulls(out, v);
1,464 ✔
1084
    return out;
1,464 ✔
1085
}
1086

1087
// The bit arrays of one kind over p[0, n), across the pool for a large buffer.
1088
struct Bits {
1089
    std::vector<std::uint64_t> bad;
1090
    std::vector<std::uint64_t> aux;
1091
};
1092

1093
Bits compute_bits(simd::BitKind kind, const std::uint8_t* p, std::size_t n,
980 ✔
1094
                  std::uint8_t eq, bool want_aux) {
1095
    const std::size_t words = (n + 63) / 64;
980 ✔
1096
    Bits b;
980 ✔
1097
    b.bad.assign(words + 1, 0);
980 !
1098
    if (want_aux) b.aux.assign(words + 1, 0);
980 !
1099
    std::uint64_t* bp = b.bad.data();
980 ✔
1100
    std::uint64_t* ap = want_aux ? b.aux.data() : nullptr;
980 ✔
1101
    constexpr std::int64_t CHUNK = 1 << 14;  // words: 1 MiB of bytes
980 ✔
1102
    if (static_cast<std::int64_t>(words) > CHUNK &&
980 !
1103
        parallel_backend_installed()) {
×
1104
        parallel_for(static_cast<std::int64_t>(words), CHUNK,
×
1105
                     [&](std::int64_t b0, std::int64_t e0) {
×
1106
                         simd::class_bits(
×
1107
                             kind, p, n, static_cast<std::size_t>(b0),
×
1108
                             static_cast<std::size_t>(e0), eq, bp, ap);
×
1109
                     });
×
1110
    } else if (words != 0) {
980 ✔
1111
        simd::class_bits(kind, p, n, 0, words, eq, bp, ap);
630 !
1112
    }
315 ✔
1113
    return b;
1,470 ✔
1114
}
490 !
1115

1116
bool lower_byte(std::uint8_t c) { return c >= 'a' && c <= 'z'; }
286,194 ✔
1117

1118
// Narrow String out of a List<String> shape: row i of the list holds
1119
// `list_off[i + 1] - list_off[i]` strings.
1120
dftu_series* make_str_list(const dftu_series* v,
522 ✔
1121
                           const std::vector<std::int32_t>& list_off,
1122
                           std::int64_t parts, std::shared_ptr<Buffer> coff,
1123
                           std::shared_ptr<Buffer> cdata) {
1124
    auto* child = new dftu_series();
522 ✔
1125
    child->type = TypeId::String;
522 ✔
1126
    child->encoding = Encoding::Flat;
522 ✔
1127
    child->length = parts;
522 ✔
1128
    child->offsets = std::move(coff);
522 ✔
1129
    child->data = std::move(cdata);
522 ✔
1130
    auto* out = new dftu_series();
522 ✔
1131
    out->type = TypeId::List;
522 ✔
1132
    out->encoding = Encoding::Flat;
522 ✔
1133
    out->length = v->length;
522 ✔
1134
    out->null_count = v->null_count;
522 ✔
1135
    out->validity = v->validity;  // a null input row stays a null list
522 ✔
1136
    const std::size_t loff_bytes = list_off.size() * sizeof(std::int32_t);
522 ✔
1137
    out->offsets = Buffer::allocate(loff_bytes);
522 ✔
1138
    std::memcpy(out->offsets->data(), list_off.data(), loff_bytes);
522 ✔
1139
    out->set_child(std::shared_ptr<dftu_series>(child));
522 !
1140
    return out;
522 ✔
1141
}
1142

1143
// The first (last, when `from_right`) place in row [s, e) of p where `sep`
1144
// occurs, or NPOS: candidate bits of sep's first byte, each verified.
1145
std::size_t find_sep(const std::uint64_t* cand, const std::uint8_t* p,
863,680 ✔
1146
                     std::size_t s, std::size_t e, std::string_view sep,
1147
                     bool from_right) {
1148
    const std::size_t sl = sep.size();
863,680 ✔
1149
    if (e - s < sl) return simd::NPOS;
863,680 ✔
1150
    const std::size_t limit = e - sl + 1;  // one past the last start
862,866 ✔
1151
    auto verify = [&](std::size_t q) {
1,193,831 ✔
1152
        return sl == 1 || std::memcmp(p + q + 1, sep.data() + 1, sl - 1) == 0;
762,398 ✔
1153
    };
431,433 ✔
1154
    if (!from_right) {
862,866 ✔
1155
        std::size_t pos = s;
823,242 ✔
1156
        while (pos < limit) {
907,902 ✔
1157
            const std::size_t q = simd::bits_next(cand, pos, limit);
907,250 ✔
1158
            if (q >= limit) return simd::NPOS;
907,250 ✔
1159
            if (verify(q)) return q;
645,518 ✔
1160
            pos = q + 1;
84,660 ✔
1161
        }
1162
        return simd::NPOS;
652 ✔
1163
    }
1164
    std::size_t lim = limit;
39,624 ✔
1165
    while (lim > s) {
142,394 ✔
1166
        const std::size_t q = simd::bits_prev(cand, s, lim);
141,674 ✔
1167
        if (q == simd::NPOS) return simd::NPOS;
141,674 ✔
1168
        if (verify(q)) return q;
116,880 ✔
1169
        lim = q;
102,770 ✔
1170
    }
1171
    return simd::NPOS;
720 ✔
1172
}
431,840 ✔
1173

1174
dftu_series* case_impl(const dftu_series* v, simd::CaseKind kind,
230 ✔
1175
                       bool capitalize) {
1176
    if (!v || !is_string_kind(v->type)) return nullptr;
230 !
1177
    const bool wide = is_wide_offset_type(v->type);
230 ✔
1178
    auto run = [&](const auto& f) -> dftu_series* {
345 ✔
1179
        auto* out = new dftu_series();
230 ✔
1180
        out->type = wide ? TypeId::LargeString : TypeId::String;
230 !
1181
        out->encoding = Encoding::Flat;
230 ✔
1182
        out->length = v->length;
667 ✔
1183
        out->null_count = v->null_count;
230 ✔
1184
        out->validity = v->validity;
230 ✔
1185
        using Off = std::remove_const_t<std::remove_pointer_t<decltype(f.off)>>;
1186
        offsets_of<Off>(*out) = offsets_of<Off>(*v);  // byte lengths unchanged
230 ✔
1187
        const std::size_t data_len = v->data ? v->data->size() : 0;
230 !
1188
        out->data = Buffer::allocate(data_len);
230 ✔
1189
        if (data_len == 0) return out;
230 ✔
1190
        const std::uint8_t* in = v->data->data();
184 ✔
1191
        std::uint8_t* o = out->data->data();
184 ✔
1192
        simd::case_map(capitalize ? simd::CaseKind::Lower : kind, in, o,
184 ✔
1193
                       data_len);
92 ✔
1194
        if (capitalize || kind == simd::CaseKind::Title) {
184 ✔
1195
            // A row's first byte has no previous byte: it is upper-cased when
1196
            // lower, whatever sat before it in the buffer.
1197
            for (std::int64_t i = 0; i < f.n; ++i) {
298,234 ✔
1198
                if (f.len(i) <= 0) continue;
298,088 ✔
1199
                const std::int64_t s = f.off[i];
281,342 ✔
1200
                o[s] = lower_byte(in[s]) ? static_cast<std::uint8_t>(in[s] - 32)
363,155 ✔
1201
                                         : in[s];
163,626 ✔
1202
            }
140,671 ✔
1203
        }
73 ✔
1204
        return out;
184 ✔
1205
    };
230 ✔
1206
    if (wide) {
230 !
1207
        FlatStr<std::int64_t> f(v);
×
1208
        return f.ok ? run(f) : nullptr;
×
1209
    }
1210
    FlatStr<std::int32_t> f(v);
230 !
1211
    return f.ok ? run(f) : nullptr;
230 !
1212
}
115 ✔
1213

1214
dftu_series* is_impl(const dftu_series* v, int cls) {
584 ✔
1215
    simd::BitKind kind = simd::BitKind::Alnum;
584 ✔
1216
    bool want_aux = false;
584 ✔
1217
    switch (cls) {
584 ✔
1218
        case DFTU_STR_ALNUM:
26 ✔
1219
            kind = simd::BitKind::Alnum;
52 ✔
1220
            break;
52 ✔
1221
        case DFTU_STR_ALPHA:
79 ✔
1222
            kind = simd::BitKind::Alpha;
158 ✔
1223
            break;
158 ✔
1224
        case DFTU_STR_DIGIT:
78 ✔
1225
        case DFTU_STR_DECIMAL:
1226
        case DFTU_STR_NUMERIC:
1227
            kind = simd::BitKind::Digit;
156 ✔
1228
            break;
156 ✔
1229
        case DFTU_STR_SPACE:
26 ✔
1230
            kind = simd::BitKind::Space;
52 ✔
1231
            break;
52 ✔
1232
        case DFTU_STR_LOWER:
27 ✔
1233
            kind = simd::BitKind::Lower;
54 ✔
1234
            want_aux = true;
54 ✔
1235
            break;
54 ✔
1236
        case DFTU_STR_UPPER:
28 ✔
1237
            kind = simd::BitKind::Upper;
56 ✔
1238
            want_aux = true;
56 ✔
1239
            break;
56 ✔
1240
        case DFTU_STR_TITLE:
27 ✔
1241
            kind = simd::BitKind::Title;
54 ✔
1242
            want_aux = true;
54 ✔
1243
            break;
54 ✔
1244
        default:
1 ✔
1245
            return nullptr;
2 ✔
1246
    }
1247
    const bool title = kind == simd::BitKind::Title;
582 ✔
1248
    return with_flat(v, [&](const auto& f) -> dftu_series* {
1,399 !
1249
        const std::int64_t lo = f.lo();
526 ✔
1250
        const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
526 ✔
1251
        const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
526 ✔
1252
        // Short strings: one vector pass over the whole buffer, then a bit
1253
        // range per row. Long strings: scan each row and stop at its first
1254
        // bad vector (no bit arrays at all).
1255
        const std::int64_t avg =
526 ✔
1256
            f.n > 0 ? static_cast<std::int64_t>(nbytes) / f.n : 0;
526 ✔
1257
        const simd::PredStrategy strat = simd::pred_strategy();
526 !
1258
        const bool by_rows = strat == simd::PredStrategy::Rows ||
998 ✔
1259
                             (strat == simd::PredStrategy::Auto &&
472 ✔
1260
                              avg >= simd::PRED_ROWS_MIN_AVG);
227 ✔
1261
        Bits bits;
526 ✔
1262
        if (!by_rows) bits = compute_bits(kind, p, nbytes, 0, want_aux);
526 !
1263
        const std::uint64_t* bad = bits.bad.data();
526 ✔
1264
        const std::uint64_t* aux =
526 ✔
1265
            want_aux && !by_rows ? bits.aux.data() : nullptr;
526 ✔
1266

1267
        auto* out = new dftu_series();
526 !
1268
        out->type = TypeId::Bool;
526 ✔
1269
        out->encoding = Encoding::Flat;
526 ✔
1270
        out->length = f.n;
526 ✔
1271
        out->null_count = v->null_count;
526 ✔
1272
        out->validity = v->validity;
526 ✔
1273
        const std::size_t bytes = buffer_bytes(TypeId::Bool, f.n);
526 ✔
1274
        out->data = Buffer::allocate(bytes);
526 !
1275
        std::memset(out->data->data(), 0, bytes);
526 ✔
1276
        std::uint8_t* res = out->data->data();
526 ✔
1277
        auto rows = [&](std::int64_t b, std::int64_t e) {
88,483 ✔
1278
            if (by_rows) {
526 ✔
1279
                simd::class_rows(kind, f.data, f.off, lo, b, e, res);
234 ✔
1280
                return;
234 ✔
1281
            }
1282
            for (std::int64_t i = b; i < e; ++i) {
45,824 ✔
1283
                const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
45,532 ✔
1284
                const std::size_t t =
45,532 ✔
1285
                    static_cast<std::size_t>(f.off[i + 1] - lo);
45,532 ✔
1286
                if (s >= t) continue;  // an empty string is in no class
45,532 ✔
1287
                bool yes;
1288
                if (title) {
44,071 ✔
1289
                    // The first byte has no previous byte, so it breaks the
1290
                    // rule when lower; the rest read the bit array.
1291
                    yes = !lower_byte(p[s]) && !simd::bits_any(bad, s + 1, t) &&
4,950 !
1292
                          simd::bits_any(aux, s, t);
98 ✔
1293
                } else {
2,426 ✔
1294
                    yes = !simd::bits_any(bad, s, t) &&
53,640 ✔
1295
                          (aux == nullptr || simd::bits_any(aux, s, t));
14,684 !
1296
                }
1297
                if (yes)
43,808 ✔
1298
                    res[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
14,672 ✔
1299
            }
21,904 ✔
1300
        };
263 ✔
1301
        constexpr std::int64_t ROW_GRAIN = 1 << 15;  // a multiple of 8
526 ✔
1302
        if (f.n > ROW_GRAIN && parallel_backend_installed())
526 !
1303
            parallel_for(f.n, ROW_GRAIN, rows);
×
1304
        else
1305
            rows(0, f.n);
526 !
1306
        return out;
526 ✔
1307
    });
817 ✔
1308
}
292 ✔
1309

1310
// Pad / center: `mode` 0 pads the start, 1 the end, 2 centers.
1311
dftu_series* pad_impl(const dftu_series* v, std::int64_t width, char fill,
592 ✔
1312
                      int mode) {
1313
    return map_strings(
592 ✔
1314
        v,
296 ✔
1315
        [width](const auto& f, std::int64_t i) {
357,366 ✔
1316
            return std::max<std::int64_t>(f.len(i), width);
357,070 ✔
1317
        },
1318
        [width, fill, mode](const auto& f, std::int64_t i, std::uint8_t* dst) {
1,039,718 ✔
1319
            const std::int64_t len = f.len(i);
294,285 ✔
1320
            if (len >= width) {
294,383 ✔
1321
                copy_bytes(dst, f.row(i), len);
65,547 ✔
1322
                return;
66,422 ✔
1323
            }
1324
            const std::int64_t gap = width - len;
228,836 ✔
1325
            // CPython's center puts an odd gap's extra fill on the left when
1326
            // the width is odd, else on the right.
1327
            const std::int64_t left = mode == 0   ? gap
454,132 ✔
1328
                                      : mode == 1 ? 0
225,296 ✔
1329
                                                  : gap / 2 + (gap & width & 1);
221,840 ✔
1330
            std::memset(dst, fill, static_cast<std::size_t>(left));
228,836 ✔
1331
            copy_bytes(dst + left, f.row(i), len);
228,836 ✔
1332
            std::memset(dst + left + len, fill,
337,695 ✔
1333
                        static_cast<std::size_t>(gap - left));
228,561 ✔
1334
        });
142,641 ✔
1335
}
1336

1337
dftu_series* zfill_impl(const dftu_series* v, std::int64_t width) {
180 ✔
1338
    return map_strings(
180 ✔
1339
        v,
90 ✔
1340
        [width](const auto& f, std::int64_t i) {
21,920 ✔
1341
            return std::max<std::int64_t>(f.len(i), width);
21,830 ✔
1342
        },
1343
        [width](const auto& f, std::int64_t i, std::uint8_t* dst) {
34,472 ✔
1344
            const std::int64_t len = f.len(i);
21,830 ✔
1345
            const std::uint8_t* r = f.row(i);
21,830 ✔
1346
            if (len >= width) {
21,830 ✔
1347
                copy_bytes(dst, r, len);
18,556 ✔
1348
                return;
18,556 ✔
1349
            }
1350
            const std::int64_t gap = width - len;
3,274 ✔
1351
            // A leading sign stays first; the zeros go after it.
1352
            const bool sign = len > 0 && (r[0] == '+' || r[0] == '-');
4,845 ✔
1353
            std::int64_t at = 0;
3,274 ✔
1354
            if (sign) dst[at++] = r[0];
3,274 ✔
1355
            std::memset(dst + at, '0', static_cast<std::size_t>(gap));
3,274 ✔
1356
            at += gap;
3,274 ✔
1357
            copy_bytes(dst + at, r + (sign ? 1 : 0), len - (sign ? 1 : 0));
3,274 ✔
1358
        });
11,005 ✔
1359
}
1360

1361
dftu_series* remove_affix_impl(const dftu_series* v, std::string_view a,
306 ✔
1362
                               bool prefix) {
1363
    const auto plen = static_cast<std::int64_t>(a.size());
306 ✔
1364
    auto cut = [a, plen, prefix](const auto& f,
73,157 ✔
1365
                                 std::int64_t i) -> std::int64_t {
138,264 ✔
1366
        const std::int64_t len = f.len(i);
73,004 ✔
1367
        if (plen == 0 || len < plen) return 0;
73,004 ✔
1368
        const std::uint8_t* at = f.row(i) + (prefix ? 0 : len - plen);
57,960 ✔
1369
        return std::memcmp(at, a.data(), static_cast<std::size_t>(plen)) == 0
57,960 !
1370
                   ? plen
29,382 ✔
1371
                   : 0;
28,980 ✔
1372
    };
36,655 ✔
1373
    return map_strings(
306 !
1374
        v,
153 ✔
1375
        [&cut](const auto& f, std::int64_t i) { return f.len(i) - cut(f, i); },
36,655 ✔
1376
        [&cut, prefix](const auto& f, std::int64_t i, std::uint8_t* dst) {
54,906 ✔
1377
            const std::int64_t c = cut(f, i);
36,502 ✔
1378
            copy_bytes(dst, f.row(i) + (prefix ? c : 0), f.len(i) - c);
36,502 ✔
1379
        });
36,808 ✔
1380
}
1381

1382
dftu_series* repeat_impl(const dftu_series* v, std::int64_t n) {
132 ✔
1383
    return map_strings(
132 ✔
1384
        v,
66 ✔
1385
        [n](const auto& f, std::int64_t i) {
22,080 ✔
1386
            std::int64_t total;
1387
            if (__builtin_mul_overflow(f.len(i), n, &total))
14,676 !
1388
                return std::numeric_limits<std::int64_t>::max();
×
1389
            return total;
14,676 ✔
1390
        },
7,338 ✔
1391
        [n](const auto& f, std::int64_t i, std::uint8_t* dst) {
22,077 ✔
1392
            const std::int64_t len = f.len(i);
14,674 ✔
1393
            const std::int64_t total = len * n;
14,674 ✔
1394
            if (total == 0) return;
14,674 ✔
1395
            copy_bytes(dst, f.row(i), len);
10,978 ✔
1396
            // Double the filled prefix until the row is full.
1397
            std::int64_t filled = len;
10,978 ✔
1398
            while (filled < total) {
25,522 ✔
1399
                const std::int64_t c = std::min(filled, total - filled);
14,544 ✔
1400
                std::memcpy(dst + filled, dst, static_cast<std::size_t>(c));
14,544 ✔
1401
                filled += c;
14,544 ✔
1402
            }
1403
        });
7,403 ✔
1404
}
1405

1406
dftu_series* slice_impl(const dftu_series* v, std::int64_t start,
254 ✔
1407
                        std::int64_t length) {
1408
    // The byte range of a row: a negative start counts from the end, a
1409
    // negative length runs to the end (polars slice with no length).
1410
    auto range = [start, length](std::int64_t len) {
147,183 ✔
1411
        std::int64_t b = start < 0 ? start + len : start;
73,528 ✔
1412
        b = std::clamp<std::int64_t>(b, 0, len);
73,528 ✔
1413
        std::int64_t e = length < 0 ? len : b + length;
73,528 ✔
1414
        e = std::clamp<std::int64_t>(e, b, len);
73,528 ✔
1415
        return std::pair<std::int64_t, std::int64_t>(b, e);
73,528 ✔
1416
    };
127 ✔
1417
    return map_strings(
254 !
1418
        v,
127 ✔
1419
        [&range](const auto& f, std::int64_t i) {
36,891 ✔
1420
            const auto [b, e] = range(f.len(i));
36,764 !
1421
            return e - b;
36,764 ✔
1422
        },
1423
        [&range](const auto& f, std::int64_t i, std::uint8_t* dst) {
36,891 ✔
1424
            const auto [b, e] = range(f.len(i));
36,764 !
1425
            copy_bytes(dst, f.row(i) + b, e - b);
36,764 ✔
1426
        });
37,018 ✔
1427
}
1428

1429
template <class OffA, class OffB>
1430
dftu_series* cat_impl(const dftu_series* a, const dftu_series* b) {
1,834 ✔
1431
    FlatStr<OffA> fa(a);
1,834 !
1432
    FlatStr<OffB> fb(b);
1,834 !
1433
    if (!fa.ok || !fb.ok) return nullptr;
1,834 !
1434
    dftu_series* out = build_flat_string(
1,834 !
1435
        fa.n, [&](std::int64_t i) { return fa.is_null(i) || fb.is_null(i); },
286,025 !
1436
        [&](std::int64_t i) { return fa.len(i) + fb.len(i); },
139,027 ✔
1437
        [&](std::int64_t i, std::uint8_t* dst) {
484,302 ✔
1438
            copy_bytes(dst, fa.row(i), fa.len(i));
138,110 ✔
1439
            copy_bytes(dst + fa.len(i), fb.row(i), fb.len(i));
138,110 ✔
1440
        });
69,055 ✔
1441
    if (!out) return nullptr;
1,834 !
1442
    if (fa.validity == nullptr && fb.validity == nullptr) return out;
1,834 !
1443
    // A null on either side is null: the validity is the two ANDed.
1444
    const std::size_t vbytes = buffer_bytes(TypeId::Bool, fa.n);
394 ✔
1445
    auto valid = Buffer::allocate(vbytes);
394 !
1446
    std::int64_t valid_rows = 0;
394 ✔
1447
    for (std::size_t k = 0; k < vbytes; ++k) {
7,524 !
1448
        std::uint8_t w =
7,130 ✔
1449
            static_cast<std::uint8_t>((fa.validity ? fa.validity[k] : 0xFF) &
11,349 !
1450
                                      (fb.validity ? fb.validity[k] : 0xFF));
7,130 !
1451
        const std::int64_t rows_here =
7,130 ✔
1452
            std::min<std::int64_t>(8, fa.n - static_cast<std::int64_t>(k) * 8);
7,130 !
1453
        if (rows_here < 8)
7,130 !
1454
            w &= static_cast<std::uint8_t>((1u << rows_here) - 1);
284 ✔
1455
        valid->data()[k] = w;
7,130 ✔
1456
        valid_rows += std::popcount(static_cast<unsigned>(w));
7,130 ✔
1457
    }
3,565 ✔
1458
    out->null_count = fa.n - valid_rows;
394 ✔
1459
    out->validity = out->null_count != 0 ? std::move(valid) : nullptr;
394 !
1460
    return out;
394 ✔
1461
}
1,114 ✔
1462

1463
template <class ChildOff>
1464
dftu_series* join_impl(const dftu_series* v, const dftu_series& child,
256 ✔
1465
                       std::string_view sep) {
1466
    FlatStr<ChildOff> c(&child);
256 !
1467
    if (!c.ok) return nullptr;
256 !
1468
    const std::int32_t* off = dftu_series_offsets(v);
256 !
1469
    const auto sl = static_cast<std::int64_t>(sep.size());
256 ✔
1470
    auto is_null = [&](std::int64_t i) {
145,662 ✔
1471
        return v->validity && !((v->validity->data()[i >> 3] >> (i & 7)) & 1);
97,024 !
1472
    };
1473
    dftu_series* out = build_flat_string(
384 ✔
1474
        v->length, is_null,
256 !
1475
        [&](std::int64_t i) {
59,600 ✔
1476
            const std::int64_t cnt = off[i + 1] - off[i];
39,648 ✔
1477
            const std::int64_t bytes =
39,648 ✔
1478
                static_cast<std::int64_t>(c.off[off[i + 1]]) - c.off[off[i]];
39,648 ✔
1479
            return bytes + (cnt > 0 ? (cnt - 1) * sl : 0);
39,648 !
1480
        },
1481
        [&](std::int64_t i, std::uint8_t* dst) {
356,591 ✔
1482
            const std::int64_t cnt = off[i + 1] - off[i];
39,648 ✔
1483
            if (cnt == 0) return;
39,648 !
1484
            if (sl == 0 || cnt == 1) {
39,648 ✔
1485
                // The elements are back to back: one copy.
1486
                copy_bytes(dst, c.data + c.off[off[i]],
48,033 ✔
1487
                           static_cast<std::int64_t>(c.off[off[i + 1]]) -
48,033 ✔
1488
                               c.off[off[i]]);
32,022 ✔
1489
                return;
32,022 ✔
1490
            }
1491
            for (std::int32_t k = off[i]; k < off[i + 1]; ++k) {
87,906 ✔
1492
                if (k != off[i]) {
80,280 ✔
1493
                    std::memcpy(dst, sep.data(), static_cast<std::size_t>(sl));
72,654 ✔
1494
                    dst += sl;
72,654 ✔
1495
                }
36,327 ✔
1496
                copy_bytes(dst, c.row(k), c.len(k));
80,280 ✔
1497
                dst += c.len(k);
80,280 ✔
1498
            }
40,140 ✔
1499
        });
19,824 ✔
1500
    share_nulls(out, v);
256 ✔
1501
    return out;
256 ✔
1502
}
128 ✔
1503

1504
template <class F>
1505
dftu_series* split_impl(const dftu_series* v, const F& f,
252 ✔
1506
                        std::string_view sep) {
1507
    const std::int64_t n = f.n;
252 ✔
1508
    const std::int64_t lo = f.lo();
252 ✔
1509
    const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
252 ✔
1510
    const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
252 ✔
1511
    const std::size_t sl = sep.size();
252 ✔
1512
    Bits cand;
252 ✔
1513
    if (sl != 0)
252 ✔
1514
        cand = compute_bits(simd::BitKind::Eq, p, nbytes,
342 !
1515
                            static_cast<std::uint8_t>(sep[0]), false);
228 !
1516

1517
    // Pass 1: where the separator occurs in each row, the part counts and
1518
    // the bytes the parts hold.
1519
    std::vector<std::size_t> hits;
252 ✔
1520
    std::vector<std::int32_t> list_off(static_cast<std::size_t>(n + 1), 0);
252 !
1521
    std::int64_t parts = 0, bytes = 0;
252 ✔
1522
    for (std::int64_t i = 0; i < n; ++i) {
316,180 ✔
1523
        if (!f.is_null(i)) {
315,928 ✔
1524
            const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
309,786 ✔
1525
            const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
309,786 ✔
1526
            const std::size_t before = hits.size();
309,786 ✔
1527
            std::size_t pos = s;
309,786 ✔
1528
            while (sl != 0 && pos < e) {
863,012 ✔
1529
                const std::size_t q =
805,418 ✔
1530
                    find_sep(cand.bad.data(), p, pos, e, sep, false);
805,418 !
1531
                if (q == simd::NPOS) break;
805,418 ✔
1532
                hits.push_back(q);
553,226 !
1533
                pos = q + sl;
553,226 ✔
1534
            }
1535
            const std::int64_t h =
309,786 ✔
1536
                static_cast<std::int64_t>(hits.size() - before);
309,786 ✔
1537
            parts += h + 1;
309,786 ✔
1538
            bytes += static_cast<std::int64_t>(e - s) -
464,679 ✔
1539
                     h * static_cast<std::int64_t>(sl);
309,786 ✔
1540
            if (parts > std::numeric_limits<std::int32_t>::max())
309,786 !
1541
                return nullptr;
×
1542
        }
154,893 ✔
1543
        list_off[static_cast<std::size_t>(i + 1)] =
315,928 ✔
1544
            static_cast<std::int32_t>(parts);
157,964 ✔
1545
    }
157,964 ✔
1546
    if (bytes > std::numeric_limits<std::int32_t>::max()) return nullptr;
252 !
1547

1548
    // Pass 2: copy the parts.
1549
    auto coff = Buffer::allocate(static_cast<std::size_t>(parts + 1) *
252 !
1550
                                 sizeof(std::int32_t));
1551
    auto cdata = Buffer::allocate(static_cast<std::size_t>(bytes));
252 !
1552
    auto* co = reinterpret_cast<std::int32_t*>(coff->data());
252 ✔
1553
    std::uint8_t* cd = cdata->data();
252 ✔
1554
    std::int64_t at = 0, k = 0;
252 ✔
1555
    co[0] = 0;
252 ✔
1556
    std::size_t h = 0;
252 ✔
1557
    for (std::int64_t i = 0; i < n; ++i) {
316,180 ✔
1558
        if (f.is_null(i)) continue;
315,928 ✔
1559
        const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
309,786 ✔
1560
        std::size_t start = static_cast<std::size_t>(f.off[i] - lo);
309,786 ✔
1561
        auto emit = [&](std::size_t from, std::size_t to) {
1,604,304 ✔
1562
            copy_bytes(cd + at, p + from, static_cast<std::int64_t>(to - from));
863,012 ✔
1563
            at += static_cast<std::int64_t>(to - from);
863,012 ✔
1564
            co[++k] = static_cast<std::int32_t>(at);
863,012 ✔
1565
        };
431,506 ✔
1566
        while (h < hits.size() && hits[h] < e) {
863,012 ✔
1567
            emit(start, hits[h]);
553,226 !
1568
            start = hits[h] + sl;
553,226 ✔
1569
            ++h;
553,226 ✔
1570
        }
1571
        emit(start, e);
309,786 !
1572
    }
154,893 ✔
1573
    return make_str_list(v, list_off, parts, std::move(coff), std::move(cdata));
252 !
1574
}
252 ✔
1575

1576
template <class F>
1577
dftu_series* partition_impl(const dftu_series* v, const F& f,
270 ✔
1578
                            std::string_view sep, bool right) {
1579
    const std::int64_t n = f.n;
270 ✔
1580
    const std::int64_t lo = f.lo();
270 ✔
1581
    const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
270 ✔
1582
    const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
270 ✔
1583
    const std::size_t sl = sep.size();
270 ✔
1584
    const Bits cand = compute_bits(simd::BitKind::Eq, p, nbytes,
405 ✔
1585
                                   static_cast<std::uint8_t>(sep[0]), false);
270 !
1586
    std::vector<std::size_t> at(static_cast<std::size_t>(n), simd::NPOS);
270 !
1587
    std::vector<std::int32_t> list_off(static_cast<std::size_t>(n + 1), 0);
270 !
1588
    std::int64_t parts = 0, bytes = 0;
270 ✔
1589
    for (std::int64_t i = 0; i < n; ++i) {
44,546 ✔
1590
        if (!f.is_null(i)) {
44,276 ✔
1591
            const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
36,394 ✔
1592
            const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
36,394 ✔
1593
            at[static_cast<std::size_t>(i)] =
36,394 ✔
1594
                find_sep(cand.bad.data(), p, s, e, sep, right);
36,394 !
1595
            parts += 3;
36,394 ✔
1596
            bytes += static_cast<std::int64_t>(e - s);
36,394 ✔
1597
            if (parts > std::numeric_limits<std::int32_t>::max())
36,394 !
1598
                return nullptr;
×
1599
        }
18,197 ✔
1600
        list_off[static_cast<std::size_t>(i + 1)] =
44,276 ✔
1601
            static_cast<std::int32_t>(parts);
22,138 ✔
1602
    }
22,138 ✔
1603
    if (bytes > std::numeric_limits<std::int32_t>::max()) return nullptr;
270 !
1604
    auto coff = Buffer::allocate(static_cast<std::size_t>(parts + 1) *
270 !
1605
                                 sizeof(std::int32_t));
1606
    auto cdata = Buffer::allocate(static_cast<std::size_t>(bytes));
270 !
1607
    auto* co = reinterpret_cast<std::int32_t*>(coff->data());
270 ✔
1608
    std::uint8_t* cd = cdata->data();
270 ✔
1609
    std::int64_t w = 0, k = 0;
270 ✔
1610
    co[0] = 0;
270 ✔
1611
    auto put = [&](const std::uint8_t* src, std::int64_t len) {
164,043 ✔
1612
        copy_bytes(cd + w, src, len);
109,182 ✔
1613
        w += len;
109,182 ✔
1614
        co[++k] = static_cast<std::int32_t>(w);
109,182 ✔
1615
    };
54,591 ✔
1616
    for (std::int64_t i = 0; i < n; ++i) {
44,546 ✔
1617
        if (f.is_null(i)) continue;
44,276 ✔
1618
        const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
36,394 ✔
1619
        const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
36,394 ✔
1620
        const std::size_t q = at[static_cast<std::size_t>(i)];
36,394 ✔
1621
        if (q == simd::NPOS) {
36,394 ✔
1622
            // Python: (row, "", "") for partition, ("", "", row) for
1623
            // rpartition.
1624
            if (!right) {
23,130 ✔
1625
                put(p + s, static_cast<std::int64_t>(e - s));
10,506 !
1626
                put(p, 0);
10,506 !
1627
                put(p, 0);
10,506 !
1628
            } else {
5,253 ✔
1629
                put(p, 0);
12,624 !
1630
                put(p, 0);
12,624 !
1631
                put(p + s, static_cast<std::int64_t>(e - s));
12,624 !
1632
            }
1633
            continue;
23,130 ✔
1634
        }
1635
        put(p + s, static_cast<std::int64_t>(q - s));
13,264 !
1636
        put(p + q, static_cast<std::int64_t>(sl));
13,264 !
1637
        put(p + q + sl, static_cast<std::int64_t>(e - q - sl));
13,264 !
1638
    }
6,632 ✔
1639
    return make_str_list(v, list_off, parts, std::move(coff), std::move(cdata));
270 !
1640
}
270 ✔
1641

1642
template <class F>
1643
dftu_series* rfind_impl(const dftu_series* v, const F& f,
214 ✔
1644
                        std::string_view needle) {
1645
    const std::int64_t lo = f.lo();
214 ✔
1646
    const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
214 ✔
1647
    const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
214 ✔
1648
    Bits cand;
214 ✔
1649
    if (!needle.empty())
214 ✔
1650
        cand = compute_bits(simd::BitKind::Eq, p, nbytes,
285 !
1651
                            static_cast<std::uint8_t>(needle[0]), false);
190 !
1652
    auto* out = new dftu_series();
214 !
1653
    out->type = TypeId::Int64;
214 ✔
1654
    out->encoding = Encoding::Flat;
214 ✔
1655
    out->length = f.n;
214 ✔
1656
    out->null_count = v->null_count;
214 ✔
1657
    out->validity = v->validity;
214 ✔
1658
    out->data = Buffer::allocate(buffer_bytes(TypeId::Int64, f.n));
214 !
1659
    auto* r = reinterpret_cast<std::int64_t*>(out->data->data());
214 ✔
1660
    for (std::int64_t i = 0; i < f.n; ++i) {
31,294 ✔
1661
        if (f.is_null(i)) {
31,080 ✔
1662
            r[i] = 0;
5,620 ✔
1663
            continue;
5,620 ✔
1664
        }
1665
        const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
25,460 ✔
1666
        const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
25,460 ✔
1667
        if (needle.empty()) {
25,460 ✔
1668
            r[i] = static_cast<std::int64_t>(e - s);
3,592 ✔
1669
            continue;
3,592 ✔
1670
        }
1671
        const std::size_t q = find_sep(cand.bad.data(), p, s, e, needle, true);
21,868 !
1672
        r[i] = q == simd::NPOS ? -1 : static_cast<std::int64_t>(q - s);
21,868 ✔
1673
    }
10,934 ✔
1674
    return out;
214 ✔
1675
}
214 ✔
1676

1677
std::int64_t count_literal(std::string_view s, std::string_view pat) {
1,560 ✔
1678
    if (pat.empty()) return static_cast<std::int64_t>(s.size()) + 1;
1,560 ✔
1679
    std::int64_t n = 0;
1,536 ✔
1680
    std::size_t pos = 0;
1,536 ✔
1681
    while (true) {
1,904 ✔
1682
        const std::size_t hit = s.find(pat, pos);
3,808 ✔
1683
        if (hit == std::string_view::npos) break;
3,808 ✔
1684
        ++n;
2,272 ✔
1685
        pos = hit + pat.size();
2,272 ✔
1686
    }
1,136 ✔
1687
    return n;
1,536 ✔
1688
}
780 ✔
1689

1690
}  // namespace
1691

1692
dftu_series* dftu_series_str_slice(const dftu_series* v, int64_t start,
322 ✔
1693
                                   int64_t length) {
1694
    if (!v || !is_string_kind(v->type)) return nullptr;
322 !
1695
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_slice(flat_v, start, length));
266 ✔
1696
    return slice_impl(v, start, length);
254 ✔
1697
}
161 ✔
1698

1699
dftu_series* dftu_series_str_pad_start(const dftu_series* v, int64_t width,
272 ✔
1700
                                       char fill) {
1701
    if (!v || !is_string_kind(v->type)) return nullptr;
272 !
1702
    DFTU_FLAT_OPERAND(v, flat_v,
216 ✔
1703
                      dftu_series_str_pad_start(flat_v, width, fill));
1704
    return pad_impl(v, width, fill, 0);
204 ✔
1705
}
136 ✔
1706
dftu_series* dftu_series_str_pad_end(const dftu_series* v, int64_t width,
268 ✔
1707
                                     char fill) {
1708
    if (!v || !is_string_kind(v->type)) return nullptr;
268 !
1709
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_pad_end(flat_v, width, fill));
212 ✔
1710
    return pad_impl(v, width, fill, 1);
200 ✔
1711
}
134 ✔
1712
dftu_series* dftu_series_str_center(const dftu_series* v, int64_t width,
256 ✔
1713
                                    char fill) {
1714
    if (!v || !is_string_kind(v->type)) return nullptr;
256 !
1715
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_center(flat_v, width, fill));
200 ✔
1716
    return pad_impl(v, width, fill, 2);
188 ✔
1717
}
128 ✔
1718
dftu_series* dftu_series_str_zfill(const dftu_series* v, int64_t width) {
248 ✔
1719
    if (!v || !is_string_kind(v->type)) return nullptr;
248 !
1720
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_zfill(flat_v, width));
192 ✔
1721
    return zfill_impl(v, width);
180 ✔
1722
}
124 ✔
1723

1724
dftu_series* dftu_series_str_split(const dftu_series* v, const char* sep,
320 ✔
1725
                                   int32_t sep_len) {
1726
    if (!v || !is_string_kind(v->type)) return nullptr;
320 !
1727
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_split(flat_v, sep, sep_len));
264 !
1728
    // An empty separator is no split point: one part, the whole row.
1729
    const std::string_view s_sep(sep, static_cast<std::size_t>(sep_len));
252 ✔
1730
    return with_flat(v, [&](const auto& f) { return split_impl(v, f, s_sep); });
504 !
1731
}
160 ✔
1732

1733
dftu_series* dftu_series_str_partition(const dftu_series* v, const char* sep,
338 ✔
1734
                                       int32_t sep_len, int32_t from_right) {
1735
    if (!v || !is_string_kind(v->type) || sep_len <= 0) return nullptr;
338 !
1736
    DFTU_FLAT_OPERAND(
282 !
1737
        v, flat_v, dftu_series_str_partition(flat_v, sep, sep_len, from_right));
1738
    const std::string_view s_sep(sep, static_cast<std::size_t>(sep_len));
270 ✔
1739
    return with_flat(v, [&](const auto& f) {
675 !
1740
        return partition_impl(v, f, s_sep, from_right != 0);
270 ✔
1741
    });
135 ✔
1742
}
169 ✔
1743

1744
dftu_series* dftu_series_str_rfind(const dftu_series* v, const char* needle,
282 ✔
1745
                                   int32_t needle_len) {
1746
    if (!v || !is_string_kind(v->type)) return nullptr;
282 !
1747
    DFTU_FLAT_OPERAND(v, flat_v,
226 !
1748
                      dftu_series_str_rfind(flat_v, needle, needle_len));
1749
    const std::string_view n(needle, static_cast<std::size_t>(needle_len));
214 ✔
1750
    return with_flat(v, [&](const auto& f) { return rfind_impl(v, f, n); });
428 !
1751
}
141 ✔
1752

1753
dftu_series* dftu_series_str_case(const dftu_series* v, int32_t op) {
302 ✔
1754
    if (!v || !is_string_kind(v->type)) return nullptr;
302 !
1755
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_case(flat_v, op));
246 ✔
1756
    switch (static_cast<dftu_str_case>(op)) {
232 ✔
1757
        case DFTU_STR_CAPITALIZE:
38 ✔
1758
            return case_impl(v, simd::CaseKind::Lower, true);
76 ✔
1759
        case DFTU_STR_TITLE_CASE:
52 ✔
1760
            return case_impl(v, simd::CaseKind::Title, false);
104 ✔
1761
        case DFTU_STR_SWAPCASE:
25 ✔
1762
            return case_impl(v, simd::CaseKind::Swapcase, false);
50 ✔
1763
    }
1764
    return nullptr;
2 ✔
1765
}
151 ✔
1766

1767
dftu_series* dftu_series_str_is(const dftu_series* v, int32_t cls) {
612 ✔
1768
    if (!v) return nullptr;
612 ✔
1769
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_is(flat_v, cls));
612 ✔
1770
    return is_impl(v, cls);
584 ✔
1771
}
306 ✔
1772

1773
dftu_series* dftu_series_str_count(const dftu_series* v, const char* pat,
130 ✔
1774
                                   int32_t pat_len) {
1775
    if (!v || !is_string_kind(v->type)) return nullptr;
130 !
1776
    std::string_view p(pat, static_cast<std::size_t>(pat_len));
72 ✔
1777
    return string_int64(
72 !
1778
        v, [p](std::string_view s) { return count_literal(s, p); });
1,632 ✔
1779
}
65 ✔
1780

1781
dftu_series* dftu_series_str_remove_prefix(const dftu_series* v,
224 ✔
1782
                                           const char* prefix, int32_t len) {
1783
    if (!v || !is_string_kind(v->type)) return nullptr;
224 !
1784
    DFTU_FLAT_OPERAND(v, flat_v,
168 ✔
1785
                      dftu_series_str_remove_prefix(flat_v, prefix, len));
1786
    return remove_affix_impl(
234 !
1787
        v, std::string_view(prefix, static_cast<std::size_t>(len)), true);
156 ✔
1788
}
112 ✔
1789

1790
dftu_series* dftu_series_str_remove_suffix(const dftu_series* v,
218 ✔
1791
                                           const char* suffix, int32_t len) {
1792
    if (!v || !is_string_kind(v->type)) return nullptr;
218 !
1793
    DFTU_FLAT_OPERAND(v, flat_v,
162 ✔
1794
                      dftu_series_str_remove_suffix(flat_v, suffix, len));
1795
    return remove_affix_impl(
225 !
1796
        v, std::string_view(suffix, static_cast<std::size_t>(len)), false);
150 ✔
1797
}
109 ✔
1798

1799
dftu_series* dftu_series_str_repeat(const dftu_series* v, int64_t n) {
202 ✔
1800
    if (!v || !is_string_kind(v->type) || n < 0) return nullptr;
202 !
1801
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_repeat(flat_v, n));
144 ✔
1802
    return repeat_impl(v, n);
132 ✔
1803
}
101 ✔
1804

1805
dftu_series* dftu_series_str_cat(const dftu_series* a, const dftu_series* b) {
1,948 ✔
1806
    if (!a || !b) return nullptr;
1,948 !
1807
    DFTU_FLAT_OPERAND(a, flat_a, dftu_series_str_cat(flat_a, b));
1,948 ✔
1808
    DFTU_FLAT_OPERAND(b, flat_b, dftu_series_str_cat(a, flat_b));
1,920 ✔
1809
    if (!is_string_kind(a->type) || !is_string_kind(b->type) ||
2,810 !
1810
        a->length != b->length)
1,836 ✔
1811
        return nullptr;
58 ✔
1812
    const bool wa = is_wide_offset_type(a->type);
1,834 ✔
1813
    const bool wb = is_wide_offset_type(b->type);
1,834 ✔
1814
    if (wa && wb) return cat_impl<std::int64_t, std::int64_t>(a, b);
1,834 !
1815
    if (wa) return cat_impl<std::int64_t, std::int32_t>(a, b);
1,834 !
1816
    if (wb) return cat_impl<std::int32_t, std::int64_t>(a, b);
1,834 !
1817
    return cat_impl<std::int32_t, std::int32_t>(a, b);
1,834 ✔
1818
}
974 ✔
1819

1820
dftu_series* dftu_series_list_join(const dftu_series* v, const char* sep,
378 ✔
1821
                                   int32_t sep_len) {
1822
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_list_join(flat_v, sep, sep_len));
378 !
1823
    if (!v || v->type != TypeId::List || v->encoding != Encoding::Flat)
350 !
1824
        return nullptr;
94 ✔
1825
    if (!dftu_series_offsets(v) || !v->child() ||
384 !
1826
        !is_string_kind(v->child()->type))
256 !
1827
        return nullptr;
×
1828
    const dftu_series& child = *v->child();
256 ✔
1829
    const std::string_view s(sep, static_cast<std::size_t>(sep_len));
256 ✔
1830
    return is_wide_offset_type(child.type)
256 !
1831
               ? join_impl<std::int64_t>(v, child, s)
128 !
1832
               : join_impl<std::int32_t>(v, child, s);
256 !
1833
}
189 ✔
1834

1835
dftu_series* dftu_series_str_findall(const dftu_series* v, const char* pattern,
130 ✔
1836
                                     int32_t pattern_len) {
1837
    if (!v || !is_string_kind(v->type)) return nullptr;
130 !
1838
    DFTU_FLAT_OPERAND(v, flat_v,
74 !
1839
                      dftu_series_str_findall(flat_v, pattern, pattern_len));
1840
    const auto re = compiled(
31 !
1841
        duql::compile_regex(pattern_text(pattern, pattern_len), false));
62 !
1842
    if (!re) return nullptr;
62 ✔
1843
    LimitedRows limited;
58 ✔
1844
    dftu_series* out = list_transform(
58 !
1845
        v, [&](std::string_view row, std::vector<std::string>& parts) {
3,903 ✔
1846
            const auto r = duql::findall(
5,811 !
1847
                *re, row, [&](std::string_view m) { parts.emplace_back(m); });
59,338 ✔
1848
            if (r == duql::MatchResult::LIMIT) limited.add(row);
3,874 ✔
1849
        });
3,874 ✔
1850
    return limited.apply(out, v);
58 !
1851
}
96 ✔
1852

1853
// Unicode text ops over UTF-8 rows: normalize, translate and wrap. A row that
1854
// is not valid UTF-8 is null in the output.
1855
namespace {
1856

1857
// The bytes of the codepoint at p (0 when it is not valid UTF-8: a stray or
1858
// truncated sequence, an overlong form, a surrogate or past U+10FFFF), and the
1859
// codepoint in `cp`.
1860
std::size_t utf8_next(const std::uint8_t* p, const std::uint8_t* end,
4,734 ✔
1861
                      std::uint32_t& cp) {
1862
    std::uint32_t c = *p;
4,734 ✔
1863
    if (c < 0x80) {
4,734 ✔
1864
        cp = c;
4,334 ✔
1865
        return 1;
4,334 ✔
1866
    }
1867
    std::size_t extra;
1868
    std::uint32_t least;
1869
    if (c >= 0xC2 && c <= 0xDF) {
400 !
1870
        extra = 1;
218 ✔
1871
        least = 0x80;
218 ✔
1872
        c &= 0x1F;
218 ✔
1873
    } else if ((c & 0xF0) == 0xE0) {
291 ✔
1874
        extra = 2;
74 ✔
1875
        least = 0x800;
74 ✔
1876
        c &= 0x0F;
74 ✔
1877
    } else if (c >= 0xF0 && c <= 0xF4) {
145 !
1878
        extra = 3;
82 ✔
1879
        least = 0x10000;
82 ✔
1880
        c &= 0x07;
82 ✔
1881
    } else {
41 ✔
1882
        return 0;
26 ✔
1883
    }
1884
    if (static_cast<std::size_t>(end - p) <= extra) return 0;
374 !
1885
    for (std::size_t k = 1; k <= extra; ++k) {
986 ✔
1886
        if ((p[k] & 0xC0) != 0x80) return 0;
612 !
1887
        c = (c << 6) | (p[k] & 0x3F);
612 ✔
1888
    }
306 ✔
1889
    if (c < least || c > 0x10FFFF || (c >= 0xD800 && c <= 0xDFFF)) return 0;
374 !
1890
    cp = c;
374 ✔
1891
    return extra + 1;
374 ✔
1892
}
2,367 ✔
1893

1894
bool decode_utf8(std::string_view s, std::vector<std::uint32_t>& out) {
636 ✔
1895
    out.clear();
636 ✔
1896
    const auto* p = reinterpret_cast<const std::uint8_t*>(s.data());
636 ✔
1897
    const auto* end = p + s.size();
636 ✔
1898
    while (p < end) {
2,622 ✔
1899
        std::uint32_t cp;
1900
        const std::size_t n = utf8_next(p, end, cp);
2,000 ✔
1901
        if (n == 0) return false;
2,000 ✔
1902
        out.push_back(cp);
1,986 !
1903
        p += n;
1,986 ✔
1904
    }
1905
    return true;
622 ✔
1906
}
318 ✔
1907

1908
void encode_utf8(std::uint32_t c, std::string& out) {
4,046 ✔
1909
    if (c < 0x80) {
4,046 ✔
1910
        out.push_back(static_cast<char>(c));
3,452 ✔
1911
    } else if (c < 0x800) {
2,320 ✔
1912
        out.push_back(static_cast<char>(0xC0 | (c >> 6)));
274 ✔
1913
        out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
274 ✔
1914
    } else if (c < 0x10000) {
457 !
1915
        out.push_back(static_cast<char>(0xE0 | (c >> 12)));
320 ✔
1916
        out.push_back(static_cast<char>(0x80 | ((c >> 6) & 0x3F)));
320 ✔
1917
        out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
320 ✔
1918
    } else {
160 ✔
NEW
1919
        out.push_back(static_cast<char>(0xF0 | (c >> 18)));
×
NEW
1920
        out.push_back(static_cast<char>(0x80 | ((c >> 12) & 0x3F)));
×
NEW
1921
        out.push_back(static_cast<char>(0x80 | ((c >> 6) & 0x3F)));
×
NEW
1922
        out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
×
1923
    }
1924
}
4,046 ✔
1925

1926
bool is_ascii_row(std::string_view s) {
504 ✔
1927
    for (const char ch : s)
1,460 ✔
1928
        if (static_cast<unsigned char>(ch) >= 0x80) return false;
1,234 ✔
1929
    return true;
226 ✔
1930
}
252 ✔
1931

1932
// A narrow String column whose row i is what `fn(row, buf)` leaves in `buf`;
1933
// `fn` returns false to make the row null. A null input row stays null.
1934
template <class Off, class Fn>
1935
dftu_series* transform_rows_w(const dftu_series* v, Fn& fn) {
240 ✔
1936
    RowReader<Off> r(v);
240 !
1937
    if (!r.ok()) return nullptr;
240 !
1938
    const std::size_t n = static_cast<std::size_t>(v->length);
240 ✔
1939
    std::vector<std::int32_t> offsets(n + 1, 0);
240 !
1940
    std::string data;
240 ✔
1941
    std::string buf;
240 ✔
1942
    std::vector<std::uint8_t> valid((n + 7) / 8, 0);
240 !
1943
    bool any_null = false;
240 ✔
1944
    for (std::size_t i = 0; i < n; ++i) {
1,540 ✔
1945
        bool hit = false;
1,300 ✔
1946
        if (!r.is_null(static_cast<std::int64_t>(i)) &&
2,392 !
1947
            fn(r.at(static_cast<std::int64_t>(i)), buf)) {
1,092 !
1948
            data.append(buf);
1,050 !
1949
            hit = true;
1,050 ✔
1950
            if (!fits_int32_offsets(data.size())) return nullptr;
1,050 !
1951
        }
525 ✔
1952
        if (hit)
1,300 ✔
1953
            valid[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
1,050 ✔
1954
        else
1955
            any_null = true;
250 ✔
1956
        offsets[i + 1] = static_cast<std::int32_t>(data.size());
1,300 ✔
1957
    }
650 ✔
1958
    return dftu_series_new_string(DFTU_TYPE_STRING, offsets.data(), data.data(),
460 !
1959
                                  static_cast<int64_t>(n),
120 ✔
1960
                                  any_null ? valid.data() : nullptr);
340 !
1961
}
240 ✔
1962

1963
template <class Fn>
1964
dftu_series* transform_rows(const dftu_series* v, Fn fn) {
240 ✔
1965
    return is_wide_offset_type(v->type) ? transform_rows_w<std::int64_t>(v, fn)
240 ✔
1966
                                        : transform_rows_w<std::int32_t>(v, fn);
237 ✔
1967
}
1968

1969
bool is_utf8_string(const dftu_series* v) {
628 ✔
1970
    return v && narrow_varwidth_type(v->type) == TypeId::String;
628 ✔
1971
}
1972

1973
// translate: the codepoint table.
1974
struct TranslateTable {
1975
    // The replacement of an ASCII byte, an index into `reps`, or -1.
1976
    std::int32_t ascii[128];
1977
    // Sorted by codepoint; the other keys.
1978
    std::vector<std::pair<std::uint32_t, std::int32_t>> wide;
1979
    std::vector<std::string> reps;
1980
    TranslateTable() { std::fill(std::begin(ascii), std::end(ascii), -1); }
159 !
1981

1982
    std::int32_t find(std::uint32_t cp) const {
2,722 ✔
1983
        if (cp < 0x80) return ascii[cp];
2,722 ✔
1984
        const auto it = std::lower_bound(
288 !
1985
            wide.begin(), wide.end(), cp,
144 ✔
1986
            [](const auto& e, std::uint32_t k) { return e.first < k; });
142 ✔
1987
        return it != wide.end() && it->first == cp ? it->second : -1;
288 ✔
1988
    }
1,361 ✔
1989
};
1990

1991
struct StringRows {
1992
    std::vector<std::string> rows;
1993
    std::vector<bool> nulls;
1994
};
1995

1996
template <class Off>
1997
bool read_rows_w(const dftu_series* s, StringRows& out) {
184 ✔
1998
    RowReader<Off> r(s);
184 !
1999
    if (!r.ok()) return false;
184 !
2000
    for (std::int64_t i = 0; i < s->length; ++i) {
660 ✔
2001
        const bool is_null = r.is_null(i);
476 ✔
2002
        out.nulls.push_back(is_null);
476 !
2003
        out.rows.emplace_back(is_null ? std::string_view() : r.at(i));
476 !
2004
    }
238 ✔
2005
    return true;
184 ✔
2006
}
184 ✔
2007

2008
bool read_rows(const dftu_series* s, StringRows& out) {
208 ✔
2009
    if (s->length == 0) return true;
208 ✔
2010
    std::unique_ptr<dftu_series, decltype(&dftu_series_free)> flat(
92 ✔
2011
        nullptr, &dftu_series_free);
184 ✔
2012
    if (s->encoding != Encoding::Flat) {
184 ✔
NEW
2013
        flat.reset(dftu_series_materialize(s));
×
NEW
2014
        if (!flat) return false;
×
NEW
2015
        s = flat.get();
×
2016
    }
2017
    return is_wide_offset_type(s->type) ? read_rows_w<std::int64_t>(s, out)
276 !
2018
                                        : read_rows_w<std::int32_t>(s, out);
184 !
2019
}
196 ✔
2020

2021
bool build_translate_table(const dftu_series* from, const dftu_series* to,
106 ✔
2022
                           TranslateTable& t) {
2023
    if (!is_utf8_string(from) || !is_utf8_string(to) ||
159 !
2024
        from->length != to->length)
106 ✔
2025
        return false;
2 ✔
2026
    StringRows keys, vals;
104 ✔
2027
    if (!read_rows(from, keys) || !read_rows(to, vals)) return false;
104 !
2028
    std::vector<std::uint32_t> key, val;
104 ✔
2029
    for (std::size_t i = 0; i < keys.rows.size(); ++i) {
330 ✔
2030
        if (keys.nulls[i] || !decode_utf8(keys.rows[i], key) || key.size() != 1)
238 !
2031
            return false;
9 ✔
2032
        if (!vals.nulls[i] && !decode_utf8(vals.rows[i], val)) return false;
232 !
2033
        const auto rep = static_cast<std::int32_t>(t.reps.size());
230 ✔
2034
        t.reps.push_back(vals.nulls[i] ? std::string() : vals.rows[i]);
230 !
2035
        if (key[0] < 0x80) {
230 ✔
2036
            if (t.ascii[key[0]] >= 0) return false;
188 ✔
2037
            t.ascii[key[0]] = rep;
184 ✔
2038
        } else {
92 ✔
2039
            t.wide.emplace_back(key[0], rep);
42 !
2040
        }
2041
    }
113 ✔
2042
    std::sort(t.wide.begin(), t.wide.end());
92 !
2043
    return std::adjacent_find(t.wide.begin(), t.wide.end(),
92 !
2044
                              [](const auto& a, const auto& b) {
12 ✔
2045
                                  return a.first == b.first;
12 ✔
2046
                              }) == t.wide.end();
138 ✔
2047
}
105 ✔
2048

2049
}  // namespace
2050

2051
// wrap: textwrap.TextWrapper of CPython 3.13.10 and 3.14.1 on codepoints. A
2052
// non-ASCII codepoint counts as a letter and a word character in the splitting
2053
// rules.
2054
namespace {
2055

2056
struct WrapChunk {
2057
    std::uint32_t s;
2058
    std::uint32_t e;
2059
    std::int64_t len() const { return static_cast<std::int64_t>(e - s); }
926 ✔
2060
};
2061

2062
bool wrap_is_ws(std::uint32_t c) { return (c >= 9 && c <= 13) || c == ' '; }
3,114 !
2063

2064
bool wrap_is_letter(std::uint32_t c) {
686 ✔
2065
    return c >= 0x80 || c == '_' || (c >= 'a' && c <= 'z') ||
725 !
2066
           (c >= 'A' && c <= 'Z');
382 ✔
2067
}
2068

2069
bool wrap_is_word(std::uint32_t c) {
646 ✔
2070
    return wrap_is_letter(c) || (c >= '0' && c <= '9');
646 !
2071
}
2072

2073
bool wrap_is_punct_word(std::uint32_t c) {
646 ✔
2074
    return wrap_is_word(c) || c == '!' || c == '"' || c == '\'' || c == '&' ||
664 !
2075
           c == '.' || c == ',' || c == '?';
341 !
2076
}
2077

2078
// Python's str.isspace for one codepoint.
2079
bool py_is_space(std::uint32_t c) {
372 ✔
2080
    return (c >= 9 && c <= 13) || (c >= 0x1C && c <= 0x20) || c == 0x85 ||
490 !
2081
           c == 0xA0 || c == 0x1680 || (c >= 0x2000 && c <= 0x200A) ||
236 !
2082
           c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F ||
490 !
2083
           c == 0x3000;
304 ✔
2084
}
2085

2086
class Wrapper {
2087
   public:
2088
    Wrapper(std::int64_t width, std::int32_t flags)
124 ✔
2089
        : width_(width),
62 ✔
2090
          expand_tabs_((flags & DFTU_WRAP_EXPAND_TABS) != 0),
62 ✔
2091
          replace_ws_((flags & DFTU_WRAP_REPLACE_WHITESPACE) != 0),
62 ✔
2092
          drop_ws_((flags & DFTU_WRAP_DROP_WHITESPACE) != 0),
62 ✔
2093
          break_long_((flags & DFTU_WRAP_BREAK_LONG_WORDS) != 0),
62 ✔
2094
          break_hyphens_((flags & DFTU_WRAP_BREAK_ON_HYPHENS) != 0) {}
124 ✔
2095

2096
    // The lines of `src` joined by "\n" in `out`.
2097
    void run(const std::vector<std::uint32_t>& src, std::string& out) {
220 ✔
2098
        munge(src);
220 ✔
2099
        if (break_hyphens_)
220 ✔
2100
            split_hyphens();
68 ✔
2101
        else
2102
            split_spaces();
152 ✔
2103
        wrap(out);
220 ✔
2104
    }
220 ✔
2105

2106
   private:
2107
    void munge(const std::vector<std::uint32_t>& src) {
220 ✔
2108
        t_.clear();
220 ✔
2109
        std::uint32_t col = 0;
220 ✔
2110
        for (const std::uint32_t c : src) {
1,676 ✔
2111
            if (c == '\t' && expand_tabs_) {
1,456 ✔
2112
                const std::uint32_t k = 8 - col % 8;
4 ✔
2113
                t_.insert(t_.end(), k, std::uint32_t{' '});
4 !
2114
                col += k;
4 ✔
2115
                continue;
4 ✔
2116
            }
2 ✔
2117
            col = (c == '\n' || c == '\r') ? 0 : col + 1;
1,452 !
2118
            t_.push_back(replace_ws_ && wrap_is_ws(c) ? std::uint32_t{' '} : c);
1,452 !
2119
        }
2120
    }
220 ✔
2121

2122
    void emit(std::size_t s, std::size_t e) {
590 ✔
2123
        chunks_.push_back(
885 !
2124
            {static_cast<std::uint32_t>(s), static_cast<std::uint32_t>(e)});
295 ✔
2125
    }
590 ✔
2126

2127
    void split_spaces() {
152 ✔
2128
        chunks_.clear();
152 ✔
2129
        const std::size_t n = t_.size();
152 ✔
2130
        std::size_t i = 0;
152 ✔
2131
        while (i < n) {
368 ✔
2132
            const bool ws = wrap_is_ws(t_[i]);
216 ✔
2133
            std::size_t j = i + 1;
216 ✔
2134
            while (j < n && wrap_is_ws(t_[j]) == ws) ++j;
424 ✔
2135
            emit(i, j);
216 ✔
2136
            i = j;
216 ✔
2137
        }
2138
    }
152 ✔
2139

2140
    // Whether t_[j..] is two or more '-' followed by a word character.
2141
    bool dashes_then_word(std::size_t j) const {
640 ✔
2142
        const std::size_t n = t_.size();
640 ✔
2143
        std::size_t k = j;
640 ✔
2144
        while (k < n && t_[k] == '-') ++k;
642 ✔
2145
        return k - j >= 2 && k < n && wrap_is_word(t_[k]);
640 !
2146
    }
2147

2148
    // wordsep_re: whitespace runs, an em-dash between words, or a word that
2149
    // ends at whitespace, the end, a hyphen inside a word or before an
2150
    // em-dash.
2151
    void split_hyphens() {
68 ✔
2152
        chunks_.clear();
68 ✔
2153
        const std::vector<std::uint32_t>& t = t_;
68 ✔
2154
        const std::size_t n = t.size();
68 ✔
2155
        std::size_t i = 0;
68 ✔
2156
        while (i < n) {
442 ✔
2157
            if (wrap_is_ws(t[i])) {
374 ✔
2158
                std::size_t j = i + 1;
156 ✔
2159
                while (j < n && wrap_is_ws(t[j])) ++j;
174 ✔
2160
                emit(i, j);
156 ✔
2161
                i = j;
156 ✔
2162
                continue;
156 ✔
2163
            }
78 ✔
2164
            if (t[i] == '-' && i > 0 && wrap_is_punct_word(t[i - 1]) &&
218 !
NEW
2165
                dashes_then_word(i)) {
×
NEW
2166
                std::size_t j = i;
×
NEW
2167
                while (j < n && t[j] == '-') ++j;
×
NEW
2168
                emit(i, j);
×
NEW
2169
                i = j;
×
NEW
2170
                continue;
×
2171
            }
2172
            std::size_t j = i + 1;
218 ✔
2173
            while (true) {
432 ✔
2174
                if (j < n && t[j] == '-' && hyphen_break(j)) {
864 ✔
2175
                    emit(i, j + 1);
10 ✔
2176
                    i = j + 1;
10 ✔
2177
                    break;
10 ✔
2178
                }
2179
                if (j >= n || wrap_is_ws(t[j]) ||
1,817 ✔
2180
                    (wrap_is_punct_word(t[j - 1]) && dashes_then_word(j))) {
966 ✔
2181
                    emit(i, j);
208 ✔
2182
                    i = j;
208 ✔
2183
                    break;
208 ✔
2184
                }
2185
                ++j;
646 ✔
2186
            }
2187
        }
2188
    }
68 ✔
2189

2190
    // The '-' at t_[j] ends a chunk: two letters, or a letter, '-' and a
2191
    // letter, before it, and a letter, an optional '-' and a letter after it.
2192
    bool hyphen_break(std::size_t j) const {
12 ✔
2193
        const std::vector<std::uint32_t>& t = t_;
12 ✔
2194
        const std::size_t n = t.size();
12 ✔
2195
        const bool before =
6 ✔
2196
            (j >= 2 && wrap_is_letter(t[j - 2]) && wrap_is_letter(t[j - 1])) ||
13 !
2197
            (j >= 3 && wrap_is_letter(t[j - 3]) && t[j - 2] == '-' &&
1 !
NEW
2198
             wrap_is_letter(t[j - 1]));
×
2199
        if (!before) return false;
12 ✔
2200
        if (j + 2 >= n || !wrap_is_letter(t[j + 1])) return false;
10 !
2201
        return wrap_is_letter(t[j + 2]) ||
10 ✔
2202
               (t[j + 2] == '-' && j + 3 < n && wrap_is_letter(t[j + 3]));
5 !
2203
    }
6 ✔
2204

2205
    bool space_chunk(const WrapChunk& c) const {
348 ✔
2206
        for (std::uint32_t k = c.s; k < c.e; ++k)
484 ✔
2207
            if (!py_is_space(t_[k])) return false;
372 ✔
2208
        return true;
112 ✔
2209
    }
174 ✔
2210

2211
    void handle_long_word(std::size_t pos, std::int64_t cur_len) {
38 ✔
2212
        const std::int64_t space_left = width_ - cur_len;
38 ✔
2213
        if (break_long_ && space_left > 0) {
38 ✔
2214
            std::int64_t end = space_left;
30 ✔
2215
            WrapChunk& chunk = chunks_[pos];
30 ✔
2216
            if (break_hyphens_ && chunk.len() > space_left) {
30 !
2217
                std::int64_t hyphen = -1;
28 ✔
2218
                for (std::int64_t k = space_left - 1; k >= 0; --k)
98 ✔
2219
                    if (t_[chunk.s + k] == '-') {
70 !
NEW
2220
                        hyphen = k;
×
NEW
2221
                        break;
×
2222
                    }
2223
                bool other = false;
28 ✔
2224
                for (std::int64_t k = 0; k < hyphen && !other; ++k)
28 !
NEW
2225
                    other = t_[chunk.s + k] != '-';
×
2226
                if (hyphen > 0 && other) end = hyphen + 1;
28 !
2227
            }
14 ✔
2228
            const auto cut = chunk.s + static_cast<std::uint32_t>(end);
30 ✔
2229
            line_.push_back({chunk.s, cut});
30 !
2230
            chunk.s = cut;
30 ✔
2231
        } else if (line_.empty()) {
38 ✔
2232
            line_.push_back(chunks_[pos]);
4 ✔
2233
            taken_ = true;
4 ✔
2234
        }
2 ✔
2235
    }
38 ✔
2236

2237
    void wrap(std::string& out) {
220 ✔
2238
        out.clear();
220 ✔
2239
        std::size_t pos = 0;
220 ✔
2240
        const std::size_t total = chunks_.size();
220 ✔
2241
        bool any_line = false;
220 ✔
2242
        while (pos < total) {
580 ✔
2243
            line_.clear();
360 ✔
2244
            std::int64_t cur_len = 0;
360 ✔
2245
            if (drop_ws_ && any_line && space_chunk(chunks_[pos])) ++pos;
360 ✔
2246
            while (pos < total) {
920 ✔
2247
                const std::int64_t l = chunks_[pos].len();
706 ✔
2248
                if (cur_len + l > width_) break;
706 ✔
2249
                line_.push_back(chunks_[pos++]);
560 ✔
2250
                cur_len += l;
560 ✔
2251
            }
2252
            if (pos < total && chunks_[pos].len() > width_) {
360 ✔
2253
                taken_ = false;
38 ✔
2254
                handle_long_word(pos, cur_len);
38 ✔
2255
                if (taken_) ++pos;
38 ✔
2256
                cur_len = 0;
38 ✔
2257
                for (const WrapChunk& c : line_) cur_len += c.len();
84 ✔
2258
            }
19 ✔
2259
            if (drop_ws_ && !line_.empty() && space_chunk(line_.back()))
360 !
2260
                line_.pop_back();
86 ✔
2261
            if (line_.empty()) continue;
360 ✔
2262
            if (any_line) out.push_back('\n');
352 ✔
2263
            any_line = true;
352 ✔
2264
            for (const WrapChunk& c : line_)
860 ✔
2265
                for (std::uint32_t k = c.s; k < c.e; ++k)
1,844 ✔
2266
                    encode_utf8(t_[k], out);
1,336 !
2267
        }
2268
    }
220 ✔
2269

2270
    std::int64_t width_;
2271
    bool expand_tabs_;
2272
    bool replace_ws_;
2273
    bool drop_ws_;
2274
    bool break_long_;
2275
    bool break_hyphens_;
2276
    bool taken_ = false;
31 ✔
2277
    std::vector<std::uint32_t> t_;
2278
    std::vector<WrapChunk> chunks_;
2279
    std::vector<WrapChunk> line_;
2280
};
2281

2282
}  // namespace
2283

2284
dftu_series* dftu_series_str_normalize(const dftu_series* v, int32_t form) {
166 ✔
2285
    if (!is_utf8_string(v)) return nullptr;
166 ✔
2286
    int options = UTF8PROC_STABLE;
108 ✔
2287
    switch (form) {
108 ✔
2288
        case DFTU_NORM_NFC:
7 ✔
2289
            options |= UTF8PROC_COMPOSE;
14 ✔
2290
            break;
14 ✔
2291
        case DFTU_NORM_NFKC:
35 ✔
2292
            options |= UTF8PROC_COMPOSE | UTF8PROC_COMPAT;
70 ✔
2293
            break;
70 ✔
2294
        case DFTU_NORM_NFD:
4 ✔
2295
            options |= UTF8PROC_DECOMPOSE;
8 ✔
2296
            break;
8 ✔
2297
        case DFTU_NORM_NFKD:
6 ✔
2298
            options |= UTF8PROC_DECOMPOSE | UTF8PROC_COMPAT;
12 ✔
2299
            break;
12 ✔
2300
        default:
2 ✔
2301
            return nullptr;
4 ✔
2302
    }
2303
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_normalize(flat_v, form));
104 !
2304
    const auto opts = static_cast<utf8proc_option_t>(options);
86 ✔
2305
    std::vector<utf8proc_int32_t> cps;
129 ✔
2306
    return transform_rows(v, [&](std::string_view row, std::string& out) {
338 !
2307
        out.clear();
504 ✔
2308
        if (is_ascii_row(row)) {
504 ✔
2309
            out.assign(row);
226 ✔
2310
            return true;
226 ✔
2311
        }
2312
        const auto* src = reinterpret_cast<const utf8proc_uint8_t*>(row.data());
278 ✔
2313
        const auto len = static_cast<utf8proc_ssize_t>(row.size());
278 ✔
2314
        if (cps.size() < row.size()) cps.resize(row.size());
278 ✔
2315
        auto n =
139 ✔
2316
            utf8proc_decompose(src, len, cps.data(),
417 ✔
2317
                               static_cast<utf8proc_ssize_t>(cps.size()), opts);
278 ✔
2318
        if (n > static_cast<utf8proc_ssize_t>(cps.size())) {
278 ✔
NEW
2319
            cps.resize(static_cast<std::size_t>(n));
×
NEW
2320
            n = utf8proc_decompose(src, len, cps.data(), n, opts);
×
2321
        }
2322
        if (n < 0) return false;
278 ✔
2323
        n = utf8proc_normalize_utf32(cps.data(), n, opts);
260 ✔
2324
        if (n < 0) return false;
260 ✔
2325
        for (utf8proc_ssize_t i = 0; i < n; ++i)
2,970 ✔
2326
            encode_utf8(static_cast<std::uint32_t>(cps[i]), out);
2,710 ✔
2327
        return true;
260 ✔
2328
    });
295 ✔
2329
}
83 ✔
2330

2331
dftu_series* dftu_series_str_translate(const dftu_series* v,
110 ✔
2332
                                       const dftu_series* from,
2333
                                       const dftu_series* to) {
2334
    if (!is_utf8_string(v) || !from || !to) return nullptr;
110 !
2335
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_translate(flat_v, from, to));
110 !
2336
    TranslateTable table;
106 !
2337
    if (!build_translate_table(from, to, table)) return nullptr;
106 !
2338
    return transform_rows(v, [&](std::string_view row, std::string& out) {
270 !
2339
        out.clear();
356 ✔
2340
        const auto* begin = reinterpret_cast<const std::uint8_t*>(row.data());
356 ✔
2341
        const auto* end = begin + row.size();
356 ✔
2342
        const auto* run = begin;
356 ✔
2343
        for (const auto* p = begin; p < end;) {
3,078 ✔
2344
            std::uint32_t cp;
2345
            const std::size_t n = utf8_next(p, end, cp);
2,734 ✔
2346
            if (n == 0) return false;
2,734 ✔
2347
            const std::int32_t rep = table.find(cp);
2,722 !
2348
            if (rep >= 0) {
2,722 ✔
2349
                out.append(reinterpret_cast<const char*>(run),
561 ✔
2350
                           static_cast<std::size_t>(p - run));
374 !
2351
                out.append(table.reps[static_cast<std::size_t>(rep)]);
374 !
2352
                run = p + n;
374 ✔
2353
            }
187 ✔
2354
            p += n;
2,722 ✔
2355
        }
2356
        out.append(reinterpret_cast<const char*>(run),
516 ✔
2357
                   static_cast<std::size_t>(end - run));
344 ✔
2358
        return true;
344 ✔
2359
    });
224 ✔
2360
}
108 ✔
2361

2362
dftu_series* dftu_series_str_wrap(const dftu_series* v, int64_t width,
140 ✔
2363
                                  int32_t flags) {
2364
    constexpr std::int32_t ALL_FLAGS =
140 ✔
2365
        DFTU_WRAP_EXPAND_TABS | DFTU_WRAP_REPLACE_WHITESPACE |
2366
        DFTU_WRAP_DROP_WHITESPACE | DFTU_WRAP_BREAK_LONG_WORDS |
2367
        DFTU_WRAP_BREAK_ON_HYPHENS;
2368
    if (!is_utf8_string(v) || width < 1 || (flags & ~ALL_FLAGS) != 0)
140 ✔
2369
        return nullptr;
62 ✔
2370
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_wrap(flat_v, width, flags));
78 !
2371
    Wrapper wrapper(width, flags);
62 ✔
2372
    std::vector<std::uint32_t> cps;
62 ✔
2373
    return transform_rows(v, [&](std::string_view row, std::string& out) {
178 !
2374
        if (!decode_utf8(row, cps)) return false;
232 ✔
2375
        wrapper.run(cps, out);
220 ✔
2376
        return true;
220 ✔
2377
    });
147 ✔
2378
}
101 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc