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

llnl-asr / dftracer-utils / 45982802704

27 Nov 2026 10:31AM UTC coverage: 77.583% (-0.008%) from 77.591%
45982802704

Pull #119

github

web-flow
Merge 19141038b into 9c0c823c8
Pull Request #119: feat(python): take the pandas eval syntax in dataframe query

166938 of 258053 branches covered (64.69%)

Branch coverage included in aggregate %.

2908 of 3029 new or added lines in 43 files covered. (96.01%)

31 existing lines in 15 files now uncovered.

192748 of 205562 relevant lines covered (93.77%)

4648330.98 hits per line

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

82.58
/src/dftracer/utils/dataframe/kernels/string_ops.cpp
1
// SPDX-License-Identifier: MIT
2
#include <dftracer/utils/dataframe/c_api.h>
3
#include <dftracer/utils/dataframe/internal/column_data.h>
4
#include <dftracer/utils/dataframe/internal/string_reader.h>
5
#include <dftracer/utils/dataframe/internal/string_simd.h>
6
#include <dftracer/utils/dataframe/internal/varwidth_offsets.h>
7
#include <dftracer/utils/dataframe/kernels/limited_rows.h>
8
#include <dftracer/utils/dataframe/kernels/string_match.h>
9
#include <dftracer/utils/dataframe/kernels/string_ops.h>
10
#include <dftracer/utils/dataframe/parallel.h>
11
#include <dftracer/utils/dstd/ascii.h>
12
#include <dftracer/utils/dstd/bits.h>
13
#include <dftracer/utils/dstd/hash/fnv1a.h>
14
#include <dftracer/utils/dstd/hash/hex64.h>
15
#include <dftracer/utils/dstd/hash_map.h>
16
#include <dftracer/utils/dstd/memory.h>
17
#include <dftracer/utils/dstd/optional.h>
18
#include <dftracer/utils/dstd/pair.h>
19
#include <dftracer/utils/dstd/scope_exit.h>
20
#include <dftracer/utils/dstd/string.h>
21
#include <dftracer/utils/dstd/vector.h>
22
#include <dftracer/utils/duql/pattern_engine.h>
23
#include <dftracer/utils/duql/substr_simd.h>
24
#include <utf8proc.h>
25

26
#include <algorithm>
27
#include <cstdint>
28
#include <cstring>
29
#include <limits>
30
#include <memory>
31
#include <mutex>
32
#include <optional>
33
#include <string>
34
#include <type_traits>
35

36
using namespace dftracer::utils;
37

38
using duql::detail::substr_find;
39

40
namespace dftracer::utils::dataframe {
41

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

56
}  // namespace dftracer::utils::dataframe
57

58
namespace {
59
using dftracer::utils::dataframe::buffer_bytes;
60
using dftracer::utils::dataframe::BufferView;
61
using dftracer::utils::dataframe::Encoding;
62
using dftracer::utils::dataframe::is_wide_offset_type;
63
using dftracer::utils::dataframe::narrow_varwidth_type;
64
using dftracer::utils::dataframe::new_buffer;
65
using dftracer::utils::dataframe::offsets_of;
66
using dftracer::utils::dataframe::parallel_backend_installed;
67
using dftracer::utils::dataframe::parallel_for;
68
using dftracer::utils::dataframe::string_int64;
69
using dftracer::utils::dataframe::string_mask;
70
using dftracer::utils::dataframe::TypeId;
71
using dftracer::utils::dataframe::writable;
72

73
// String or Binary, at either offset width (narrow_varwidth_type folds the
74
// Large variants into the same case).
75
bool is_string_kind(TypeId t) {
21,140 ✔
76
    const TypeId n = narrow_varwidth_type(t);
21,140 ✔
77
    return n == TypeId::String || n == TypeId::Binary;
21,140 ✔
78
}
10,543 ✔
79

80
// Per-row byte reader over a String/Binary(/Large) column: every layer
81
// resolves through str_at, which gives the row's bytes and the nulls of every
82
// layer.
83
class RowReader {
84
   public:
85
    explicit RowReader(const dftu_series* v) : v_(v) {
5,322 ✔
86
        ok_ = is_string_kind(v->type);
3,566 ✔
87
    }
3,512 ✔
88
    bool ok() const { return ok_; }
1,756 ✔
89
    /// The bytes of row `i`; false for a null row at any layer.
90
    bool at(std::int64_t i, dftracer::utils::dstd::StringView& out) const {
637,920 ✔
91
        return dftracer::utils::dataframe::str_at(v_, i, out);
323,241 ✔
92
    }
93

94
   private:
95
    const dftu_series* v_;
96
    bool ok_ = false;
1,756 ✔
97
};
98

99
// Int64 output column with the same length/validity as `v` (nulls preserved).
100
dftu_series* make_i64(const dftu_series* v,
460 ✔
101
                      dftracer::utils::dstd::Span<const std::int64_t> vals) {
102
    auto* out = new dftu_series();
460 ✔
103
    out->type = TypeId::Int64;
460 ✔
104
    out->encoding = Encoding::Flat;
460 ✔
105
    out->length = v->length;
460 ✔
106
    out->null_count = v->null_count;
460 ✔
107
    out->validity = v->validity;
460 ✔
108
    std::size_t bytes = buffer_bytes(TypeId::Int64, v->length);
460 ✔
109
    out->data = new_buffer(bytes);
460 !
110
    if (bytes != 0) std::memcpy(writable(out->data), vals.data(), bytes);
460 ✔
111
    return out;
663 ✔
112
}
203 ✔
113

114
// UInt64 output column with the same length as `v`. `validity` is a fresh
115
// Arrow-layout bitmap the caller owns, or NULL to share `v`'s nulls.
116
dftu_series* make_u64(const dftu_series* v,
138 ✔
117
                      dftracer::utils::dstd::Span<const std::uint64_t> vals,
118
                      const std::uint8_t* validity) {
119
    auto* out = new dftu_series();
138 ✔
120
    out->type = TypeId::Uint64;
138 ✔
121
    out->encoding = Encoding::Flat;
138 ✔
122
    out->length = v->length;
138 ✔
123
    std::size_t bytes = buffer_bytes(TypeId::Uint64, v->length);
138 ✔
124
    out->data = new_buffer(bytes);
138 !
125
    if (bytes != 0) std::memcpy(writable(out->data), vals.data(), bytes);
138 ✔
126
    if (validity) {
138 ✔
127
        std::size_t vb = static_cast<std::size_t>((v->length + 7) / 8);
54 ✔
128
        out->validity = new_buffer(vb);
54 !
129
        if (vb != 0) std::memcpy(writable(out->validity), validity, vb);
54 ✔
130
    } else {
27 ✔
131
        out->null_count = v->null_count;
84 ✔
132
        out->validity = v->validity;
84 ✔
133
    }
134
    return out;
207 ✔
135
}
69 ✔
136

137
// Flat String output column from one string per row (size == v->length); shares
138
// v's validity so null rows stay null (their bytes are ignored). Always
139
// narrow (int32 offsets): a derived per-row transform's total size is its own
140
// fresh sizing question, not a width the source column forces on it. nullptr
141
// when the bytes pass INT32_MAX.
142
dftu_series* make_string(
446 ✔
143
    const dftu_series* v,
144
    dftracer::utils::dstd::Span<const dftracer::utils::dstd::String> parts) {
145
    std::size_t total = 0;
446 ✔
146
    for (const dftracer::utils::dstd::String& p : parts) total += p.size();
3,796 ✔
147
    if (!fits_int32_offsets(total)) return nullptr;
446 !
148
    auto* out = new dftu_series();
446 ✔
149
    out->type = TypeId::String;
446 ✔
150
    out->encoding = Encoding::Flat;
446 ✔
151
    out->length = v->length;
446 ✔
152
    out->null_count = v->null_count;
446 ✔
153
    out->validity = v->validity;
446 ✔
154
    std::size_t off_bytes =
669 ✔
155
        static_cast<std::size_t>(v->length + 1) * sizeof(std::int32_t);
446 ✔
156
    out->offsets = new_buffer(off_bytes);
446 !
157
    out->data = new_buffer(total);
446 !
158
    std::int32_t* od = reinterpret_cast<std::int32_t*>(writable(out->offsets));
446 ✔
159
    char* bd =
669 ✔
160
        total != 0 ? reinterpret_cast<char*>(writable(out->data)) : nullptr;
446 ✔
161
    std::int32_t pos = 0;
446 ✔
162
    od[0] = 0;
446 ✔
163
    for (std::int64_t i = 0; i < v->length; ++i) {
3,796 ✔
164
        const dftracer::utils::dstd::String& p =
5,025 ✔
165
            parts[static_cast<std::size_t>(i)];
3,350 ✔
166
        if (!p.empty()) std::memcpy(bd + pos, p.data(), p.size());
3,350 ✔
167
        pos += static_cast<std::int32_t>(p.size());
3,350 ✔
168
        od[i + 1] = pos;
3,350 ✔
169
    }
1,675 ✔
170
    return out;
223 ✔
171
}
223 ✔
172

173
// Gives `out` the offsets of the rows of `v` for a data buffer that holds
174
// only the bytes [lo, hi) of v's own: shared when lo is 0, rebased otherwise.
175
template <class Off>
176
void window_offsets(const dftu_series& v, dftu_series& out, std::int64_t lo) {
1,819 ✔
177
    if (lo == 0) {
1,819 ✔
178
        offsets_of<Off>(out) = offsets_of<Off>(v);
1,799 ✔
179
        return;
1,799 ✔
180
    }
181
    const Off* src = reinterpret_cast<const Off*>(offsets_of<Off>(v).data());
20 ✔
182
    auto buf = new_buffer(static_cast<std::size_t>(v.length + 1) * sizeof(Off));
20 ✔
183
    Off* dst = reinterpret_cast<Off*>(writable(buf));
20 ✔
184
    for (std::int64_t i = 0; i <= v.length; ++i)
9,748 ✔
185
        dst[i] = static_cast<Off>(src[i] - lo);
9,728 ✔
186
    offsets_of<Off>(out) = std::move(buf);
20 !
187
}
903 ✔
188

189
// Fold that keeps offsets/validity and rewrites only the (byte-length
190
// preserving) data buffer. Fast path SIMD for a FLAT input, preserving the
191
// source's own offset width and buffer (no copy of the offsets); a
192
// DICTIONARY input falls back through make_string (always narrow) per row.
193
template <class Off>
194
dftu_series* ascii_fold_w(const dftu_series* v, std::uint8_t lo,
1,645 ✔
195
                          std::uint8_t hi, int add) {
196
    RowReader r(v);
1,645 ✔
197
    if (!r.ok()) return nullptr;
1,645 ✔
198
    if (v->encoding == Encoding::Flat) {
1,531 !
199
        auto* out = new dftu_series();
1,530 ✔
200
        out->type = v->type;
1,531 ✔
201
        out->encoding = Encoding::Flat;
1,531 ✔
202
        out->length = v->length;
1,531 ✔
203
        out->null_count = v->null_count;
1,531 ✔
204
        out->validity = v->validity;
1,531 ✔
205
        const Off* offs =
1,476 ✔
206
            reinterpret_cast<const Off*>(offsets_of<Off>(*v).data());
1,530 ✔
207
        const std::int64_t base = v->length != 0 ? offs[0] : 0;
1,530 ✔
208
        const std::size_t data_size =
2,268 ✔
209
            v->data.block() && v->length != 0
1,530 !
210
                ? static_cast<std::size_t>(offs[v->length] - base)
2,314 !
211
                : 0;
212
        window_offsets<Off>(*v, *out, base);
1,530 ✔
213
        out->data = new_buffer(data_size);
1,530 !
214
        if (data_size != 0)
1,531 ✔
215
            dataframe::strsimd::ascii_fold(v->data.data() + base,
2,245 ✔
216
                                           writable(out->data), data_size, lo,
730 ✔
217
                                           hi, add);
730 ✔
218
        return out;
1,531 ✔
219
    }
738 ✔
220
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> parts(
×
221
        static_cast<std::size_t>(v->length));
×
222
    for (std::int64_t i = 0; i < v->length; ++i) {
×
NEW
223
        dftracer::utils::dstd::StringView sv;
×
NEW
224
        if (!r.at(i, sv)) continue;
×
NEW
225
        dftracer::utils::dstd::String s(sv);
×
226
        for (char& c : s)
×
227
            if (static_cast<std::uint8_t>(c) >= lo &&
×
228
                static_cast<std::uint8_t>(c) <= hi)
229
                c = static_cast<char>(c + add);
×
230
        parts[static_cast<std::size_t>(i)] = std::move(s);
×
231
    }
×
232
    return make_string(v, parts);
×
233
}
795 ✔
234

235
dftu_series* ascii_fold(const dftu_series* v, std::uint8_t lo, std::uint8_t hi,
1,646 ✔
236
                        int add) {
237
    return is_wide_offset_type(v->type)
1,646 ✔
238
               ? ascii_fold_w<std::int64_t>(v, lo, hi, add)
854 ✔
239
               : ascii_fold_w<std::int32_t>(v, lo, hi, add);
1,638 ✔
240
}
241

242
// Per-row string transform (scalar) at offset width `Off`; null rows pass
243
// through as null. Output is always narrow (see make_string).
244
template <class Off, class Fn>
245
dftu_series* string_transform_w(const dftu_series* v, Fn fn) {
726 ✔
246
    RowReader r(v);
726 ✔
247
    if (!r.ok()) return nullptr;
726 !
248
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> parts(
892 ✔
249
        static_cast<std::size_t>(v->length));
446 ✔
250
    dftracer::utils::dstd::StringView sv;
446 ✔
251
    for (std::int64_t i = 0; i < v->length; ++i) {
3,796 ✔
252
        if (!r.at(i, sv)) continue;
3,350 ✔
253
        parts[static_cast<std::size_t>(i)] = fn(sv);
2,882 ✔
254
    }
1,441 ✔
255
    return make_string(v, parts);
446 ✔
256
}
586 ✔
257

258
template <class Fn>
259
dftu_series* string_transform(const dftu_series* v, Fn fn) {
726 ✔
260
    return is_wide_offset_type(v->type)
726 ✔
261
               ? string_transform_w<std::int64_t>(v, fn)
373 ✔
262
               : string_transform_w<std::int32_t>(v, fn);
706 ✔
263
}
264

265
bool is_ascii_ws(char c) {
2,124 ✔
266
    return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' ||
2,124 !
267
           c == '\v';
2,006 ✔
268
}
269

270
dftracer::utils::dstd::StringView lstrip_ws(
1,094 ✔
271
    dftracer::utils::dstd::StringView s) {
272
    std::size_t b = 0;
1,094 ✔
273
    while (b < s.size() && is_ascii_ws(s[b])) ++b;
1,224 ✔
274
    return s.substr(b);
1,094 ✔
275
}
547 ✔
276
dftracer::utils::dstd::StringView rstrip_ws(
1,094 ✔
277
    dftracer::utils::dstd::StringView s) {
278
    std::size_t e = s.size();
1,094 ✔
279
    while (e > 0 && is_ascii_ws(s[e - 1])) --e;
1,200 ✔
280
    return s.substr(0, e);
1,094 ✔
281
}
547 ✔
282

283
dftracer::utils::dstd::String replace_literal(
1,248 ✔
284
    dftracer::utils::dstd::StringView s, dftracer::utils::dstd::StringView pat,
285
    dftracer::utils::dstd::StringView repl, bool all) {
286
    // An empty pattern has no well-defined occurrence; leave the row unchanged
287
    // (also avoids a zero-advance loop in the all-occurrences case).
288
    if (pat.empty()) return dftracer::utils::dstd::String(s);
1,248 !
289
    dftracer::utils::dstd::String out;
1,248 ✔
290
    std::size_t pos = 0;
1,248 ✔
291
    while (true) {
1,820 ✔
292
        std::size_t hit = s.find(pat, pos);
1,820 ✔
293
        if (hit == dftracer::utils::dstd::StringView::npos) break;
1,820 ✔
294
        out.append(s.substr(pos, hit - pos));
796 ✔
295
        out.append(repl);
796 ✔
296
        pos = hit + pat.size();
796 ✔
297
        if (!all) break;
796 ✔
298
    }
910 !
299
    out.append(s.substr(pos));
1,248 ✔
300
    return out;
1,248 ✔
301
}
1,872 !
302

303
}  // namespace
304

305
namespace dftracer::utils::dataframe {
306

307
Series str_pattern(const Series& v, const duql::CompiledPattern& p) {
30 ✔
308
    if (!v.valid()) return {};
30 !
309
    return Series{kernels::string_match().pattern(v.handle(), p)};
30 ✔
310
}
15 ✔
311

312
}  // namespace dftracer::utils::dataframe
313

314
namespace {
315

316
template <class Off>
317
dftu_series* regex_replace_w(const dftu_series* v,
236 ✔
318
                             const duql::CompiledPattern& re,
319
                             const duql::Substitution& sub) {
320
    RowReader r(v);
236 ✔
321
    if (!r.ok()) return nullptr;
236 ✔
322
    const std::size_t n = static_cast<std::size_t>(v->length);
178 ✔
323
    dftracer::utils::dstd::Vector<std::int32_t> offsets(n + 1, 0);
178 ✔
324
    dftracer::utils::dstd::String data;
178 ✔
325
    dftracer::utils::dstd::String buf;
178 ✔
326
    dftracer::utils::dstd::Vector<std::uint8_t> valid((n + 7) / 8, 0);
178 ✔
327
    bool any_null = false;
178 ✔
328
    for (std::size_t i = 0; i < n; ++i) {
1,372 !
329
        bool hit = false;
1,194 ✔
330
        dftracer::utils::dstd::StringView s;
1,194 ✔
331
        if (r.at(static_cast<std::int64_t>(i), s)) {
1,194 ✔
332
            if (duql::regex_replace(re, sub, s, buf) !=
1,018 !
333
                duql::MatchResult::Limit) {
334
                data.append(buf);
1,018 ✔
335
                hit = true;
1,018 !
336
                if (!fits_int32_offsets(data.size())) return nullptr;
1,018 !
337
            }
509 ✔
338
        }
509 ✔
339
        if (hit)
597 ✔
340
            valid[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
1,018 ✔
341
        else
342
            any_null = true;
88 ✔
343
        offsets[i + 1] = static_cast<std::int32_t>(data.size());
1,194 ✔
344
    }
597 !
345
    return dftu_series_new_string(DFTU_TYPE_STRING, offsets.data(), data.data(),
338 ✔
346
                                  static_cast<std::int64_t>(n),
89 ✔
347
                                  any_null ? valid.data() : nullptr);
249 !
348
}
207 ✔
349

350
dftu_series* regex_replace_flat(const dftu_series* v,
236 ✔
351
                                const duql::CompiledPattern& re,
352
                                const duql::Substitution& sub) {
353
    return is_wide_offset_type(v->type)
236 ✔
354
               ? regex_replace_w<std::int64_t>(v, re, sub)
120 ✔
355
               : regex_replace_w<std::int32_t>(v, re, sub);
232 ✔
356
}
357

358
}  // namespace
359

360
namespace dftracer::utils::dataframe {
361

362
Series str_regex_replace(const Series& v, const duql::CompiledPattern& p,
18 ✔
363
                         const duql::Substitution& sub) {
364
    if (!v.valid()) return {};
18 !
365
    const Series flat = v.materialize();
18 ✔
366
    return Series{regex_replace_flat(flat.handle(), p, sub)};
18 !
367
}
18 ✔
368

369
}  // namespace dftracer::utils::dataframe
370

371
namespace {
372

373
duql::PatternPtr compiled(duql::PatternResult r) {
1,474 ✔
374
    return r ? std::move(*r) : nullptr;
2,204 ✔
375
}
376

377
}  // namespace
378

379
dftu_series* dftu_series_str_eq(const dftu_series* v, const char* rhs,
314 ✔
380
                                std::int32_t rhs_size) {
381
    return dataframe::kernels::string_match().eq(
628 ✔
382
        v, dftracer::utils::dstd::StringView(
314 ✔
383
               rhs, static_cast<std::size_t>(rhs_size)));
314 ✔
384
}
385

386
dftu_series* dftu_series_str_contains(const dftu_series* v, const char* needle,
506 ✔
387
                                      std::int32_t needle_size) {
388
    return dataframe::kernels::string_match().contains(
1,012 ✔
389
        v, dftracer::utils::dstd::StringView(
506 ✔
390
               needle, static_cast<std::size_t>(needle_size)));
506 ✔
391
}
392

393
dftu_series* dftu_series_str_starts_with(const dftu_series* v,
262 ✔
394
                                         const char* prefix,
395
                                         std::int32_t prefix_size) {
396
    return dataframe::kernels::string_match().starts_with(
524 ✔
397
        v, dftracer::utils::dstd::StringView(
262 ✔
398
               prefix, static_cast<std::size_t>(prefix_size)));
262 ✔
399
}
400

401
dftu_series* dftu_series_str_ends_with(const dftu_series* v, const char* suffix,
214 ✔
402
                                       std::int32_t suffix_size) {
403
    return dataframe::kernels::string_match().ends_with(
428 ✔
404
        v, dftracer::utils::dstd::StringView(
214 ✔
405
               suffix, static_cast<std::size_t>(suffix_size)));
214 ✔
406
}
407

408
dftu_series* dftu_series_str_matches(const dftu_series* v, const char* pattern,
220 ✔
409
                                     std::int32_t pattern_size) {
410
    const auto p = compiled(duql::compile_regex(
330 ✔
411
        dftracer::utils::dstd::StringView(
110 ✔
412
            pattern, static_cast<std::size_t>(pattern_size)),
110 ✔
413
        false, /*whole=*/true));
110 ✔
414
    if (!p) return nullptr;
220 ✔
415
    return dataframe::kernels::string_match().pattern(v, *p);
220 ✔
416
}
220 ✔
417

418
namespace {
419

420
// The capture `group` of the first `re` match in each row, null where the row
421
// is null or does not match: a String column with its own validity.
422
template <class Off>
423
dftu_series* str_extract_w(const dftu_series* v,
74 ✔
424
                           const duql::CompiledPattern& re, std::size_t group) {
425
    RowReader r(v);
74 ✔
426
    if (!r.ok()) return nullptr;
74 !
427
    const std::size_t n = static_cast<std::size_t>(v->length);
74 ✔
428
    dftracer::utils::dstd::Vector<std::int32_t> offsets(n + 1, 0);
74 ✔
429
    dftracer::utils::dstd::String data;
74 ✔
430
    dftracer::utils::dstd::Vector<std::uint8_t> valid((n + 7) / 8, 0);
74 ✔
431
    bool any_null = false;
74 ✔
432
    for (std::size_t i = 0; i < n; ++i) {
624,908 !
433
        bool hit = false;
624,834 ✔
434
        dftracer::utils::dstd::StringView s;
624,834 ✔
435
        if (r.at(static_cast<std::int64_t>(i), s)) {
624,834 ✔
436
            dftracer::utils::dstd::StringView m;
623,158 ✔
437
            if (duql::extract(re, s, group, m) == duql::MatchResult::Yes) {
623,158 ✔
438
                data.append(m);
620,446 ✔
439
                hit = true;
620,446 !
440
                if (!fits_int32_offsets(data.size())) return nullptr;
620,446 !
441
            }
310,223 ✔
442
        }
311,579 !
443
        if (hit)
312,417 ✔
444
            valid[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
620,446 ✔
445
        else
446
            any_null = true;
2,194 ✔
447
        offsets[i + 1] = static_cast<std::int32_t>(data.size());
624,834 ✔
448
    }
312,417 !
449
    return dftu_series_new_string(DFTU_TYPE_STRING, offsets.data(), data.data(),
144 ✔
450
                                  static_cast<std::int64_t>(n),
37 ✔
451
                                  any_null ? valid.data() : nullptr);
107 !
452
}
74 ✔
453

454
}  // namespace
455

456
dftu_series* dftu_series_str_extract(const dftu_series* v, const char* pattern,
218 ✔
457
                                     std::int32_t pattern_size,
458
                                     std::int64_t group) {
459
    if (!v || !pattern || group < 0) return nullptr;
218 !
460
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_extract, pattern,
218 !
461
                                pattern_size, group);
462
    DFTU_FLAT_OPERAND(
200 !
463
        v, flat_v,
464
        dftu_series_str_extract(flat_v, pattern, pattern_size, group));
465
    const auto re = compiled(duql::compile_regex(
252 ✔
466
        dftracer::utils::dstd::StringView(
84 ✔
467
            pattern, static_cast<std::size_t>(pattern_size)),
84 ✔
468
        false));
84 ✔
469
    if (!re) return nullptr;
168 ✔
470
    const auto g = static_cast<std::size_t>(group);
166 ✔
471
    if (g > duql::capture_count(*re)) return nullptr;
166 ✔
472
    return is_wide_offset_type(v->type)
74 ✔
473
               ? str_extract_w<std::int64_t>(v, *re, g)
39 ✔
474
               : str_extract_w<std::int32_t>(v, *re, g);
70 ✔
475
}
218 ✔
476

477
dftu_series* dftu_series_str_regex_replace(const dftu_series* v,
274 ✔
478
                                           const char* pattern,
479
                                           std::int32_t pattern_size,
480
                                           const char* to,
481
                                           std::int32_t to_size) {
482
    if (!v || !pattern || !to) return nullptr;
274 !
483
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_regex_replace, pattern,
274 !
484
                                pattern_size, to, to_size);
485
    DFTU_FLAT_OPERAND(v, flat_v,
266 !
486
                      dftu_series_str_regex_replace(flat_v, pattern,
487
                                                    pattern_size, to, to_size));
488
    const auto re = compiled(duql::compile_regex(
351 ✔
489
        dftracer::utils::dstd::StringView(
117 ✔
490
            pattern, static_cast<std::size_t>(pattern_size)),
117 ✔
491
        false));
117 ✔
492
    if (!re) return nullptr;
234 ✔
493
    auto sub = duql::compile_substitution(
456 ✔
494
        *re, dftracer::utils::dstd::StringView(
342 ✔
495
                 to, static_cast<std::size_t>(to_size)));
228 ✔
496
    if (!sub) return nullptr;
228 ✔
497
    return regex_replace_flat(v, *re, *sub);
218 ✔
498
}
254 ✔
499

500
dftu_series* dftu_series_str_search(const dftu_series* v, const char* pattern,
494 ✔
501
                                    std::int32_t pattern_size) {
502
    const auto p = compiled(duql::compile_regex(
741 ✔
503
        dftracer::utils::dstd::StringView(
247 ✔
504
            pattern, static_cast<std::size_t>(pattern_size)),
247 ✔
505
        false));
247 ✔
506
    if (!p) return nullptr;
494 ✔
507
    return dataframe::kernels::string_match().pattern(v, *p);
494 ✔
508
}
494 ✔
509

510
dftu_series* dftu_series_str_like(const dftu_series* v, const char* pattern,
290 ✔
511
                                  std::int32_t pattern_size) {
512
    const auto p = compiled(
435 ✔
513
        duql::compile_like(dftracer::utils::dstd::StringView(
580 ✔
514
                               pattern, static_cast<std::size_t>(pattern_size)),
145 ✔
515
                           false, '\\'));
290 ✔
516
    if (!p) return nullptr;
290 ✔
517
    return dataframe::kernels::string_match().pattern(v, *p);
288 ✔
518
}
290 ✔
519

520
dftu_series* dftu_series_str_len_bytes(const dftu_series* v) {
440 ✔
521
    // FLAT, narrow offsets: adjacent int32 offset difference, vectorized.
522
    // Every other case (DICTIONARY, or a wide-offset FLAT column) is scalar;
523
    // a Large* column's row count is bounded by int32 either way, only its
524
    // byte offsets are not, so the SIMD int32 path stays narrow-only.
525
    if (v->encoding == Encoding::Flat && v->offsets.block() &&
440 !
526
        !v->wide_offsets()) {
290 !
527
        dftracer::utils::dstd::Vector<std::int64_t> vals(
408 ✔
528
            static_cast<std::size_t>(v->length), 0);
290 ✔
529
        if (v->length > 0)
290 ✔
530
            dataframe::strsimd::len_bytes(
286 ✔
531
                reinterpret_cast<const std::int32_t*>(v->offsets.data()),
286 ✔
532
                vals.data(), static_cast<std::size_t>(v->length));
116 ✔
533
        // Null rows keep 0 length regardless; validity marks them null.
534
        return make_i64(v, vals);
290 ✔
535
    }
290 ✔
536
    return string_int64(v, [](dftracer::utils::dstd::StringView s) {
1,276 ✔
537
        return static_cast<std::int64_t>(s.size());
2,268 ✔
538
    });
75 ✔
539
}
193 ✔
540

541
dftu_series* dftu_series_str_len_chars(const dftu_series* v) {
352 ✔
542
    // FLAT, narrow offsets: count non-continuation bytes per row with the
543
    // vectorized scan. DICTIONARY and wide-offset columns take the scalar
544
    // per-row path.
545
    if (v->encoding == Encoding::Flat && v->offsets.block() &&
281 ✔
546
        !v->wide_offsets() && v->data.block()) {
346 !
547
        const std::int32_t* off =
255 ✔
548
            reinterpret_cast<const std::int32_t*>(v->offsets.data());
170 ✔
549
        const std::uint8_t* data = v->data.data();
170 ✔
550
        dftracer::utils::dstd::Vector<std::int64_t> vals(
255 ✔
551
            static_cast<std::size_t>(v->length), 0);
170 ✔
552
        dataframe::strsimd::char_counts(data, off, v->length, vals.data());
170 ✔
553
        return make_i64(v, vals);
170 ✔
554
    }
170 ✔
555
    return string_int64(v, [](dftracer::utils::dstd::StringView s) {
59,412 ✔
556
        std::int64_t count = 0;
118,460 ✔
557
        for (unsigned char c : s)
1,792,668 ✔
558
            if ((c & 0xC0) != 0x80) ++count;  // non-continuation byte
1,674,208 !
559
        return count;
177,690 ✔
560
    });
59,321 ✔
561
}
176 ✔
562

563
dftu_series* dftu_series_str_find(const dftu_series* v, const char* needle,
1,452 ✔
564
                                  std::int32_t needle_size) {
565
    dftracer::utils::dstd::StringView n(needle,
2,179 ✔
566
                                        static_cast<std::size_t>(needle_size));
1,452 ✔
567
    return string_int64(v, [n](dftracer::utils::dstd::StringView s) {
74,524 ✔
568
        return substr_find(s, n);
145,963 ✔
569
    });
721 ✔
570
}
727 ✔
571

572
namespace {
573
template <class Off>
574
dftu_series* fnv1a_w(const dftu_series* v) {
150 ✔
575
    RowReader r(v);
150 ✔
576
    if (!r.ok()) return nullptr;
150 ✔
577
    dftracer::utils::dstd::Vector<std::uint64_t> vals(
160 ✔
578
        static_cast<std::size_t>(v->length), 0);
80 ✔
579
    dftracer::utils::dstd::StringView sv;
80 ✔
580
    for (std::int64_t i = 0; i < v->length; ++i) {
714 ✔
581
        if (!r.at(i, sv)) continue;
634 ✔
582
        vals[static_cast<std::size_t>(i)] =
558 ✔
583
            dftracer::utils::dstd::hash::fnv1a_hash(sv);
558 ✔
584
    }
279 ✔
585
    return make_u64(v, vals, nullptr);
80 ✔
586
}
115 ✔
587
}  // namespace
588

589
dftu_series* dftu_series_fnv1a(const dftu_series* v) {
194 ✔
590
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_fnv1a);
194 !
591
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_fnv1a(flat_v));
186 !
592

593
    return is_wide_offset_type(v->type) ? fnv1a_w<std::int64_t>(v)
150 ✔
594
                                        : fnv1a_w<std::int32_t>(v);
140 ✔
595
}
97 ✔
596

597
namespace {
598
template <class Off>
599
dftu_series* hex64_parse_w(const dftu_series* v) {
114 ✔
600
    RowReader r(v);
114 ✔
601
    if (!r.ok()) return nullptr;
114 ✔
602
    dftracer::utils::dstd::Vector<std::uint64_t> vals(
116 ✔
603
        static_cast<std::size_t>(v->length), 0);
58 ✔
604
    std::size_t bitmap_bytes = static_cast<std::size_t>((v->length + 7) / 8);
58 ✔
605
    dftracer::utils::dstd::Vector<std::uint8_t> valid(bitmap_bytes, 0);
58 ✔
606
    std::int64_t nulls = 0;
58 ✔
607
    for (std::int64_t i = 0; i < v->length; ++i) {
352 ✔
608
        dftracer::utils::dstd::Optional<std::uint64_t> parsed;
294 ✔
609
        dftracer::utils::dstd::StringView sv;
294 ✔
610
        if (r.at(i, sv)) parsed = dftracer::utils::dstd::hash::parse_hex64(sv);
294 ✔
611
        if (!parsed) {
294 ✔
612
            ++nulls;
278 ✔
613
            continue;
278 ✔
614
        }
615
        vals[static_cast<std::size_t>(i)] = *parsed;
16 ✔
616
        valid[static_cast<std::size_t>(i >> 3)] |=
16 ✔
617
            static_cast<std::uint8_t>(1u << (i & 7));
16 ✔
618
    }
147 !
619
    dftu_series* out = make_u64(v, vals, valid.data());
58 ✔
620
    out->null_count = nulls;
58 ✔
621
    return out;
29 ✔
622
}
86 ✔
623
}  // namespace
624

625
dftu_series* dftu_series_hex64_parse(const dftu_series* v) {
146 ✔
626
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_hex64_parse);
146 !
627
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_hex64_parse(flat_v));
142 !
628

629
    return is_wide_offset_type(v->type) ? hex64_parse_w<std::int64_t>(v)
114 !
630
                                        : hex64_parse_w<std::int32_t>(v);
114 ✔
631
}
73 ✔
632

633
dftu_series* dftu_series_hex64_format(const dftu_series* v) {
128 ✔
634
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_hex64_format(flat_v));
128 !
635

636
    using dftracer::utils::dstd::hash::format_hex64;
50 ✔
637
    using dftracer::utils::dstd::hash::HEX64_DIGITS;
50 ✔
638
    if (!v || (v->type != TypeId::Uint64 && v->type != TypeId::Int64)) {
100 ✔
639
        return nullptr;
32 ✔
640
    }
641
    if (v->encoding != Encoding::Flat || !v->data.block()) return nullptr;
36 !
642

643
    const std::size_t n = static_cast<std::size_t>(v->length);
36 ✔
644
    const std::size_t total = n * HEX64_DIGITS;
36 ✔
645
    // Every row is exactly HEX64_DIGITS bytes, so the byte total is known up
646
    // front; refuse rather than overflow the int32 offsets Arrow uses here.
647
    if (total > static_cast<std::size_t>(INT32_MAX)) return nullptr;
36 ✔
648

649
    const std::uint64_t* src =
54 ✔
650
        reinterpret_cast<const std::uint64_t*>(v->data.data());
36 ✔
651
    auto* out = new dftu_series();
36 ✔
652
    out->type = TypeId::String;
36 ✔
653
    out->encoding = Encoding::Flat;
36 ✔
654
    out->length = v->length;
36 ✔
655
    out->null_count = v->null_count;
36 ✔
656
    out->validity = v->validity;
36 ✔
657
    out->offsets = new_buffer((n + 1) * sizeof(std::int32_t));
36 !
658
    out->data = new_buffer(total);
36 !
659
    std::int32_t* od = reinterpret_cast<std::int32_t*>(writable(out->offsets));
36 ✔
660
    char* bd =
54 ✔
661
        total != 0 ? reinterpret_cast<char*>(writable(out->data)) : nullptr;
36 ✔
662
    for (std::size_t i = 0; i < n; ++i) {
172 ✔
663
        od[i] = static_cast<std::int32_t>(i * HEX64_DIGITS);
136 ✔
664
        format_hex64(src[i], bd + i * HEX64_DIGITS);
136 ✔
665
    }
68 ✔
666
    od[n] = static_cast<std::int32_t>(total);
36 ✔
667
    return out;
36 ✔
668
}
64 ✔
669

670
dftu_series* dftu_series_to_lowercase(const dftu_series* v) {
2,036 ✔
671
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_to_lowercase);
2,036 !
672
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_to_lowercase(flat_v));
2,018 !
673

674
    return ascii_fold(v, 'A', 'Z', 32);
1,100 ✔
675
}
1,018 ✔
676

677
dftu_series* dftu_series_to_uppercase(const dftu_series* v) {
646 ✔
678
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_to_uppercase);
646 !
679
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_to_uppercase(flat_v));
638 !
680

681
    return ascii_fold(v, 'a', 'z', -32);
546 ✔
682
}
296 ✔
683

684
dftu_series* dftu_series_str_strip(const dftu_series* v) {
190 ✔
685
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_strip);
190 !
686
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_strip(flat_v));
182 !
687

688
    return string_transform(v, [](dftracer::utils::dstd::StringView s) {
427 ✔
689
        return dftracer::utils::dstd::String(rstrip_ws(lstrip_ws(s)));
554 ✔
690
    });
352 ✔
691
}
95 ✔
692
dftu_series* dftu_series_str_lstrip(const dftu_series* v) {
180 ✔
693
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_lstrip);
180 !
694
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_lstrip(flat_v));
172 !
695

696
    return string_transform(v, [](dftracer::utils::dstd::StringView s) {
410 ✔
697
        return dftracer::utils::dstd::String(lstrip_ws(s));
540 ✔
698
    });
340 ✔
699
}
90 ✔
700
dftu_series* dftu_series_str_rstrip(const dftu_series* v) {
180 ✔
701
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_rstrip);
180 !
702
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_rstrip(flat_v));
172 !
703

704
    return string_transform(v, [](dftracer::utils::dstd::StringView s) {
410 ✔
705
        return dftracer::utils::dstd::String(rstrip_ws(s));
540 ✔
706
    });
340 ✔
707
}
90 ✔
708

709
dftu_series* dftu_series_str_replace(const dftu_series* v, const char* pat,
176 ✔
710
                                     std::int32_t pat_size, const char* repl,
711
                                     std::int32_t repl_size) {
712
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_replace, pat, pat_size, repl,
176 !
713
                                repl_size);
714
    DFTU_FLAT_OPERAND(
168 !
715
        v, flat_v,
716
        dftu_series_str_replace(flat_v, pat, pat_size, repl, repl_size));
717

718
    dftracer::utils::dstd::StringView p(pat,
204 ✔
719
                                        static_cast<std::size_t>(pat_size));
136 ✔
720
    dftracer::utils::dstd::StringView r(repl,
204 ✔
721
                                        static_cast<std::size_t>(repl_size));
136 ✔
722
    return string_transform(v, [p, r](dftracer::utils::dstd::StringView s) {
393 ✔
723
        return replace_literal(s, p, r, false);
514 ✔
724
    });
325 ✔
725
}
88 ✔
726
dftu_series* dftu_series_str_replace_all(const dftu_series* v, const char* pat,
200 ✔
727
                                         std::int32_t pat_size,
728
                                         const char* repl,
729
                                         std::int32_t repl_size) {
730
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_replace_all, pat, pat_size,
200 !
731
                                repl, repl_size);
732
    DFTU_FLAT_OPERAND(
192 !
733
        v, flat_v,
734
        dftu_series_str_replace_all(flat_v, pat, pat_size, repl, repl_size));
735

736
    dftracer::utils::dstd::StringView p(pat,
240 ✔
737
                                        static_cast<std::size_t>(pat_size));
160 ✔
738
    dftracer::utils::dstd::StringView r(repl,
240 ✔
739
                                        static_cast<std::size_t>(repl_size));
160 ✔
740
    return string_transform(v, [p, r](dftracer::utils::dstd::StringView s) {
527 ✔
741
        return replace_literal(s, p, r, true);
734 ✔
742
    });
447 ✔
743
}
100 ✔
744

745
namespace {
746
// Splits every row of `v` on `s_sep`, producing a List<String> (always
747
// narrow, both levels: the per-row part count and total byte count are the
748
// source column's own data, already known to fit an int32 row count).
749
// A List<String> column over `v`'s rows (always narrow, both levels): row i
750
// holds the parts `fn(row)` yields, a null input row a null list.
751
template <class Off, class Fn>
752
dftu_series* list_transform_w(const dftu_series* v, Fn fn) {
64 ✔
753
    RowReader r(v);
64 ✔
754
    if (!r.ok()) return nullptr;
64 !
755

756
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> all_parts;
64 ✔
757
    dftracer::utils::dstd::Vector<std::int32_t> list_off(
128 ✔
758
        static_cast<std::size_t>(v->length + 1), 0);
64 ✔
759
    dftracer::utils::dstd::StringView sv;
64 ✔
760
    for (std::int64_t i = 0; i < v->length; ++i) {
4,642 !
761
        if (r.at(i, sv)) fn(sv, all_parts);
4,578 ✔
762
        if (!fits_int32_offsets(all_parts.size())) return nullptr;
4,578 !
763
        list_off[static_cast<std::size_t>(i + 1)] =
4,578 ✔
764
            static_cast<std::int32_t>(all_parts.size());
4,578 ✔
765
    }
2,289 ✔
766
    std::size_t ctotal = 0;
64 ✔
767
    for (const dftracer::utils::dstd::String& p : all_parts) ctotal += p.size();
55,602 ✔
768
    if (!fits_int32_offsets(ctotal)) return nullptr;
64 !
769

770
    auto* child = new dftu_series();
64 ✔
771
    child->type = TypeId::String;
64 ✔
772
    child->encoding = Encoding::Flat;
64 ✔
773
    child->length = static_cast<std::int64_t>(all_parts.size());
64 ✔
774
    std::size_t coff_bytes =
96 ✔
775
        static_cast<std::size_t>(all_parts.size() + 1) * sizeof(std::int32_t);
64 ✔
776
    child->offsets = new_buffer(coff_bytes);
64 !
777
    child->data = new_buffer(ctotal);
64 !
778
    std::int32_t* cod =
64 ✔
779
        reinterpret_cast<std::int32_t*>(writable(child->offsets));
64 ✔
780
    char* cbd =
96 ✔
781
        ctotal != 0 ? reinterpret_cast<char*>(writable(child->data)) : nullptr;
64 ✔
782
    std::int32_t cpos = 0;
64 ✔
783
    cod[0] = 0;
64 ✔
784
    for (std::size_t k = 0; k < all_parts.size(); ++k) {
55,602 ✔
785
        const dftracer::utils::dstd::String& p = all_parts[k];
55,538 !
786
        if (!p.empty()) std::memcpy(cbd + cpos, p.data(), p.size());
55,538 !
787
        cpos += static_cast<std::int32_t>(p.size());
55,538 ✔
788
        cod[k + 1] = cpos;
55,538 ✔
789
    }
27,769 ✔
790

791
    auto* out = new dftu_series();
64 ✔
792
    out->type = TypeId::List;
64 ✔
793
    out->encoding = Encoding::Flat;
64 ✔
794
    out->length = v->length;
64 ✔
795
    out->null_count = v->null_count;
64 ✔
796
    out->validity = v->validity;  // a null input row stays a null list
64 ✔
797
    std::size_t loff_bytes =
96 ✔
798
        static_cast<std::size_t>(v->length + 1) * sizeof(std::int32_t);
64 ✔
799
    out->offsets = new_buffer(loff_bytes);
64 !
800
    std::memcpy(writable(out->offsets), list_off.data(), loff_bytes);
64 ✔
801
    out->set_child(adopt_series(child));
64 !
802
    return out;
64 ✔
803
}
64 ✔
804

805
template <class Fn>
806
dftu_series* list_transform(const dftu_series* v, Fn fn) {
64 ✔
807
    if (!v || !is_string_kind(v->type)) return nullptr;
64 !
808
    return is_wide_offset_type(v->type) ? list_transform_w<std::int64_t>(v, fn)
64 !
809
                                        : list_transform_w<std::int32_t>(v, fn);
64 ✔
810
}
32 ✔
811

812
}  // namespace
813

814
dftu_series* dftu_series_list_len(const dftu_series* v) {
3,456 ✔
815
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_list_len(flat_v));
3,456 !
816
    DFTU_LIST_OPERAND(v, narrow, dftu_series_list_len(narrow));
3,428 !
817

818
    if (!v || v->type != TypeId::List || v->encoding != Encoding::Flat)
3,426 !
819
        return nullptr;
49 ✔
820
    const std::int32_t* off = dftu_series_offsets(v);
3,328 ✔
821
    if (!off) return nullptr;
3,328 !
822
    const std::size_t n = static_cast<std::size_t>(v->length);
3,328 ✔
823
    dftracer::utils::dstd::Vector<std::int64_t> len(n);
3,328 ✔
824
    for (std::size_t i = 0; i < n; ++i) len[i] = off[i + 1] - off[i];
30,060 ✔
825
    auto* out = new dftu_series();
3,328 ✔
826
    out->type = TypeId::Int64;
3,328 ✔
827
    out->encoding = Encoding::Flat;
3,328 ✔
828
    out->length = v->length;
3,328 ✔
829
    out->null_count = v->null_count;
3,328 ✔
830
    out->validity = v->validity;
3,328 ✔
831
    out->data = new_buffer(n * sizeof(std::int64_t));
3,328 !
832
    if (n != 0)
3,328 ✔
833
        std::memcpy(writable(out->data), len.data(), n * sizeof(std::int64_t));
3,328 ✔
834
    return out;
3,328 ✔
835
}
3,392 ✔
836

837
dftu_series* dftu_series_list_get(const dftu_series* v, std::int64_t index) {
262 ✔
838
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_list_get(flat_v, index));
262 !
839
    DFTU_LIST_OPERAND(v, narrow, dftu_series_list_get(narrow, index));
234 !
840

841
    if (!v || v->type != TypeId::List || v->encoding != Encoding::Flat)
230 !
842
        return nullptr;
48 ✔
843
    const std::int32_t* off = dftu_series_offsets(v);
134 ✔
844
    if (!off || dftu_series_num_children(v) != 1) return nullptr;
134 !
845
    const std::size_t n = static_cast<std::size_t>(v->length);
134 ✔
846
    // A gather of the element at `index` (from the end when negative) per
847
    // row; -1 marks a null row or one whose list is too short.
848
    dftracer::utils::dstd::Vector<std::int64_t> idx(n, -1);
134 ✔
849
    for (std::size_t i = 0; i < n; ++i) {
832 ✔
850
        if (v->validity.block() &&
698 ✔
851
            !((v->validity.data()[i >> 3] >> (i & 7)) & 1))
680 ✔
852
            continue;
106 ✔
853
        const std::int64_t len = off[i + 1] - off[i];
592 ✔
854
        const std::int64_t k = index < 0 ? len + index : index;
592 ✔
855
        if (k >= 0 && k < len) idx[i] = off[i] + k;
592 ✔
856
    }
296 ✔
857
    dftu_series* child = dftu_series_child(v, 0);
134 ✔
858
    if (!child) return nullptr;
134 !
859
    dftu_series* out =
201 ✔
860
        dftu_series_take(child, idx.data(), static_cast<std::int64_t>(n));
134 ✔
861
    dftu_series_free(child);
134 ✔
862
    return out;
134 ✔
863
}
198 ✔
864

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

871
// A FLAT String/Binary column read at offset width `Off`. Offsets are
872
// absolute positions in `data`; a column cut from a larger one starts past 0.
873
template <class Off>
874
struct FlatStr {
875
    const Off* off = nullptr;
3,275 ✔
876
    const std::uint8_t* data = nullptr;
3,275 ✔
877
    const std::uint8_t* validity = nullptr;
3,275 ✔
878
    std::int64_t n = 0;
3,275 ✔
879
    bool ok = false;
3,275 ✔
880

881
    explicit FlatStr(const dftu_series* v) {
9,825 ✔
882
        if (!v || v->encoding != Encoding::Flat || !is_string_kind(v->type) ||
6,550 !
883
            is_wide_offset_type(v->type) != std::is_same_v<Off, std::int64_t>)
6,550 !
884
            return;
885
        const auto& ob = offsets_of<Off>(*v);
6,550 !
886
        if (!ob.block()) return;
6,550 !
887
        off = reinterpret_cast<const Off*>(ob.data());
6,550 ✔
888
        data = v->data.block() ? v->data.data() : nullptr;
6,550 !
889
        validity = v->validity.block() ? v->validity.data() : nullptr;
6,550 ✔
890
        n = v->length;
6,550 ✔
891
        ok = true;
6,550 ✔
892
    }
9,825 !
893
    bool is_null(std::int64_t i) const {
1,961,501 ✔
894
        return validity != nullptr && ((validity[i >> 3] >> (i & 7)) & 1) == 0;
1,961,501 ✔
895
    }
896
    std::int64_t lo() const {
1,644 ✔
897
        return n != 0 ? static_cast<std::int64_t>(off[0]) : 0;
1,572 !
898
    }
899
    std::int64_t hi() const {
1,644 ✔
900
        return n != 0 ? static_cast<std::int64_t>(off[n]) : 0;
1,580 ✔
901
    }
902
    std::int64_t len(std::int64_t i) const {
1,664,950 ✔
903
        return static_cast<std::int64_t>(off[i + 1]) - off[i];
1,664,950 ✔
904
    }
905
    const std::uint8_t* row(std::int64_t i) const { return data + off[i]; }
677,668 ✔
906
};
907

908
template <class Fn>
909
dftu_series* with_flat(const dftu_series* v, Fn&& fn) {
3,352 ✔
910
    if (!v || !is_string_kind(v->type) || v->encoding != Encoding::Flat)
3,352 !
911
        return nullptr;
29 ✔
912
    if (is_wide_offset_type(v->type)) {
3,294 !
913
        FlatStr<std::int64_t> f(v);
32 ✔
914
        return f.ok ? fn(f) : nullptr;
32 !
915
    }
16 ✔
916
    FlatStr<std::int32_t> f(v);
3,262 ✔
917
    return f.ok ? fn(f) : nullptr;
3,262 !
918
}
1,676 ✔
919

920
void share_nulls(dftu_series* out, const dftu_series* v) {
2,210 ✔
921
    if (!out) return;
2,210 ✔
922
    out->validity = v->validity;
2,208 ✔
923
    out->null_count = v->null_count;
2,208 ✔
924
}
2,209 ✔
925

926
void copy_bytes(std::uint8_t* dst, const std::uint8_t* src, std::int64_t n) {
1,623,506 ✔
927
    if (n > 0) std::memcpy(dst, src, static_cast<std::size_t>(n));
1,623,506 ✔
928
}
1,623,506 ✔
929

930
constexpr std::int64_t BUILD_GRAIN = 1 << 14;
931

932
// A narrow String column of `n` rows: row i is `len_of(i)` bytes that
933
// `fill_of(i, dst)` writes (a null row is empty and never asked). Sizes the
934
// output in one pass and fills it in a second, across the pool for a large
935
// column. nullptr when the bytes pass what an int32 offset reaches.
936
template <class IsNull, class LenFn, class FillFn>
937
dftu_series* build_flat_string(std::int64_t n, IsNull is_null, LenFn len_of,
3,558 ✔
938
                               FillFn fill_of) {
939
    auto offb =
3,558 ✔
940
        new_buffer(static_cast<std::size_t>(n + 1) * sizeof(std::int32_t));
3,558 ✔
941
    auto* od = reinterpret_cast<std::int32_t*>(writable(offb));
3,558 ✔
942
    std::int64_t total = 0;
3,558 ✔
943
    od[0] = 0;
3,558 ✔
944
    for (std::int64_t i = 0; i < n; ++i) {
626,082 !
945
        if (!is_null(i)) {
622,477 !
946
            const std::int64_t l = len_of(i);
569,581 ✔
947
            if (l < 0 || dstd::bits::add_overflow(total, l, &total) ||
569,581 !
948
                total > std::numeric_limits<std::int32_t>::max())
282,878 ✔
949
                return nullptr;
51 ✔
950
        }
282,854 !
951
        od[i + 1] = static_cast<std::int32_t>(total);
622,475 ✔
952
    }
309,178 ✔
953
    auto datab = new_buffer(static_cast<std::size_t>(total));
3,556 ✔
954
    std::uint8_t* d = writable(datab);
3,556 ✔
955
    auto body = [&](std::int64_t b, std::int64_t e) {
560,352 ✔
956
        for (std::int64_t i = b; i < e; ++i)
575,358 !
957
            if (!is_null(i)) fill_of(i, d + od[i]);
571,794 !
958
    };
1,782 ✔
959
    if (n > BUILD_GRAIN && parallel_backend_installed())
3,556 !
960
        parallel_for(n, BUILD_GRAIN, body);
4 ✔
961
    else
962
        body(0, n);
3,552 ✔
963
    auto* out = new dftu_series();
3,556 ✔
964
    out->type = TypeId::String;
3,556 ✔
965
    out->encoding = Encoding::Flat;
3,556 ✔
966
    out->length = n;
3,556 ✔
967
    out->offsets = std::move(offb);
3,556 ✔
968
    out->data = std::move(datab);
3,556 ✔
969
    return out;
3,556 !
970
}
3,606 ✔
971

972
// One string op over a single column: the output shares its nulls.
973
template <class LenFn, class FillFn>
974
dftu_series* map_strings(const dftu_series* v, LenFn len_of, FillFn fill_of) {
1,938 ✔
975
    dftu_series* out = with_flat(v, [&](const auto& f) {
3,876 ✔
976
        return build_flat_string(
4,845 ✔
977
            f.n, [&](std::int64_t i) { return f.is_null(i); },
961,240 !
978
            [&](std::int64_t i) { return len_of(f, i); },
475,519 !
979
            [&](std::int64_t i, std::uint8_t* dst) { fill_of(f, i, dst); });
417,782 ✔
980
    });
981
    share_nulls(out, v);
1,938 ✔
982
    return out;
2,907 ✔
983
}
969 ✔
984

985
// The bit arrays of one kind over p[0, n), across the pool for a large buffer.
986
struct Bits {
1,073 ✔
987
    dftracer::utils::dstd::Vector<std::uint64_t> bad;
988
    dftracer::utils::dstd::Vector<std::uint64_t> aux;
989
};
990

991
Bits compute_bits(dataframe::strsimd::BitKind kind, const std::uint8_t* p,
1,074 ✔
992
                  std::size_t n, std::uint8_t eq, bool want_aux) {
993
    const std::size_t words = (n + 63) / 64;
1,074 ✔
994
    Bits b;
1,074 ✔
995
    b.bad.assign(words + 1, 0);
1,074 ✔
996
    if (want_aux) b.aux.assign(words + 1, 0);
1,074 ✔
997
    std::uint64_t* bp = b.bad.data();
1,074 ✔
998
    std::uint64_t* ap = want_aux ? b.aux.data() : nullptr;
1,074 ✔
999
    constexpr std::int64_t CHUNK = 1 << 14;  // words: 1 MiB of bytes
1,074 ✔
1000
    if (static_cast<std::int64_t>(words) > CHUNK &&
1,074 !
1001
        parallel_backend_installed()) {
×
1002
        parallel_for(static_cast<std::int64_t>(words), CHUNK,
×
1003
                     [&](std::int64_t b0, std::int64_t e0) {
×
1004
                         dataframe::strsimd::class_bits(
×
1005
                             kind, p, n, static_cast<std::size_t>(b0),
×
1006
                             static_cast<std::size_t>(e0), eq, bp, ap);
×
1007
                     });
×
1008
    } else if (words != 0) {
1,074 ✔
1009
        dataframe::strsimd::class_bits(kind, p, n, 0, words, eq, bp, ap);
724 ✔
1010
    }
362 ✔
1011
    return b;
1,074 ✔
1012
}
537 !
1013

1014
// Narrow String out of a List<String> shape: row i of the list holds
1015
// `list_off[i + 1] - list_off[i]` strings.
1016
dftu_series* make_str_list(
588 ✔
1017
    const dftu_series* v,
1018
    dftracer::utils::dstd::Span<const std::int32_t> list_off,
1019
    std::int64_t parts, BufferView coff, BufferView cdata) {
1020
    auto* child = new dftu_series();
588 ✔
1021
    child->type = TypeId::String;
588 ✔
1022
    child->encoding = Encoding::Flat;
588 ✔
1023
    child->length = parts;
588 ✔
1024
    child->offsets = std::move(coff);
588 ✔
1025
    child->data = std::move(cdata);
588 ✔
1026
    auto* out = new dftu_series();
588 ✔
1027
    out->type = TypeId::List;
588 ✔
1028
    out->encoding = Encoding::Flat;
588 ✔
1029
    out->length = v->length;
588 ✔
1030
    out->null_count = v->null_count;
588 ✔
1031
    out->validity = v->validity;  // a null input row stays a null list
588 ✔
1032
    const std::size_t loff_bytes = list_off.size() * sizeof(std::int32_t);
588 ✔
1033
    out->offsets = new_buffer(loff_bytes);
588 !
1034
    std::memcpy(writable(out->offsets), list_off.data(), loff_bytes);
588 ✔
1035
    out->set_child(adopt_series(child));
588 !
1036
    return out;
882 ✔
1037
}
294 ✔
1038

1039
// The first (last, when `from_right`) place in row [s, e) of p where `sep`
1040
// occurs, or NPOS: candidate bits of sep's first byte, each verified.
1041
std::size_t find_sep(const std::uint64_t* cand, const std::uint8_t* p,
861,413 ✔
1042
                     std::size_t s, std::size_t e,
1043
                     dftracer::utils::dstd::StringView sep, bool from_right) {
1044
    const std::size_t sl = sep.size();
861,413 ✔
1045
    if (e - s < sl) return dataframe::strsimd::NPOS;
861,413 ✔
1046
    const std::size_t limit = e - sl + 1;  // one past the last start
860,585 ✔
1047
    auto verify = [&](std::size_t q) {
1,621,412 ✔
1048
        return sl == 1 || std::memcmp(p + q + 1, sep.data() + 1, sl - 1) == 0;
760,827 ✔
1049
    };
430,208 ✔
1050
    if (!from_right) {
860,585 ✔
1051
        std::size_t pos = s;
410,518 ✔
1052
        while (pos < limit) {
905,695 ✔
1053
            const std::size_t q =
1,357,732 ✔
1054
                dataframe::strsimd::bits_next(cand, pos, limit);
905,043 ✔
1055
            if (q >= limit) return dataframe::strsimd::NPOS;
905,043 ✔
1056
            if (verify(q)) return q;
643,852 ✔
1057
            pos = q + 1;
84,662 ✔
1058
        }
452,689 ✔
1059
        return dataframe::strsimd::NPOS;
326 ✔
1060
    }
410,518 ✔
1061
    std::size_t lim = limit;
19,859 ✔
1062
    while (lim > s) {
142,488 ✔
1063
        const std::size_t q = dataframe::strsimd::bits_prev(cand, s, lim);
141,768 ✔
1064
        if (q == dataframe::strsimd::NPOS) return dataframe::strsimd::NPOS;
141,768 ✔
1065
        if (verify(q)) return q;
116,918 ✔
1066
        lim = q;
51,385 ✔
1067
    }
70,884 ✔
1068
    return dataframe::strsimd::NPOS;
360 ✔
1069
}
430,791 ✔
1070

1071
dftu_series* case_impl(const dftu_series* v, dataframe::strsimd::CaseKind kind,
288 ✔
1072
                       bool capitalize) {
1073
    if (!v || !is_string_kind(v->type)) return nullptr;
288 !
1074
    const bool wide = is_wide_offset_type(v->type);
288 ✔
1075
    auto run = [&](const auto& f) -> dftu_series* {
576 ✔
1076
        auto* out = new dftu_series();
288 ✔
1077
        out->type = wide ? TypeId::LargeString : TypeId::String;
288 ✔
1078
        out->encoding = Encoding::Flat;
288 ✔
1079
        out->length = v->length;
553 ✔
1080
        out->null_count = v->null_count;
288 ✔
1081
        out->validity = v->validity;
288 ✔
1082
        using Off = std::remove_const_t<std::remove_pointer_t<decltype(f.off)>>;
1083
        const std::int64_t base = f.lo();
288 ✔
1084
        const std::size_t data_size =
432 ✔
1085
            v->data.block() ? static_cast<std::size_t>(f.hi() - base) : 0;
432 !
1086
        window_offsets<Off>(*v, *out, base);
288 ✔
1087
        out->data = new_buffer(data_size);
288 !
1088
        if (data_size == 0) return out;
288 ✔
1089
        const std::uint8_t* in = v->data.data() + base;
242 ✔
1090
        std::uint8_t* o = writable(out->data);
242 ✔
1091
        dataframe::strsimd::case_map(
242 ✔
1092
            capitalize ? dataframe::strsimd::CaseKind::Lower : kind, in, o,
242 ✔
1093
            data_size);
121 ✔
1094
        if (capitalize || kind == dataframe::strsimd::CaseKind::Title) {
242 ✔
1095
            // A row's first byte has no previous byte: it is upper-cased when
1096
            // lower, whatever sat before it in the buffer.
1097
            for (std::int64_t i = 0; i < f.n; ++i) {
299,010 ✔
1098
                if (f.len(i) <= 0) continue;
298,808 ✔
1099
                const std::int64_t s = f.off[i] - base;
281,906 ✔
1100
                o[s] = dstd::is_ascii_lower(static_cast<char>(in[s]))
340,967 ✔
1101
                           ? static_cast<std::uint8_t>(in[s] - 32)
200,014 ✔
1102
                           : in[s];
81,892 ✔
1103
            }
140,953 ✔
1104
        }
101 ✔
1105
        return out;
121 ✔
1106
    };
288 ✔
1107
    if (wide) {
288 ✔
1108
        FlatStr<std::int64_t> f(v);
4 ✔
1109
        return f.ok ? run(f) : nullptr;
4 !
1110
    }
2 ✔
1111
    FlatStr<std::int32_t> f(v);
284 ✔
1112
    return f.ok ? run(f) : nullptr;
284 !
1113
}
144 ✔
1114

1115
dftu_series* is_impl(const dftu_series* v, int cls) {
592 ✔
1116
    dataframe::strsimd::BitKind kind = dataframe::strsimd::BitKind::Alnum;
592 ✔
1117
    bool want_aux = false;
592 ✔
1118
    switch (cls) {
592 ✔
1119
        case DFTU_STR_ALNUM:
1120
            kind = dataframe::strsimd::BitKind::Alnum;
26 ✔
1121
            break;
26 ✔
1122
        case DFTU_STR_ALPHA:
82 ✔
1123
            kind = dataframe::strsimd::BitKind::Alpha;
164 ✔
1124
            break;
164 ✔
1125
        case DFTU_STR_DIGIT:
79 ✔
1126
        case DFTU_STR_DECIMAL:
79 ✔
1127
        case DFTU_STR_NUMERIC:
79 ✔
1128
            kind = dataframe::strsimd::BitKind::Digit;
158 ✔
1129
            break;
158 ✔
1130
        case DFTU_STR_SPACE:
26 ✔
1131
            kind = dataframe::strsimd::BitKind::Space;
52 ✔
1132
            break;
52 ✔
1133
        case DFTU_STR_LOWER:
27 ✔
1134
            kind = dataframe::strsimd::BitKind::Lower;
54 ✔
1135
            want_aux = true;
54 ✔
1136
            break;
54 ✔
1137
        case DFTU_STR_UPPER:
28 ✔
1138
            kind = dataframe::strsimd::BitKind::Upper;
56 ✔
1139
            want_aux = true;
56 ✔
1140
            break;
56 ✔
1141
        case DFTU_STR_TITLE:
27 ✔
1142
            kind = dataframe::strsimd::BitKind::Title;
54 ✔
1143
            want_aux = true;
54 ✔
1144
            break;
54 ✔
1145
        default:
1146
            return nullptr;
1 ✔
1147
    }
1148
    const bool title = kind == dataframe::strsimd::BitKind::Title;
590 ✔
1149
    return with_flat(v, [&](const auto& f) -> dftu_series* {
1,122 ✔
1150
        const std::int64_t lo = f.lo();
532 ✔
1151
        const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
532 ✔
1152
        const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
532 !
1153
        // Short strings: one vector pass over the whole buffer, then a bit
1154
        // range per row. Long strings: scan each row and stop at its first
1155
        // bad vector (no bit arrays at all).
1156
        const std::int64_t avg =
798 ✔
1157
            f.n > 0 ? static_cast<std::int64_t>(nbytes) / f.n : 0;
532 ✔
1158
        const dataframe::strsimd::PredStrategy strat =
532 ✔
1159
            dataframe::strsimd::pred_strategy();
532 ✔
1160
        const bool by_rows = strat == dataframe::strsimd::PredStrategy::Rows ||
780 ✔
1161
                             (strat == dataframe::strsimd::PredStrategy::Auto &&
496 !
1162
                              avg >= dataframe::strsimd::PRED_ROWS_MIN_AVG);
478 ✔
1163
        Bits bits;
532 ✔
1164
        if (!by_rows) bits = compute_bits(kind, p, nbytes, 0, want_aux);
681 ✔
1165
        const std::uint64_t* bad = bits.bad.data();
532 ✔
1166
        const std::uint64_t* aux =
798 ✔
1167
            want_aux && !by_rows ? bits.aux.data() : nullptr;
532 ✔
1168

1169
        auto* out = new dftu_series();
532 ✔
1170
        out->type = TypeId::Bool;
532 ✔
1171
        out->encoding = Encoding::Flat;
532 ✔
1172
        out->length = f.n;
532 ✔
1173
        out->null_count = v->null_count;
532 ✔
1174
        out->validity = v->validity;
532 ✔
1175
        const std::size_t bytes = buffer_bytes(TypeId::Bool, f.n);
532 ✔
1176
        out->data = new_buffer(bytes);
532 !
1177
        std::memset(writable(out->data), 0, bytes);
532 ✔
1178
        std::uint8_t* res = writable(out->data);
532 ✔
1179
        auto rows = [&](std::int64_t b, std::int64_t e) {
84,880 ✔
1180
            if (by_rows) {
532 ✔
1181
                dataframe::strsimd::class_rows(kind, f.data, f.off, lo, b, e,
351 ✔
1182
                                               res);
117 ✔
1183
                return;
234 ✔
1184
            }
1185
            for (std::int64_t i = b; i < e; ++i) {
45,854 ✔
1186
                const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
45,556 ✔
1187
                const std::size_t t =
68,334 ✔
1188
                    static_cast<std::size_t>(f.off[i + 1] - lo);
45,556 ✔
1189
                if (s >= t) continue;  // an empty string is in no class
45,556 ✔
1190
                bool yes;
21,914 ✔
1191
                if (title) {
44,094 ✔
1192
                    // The first byte has no previous byte, so it breaks the
1193
                    // rule when lower; the rest read the bit array.
1194
                    yes = !dstd::is_ascii_lower(static_cast<char>(p[s])) &&
7,206 ✔
1195
                          !dataframe::strsimd::bits_any(bad, s + 1, t) &&
4,780 !
1196
                          dataframe::strsimd::bits_any(aux, s, t);
98 !
1197
                } else {
2,426 ✔
1198
                    yes = !dataframe::strsimd::bits_any(bad, s, t) &&
46,324 ✔
1199
                          (aux == nullptr ||
14,696 ✔
1200
                           dataframe::strsimd::bits_any(aux, s, t));
7,318 !
1201
                }
1202
                if (yes)
21,914 !
1203
                    res[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
14,684 ✔
1204
            }
22,778 !
1205
        };
415 ✔
1206
        constexpr std::int64_t ROW_GRAIN = 1 << 15;  // a multiple of 8
532 ✔
1207
        if (f.n > ROW_GRAIN && parallel_backend_installed())
532 !
1208
            parallel_for(f.n, ROW_GRAIN, rows);
×
1209
        else
1210
            rows(0, f.n);
532 ✔
1211
        return out;
532 ✔
1212
    });
532 ✔
1213
}
296 ✔
1214

1215
// Pad / center: `mode` 0 pads the start, 1 the end, 2 centers.
1216
dftu_series* pad_impl(const dftu_series* v, std::int64_t width, char fill,
696 ✔
1217
                      int mode) {
1218
    return map_strings(
1,392 ✔
1219
        v,
348 ✔
1220
        [width](const auto& f, std::int64_t i) {
354,745 ✔
1221
            return std::max<std::int64_t>(f.len(i), width);
354,397 ✔
1222
        },
1223
        [width, fill, mode](const auto& f, std::int64_t i, std::uint8_t* dst) {
667,189 ✔
1224
            const std::int64_t len = f.len(i);
303,926 ✔
1225
            if (len >= width) {
303,926 ✔
1226
                copy_bytes(dst, f.row(i), len);
66,758 ✔
1227
                return;
66,758 ✔
1228
            }
1229
            const std::int64_t gap = width - len;
237,168 ✔
1230
            // CPython's center puts an odd gap's extra fill on the left when
1231
            // the width is odd, else on the right.
1232
            const std::int64_t left = mode == 0   ? gap
351,456 ✔
1233
                                      : mode == 1 ? 0
234,124 ✔
1234
                                                  : gap / 2 + (gap & width & 1);
230,110 ✔
1235
            std::memset(dst, fill, static_cast<std::size_t>(left));
237,168 ✔
1236
            copy_bytes(dst + left, f.row(i), len);
237,168 ✔
1237
            std::memset(dst + left + len, fill,
507,731 ✔
1238
                        static_cast<std::size_t>(gap - left));
237,176 ✔
1239
        });
149,926 !
1240
}
1241

1242
dftu_series* zfill_impl(const dftu_series* v, std::int64_t width) {
222 ✔
1243
    return map_strings(
444 ✔
1244
        v,
111 ✔
1245
        [width](const auto& f, std::int64_t i) {
22,333 ✔
1246
            return std::max<std::int64_t>(f.len(i), width);
22,222 ✔
1247
        },
1248
        [width](const auto& f, std::int64_t i, std::uint8_t* dst) {
22,333 ✔
1249
            const std::int64_t len = f.len(i);
22,222 ✔
1250
            const std::uint8_t* r = f.row(i);
22,222 ✔
1251
            if (len >= width) {
22,222 ✔
1252
                copy_bytes(dst, r, len);
18,692 ✔
1253
                return;
18,692 ✔
1254
            }
1255
            const std::int64_t gap = width - len;
3,530 ✔
1256
            // A leading sign stays first; the zeros go after it.
1257
            const bool sign = len > 0 && (r[0] == '+' || r[0] == '-');
5,193 ✔
1258
            std::int64_t at = 0;
1,765 ✔
1259
            if (sign) dst[at++] = r[0];
1,904 !
1260
            std::memset(dst + at, '0', static_cast<std::size_t>(gap));
3,530 ✔
1261
            at += gap;
3,530 ✔
1262
            copy_bytes(dst + at, r + (sign ? 1 : 0), len - (sign ? 1 : 0));
6,782 ✔
1263
        });
11,222 !
1264
}
1265

1266
dftu_series* remove_affix_impl(const dftu_series* v,
418 ✔
1267
                               dftracer::utils::dstd::StringView a,
1268
                               bool prefix) {
1269
    const auto plen = static_cast<std::int64_t>(a.size());
418 ✔
1270
    auto cut = [a, plen, prefix](const auto& f,
75,262 ✔
1271
                                 std::int64_t i) -> std::int64_t {
67,166 ✔
1272
        const std::int64_t len = f.len(i);
74,844 ✔
1273
        if (plen == 0 || len < plen) return 0;
74,844 !
1274
        const std::uint8_t* at = f.row(i) + (prefix ? 0 : len - plen);
59,488 ✔
1275
        return std::memcmp(at, a.data(), static_cast<std::size_t>(plen)) == 0
59,488 ✔
1276
                   ? plen
30,248 ✔
1277
                   : 0;
1278
    };
37,631 ✔
1279
    return map_strings(
1,045 ✔
1280
        v,
209 ✔
1281
        [&cut](const auto& f, std::int64_t i) { return f.len(i) - cut(f, i); },
37,631 ✔
1282
        [&cut, prefix](const auto& f, std::int64_t i, std::uint8_t* dst) {
37,631 ✔
1283
            const std::int64_t c = cut(f, i);
37,422 ✔
1284
            copy_bytes(dst, f.row(i) + (prefix ? c : 0), f.len(i) - c);
37,422 ✔
1285
        });
37,631 ✔
1286
}
209 ✔
1287

1288
dftu_series* repeat_impl(const dftu_series* v, std::int64_t n) {
164 ✔
1289
    return map_strings(
328 ✔
1290
        v,
82 ✔
1291
        [n](const auto& f, std::int64_t i) {
15,120 ✔
1292
            std::int64_t total;
7,519 ✔
1293
            if (dstd::bits::mul_overflow(f.len(i), n, &total))
15,038 ✔
1294
                return std::numeric_limits<std::int64_t>::max();
1295
            return total;
15,038 ✔
1296
        },
7,519 ✔
1297
        [n](const auto& f, std::int64_t i, std::uint8_t* dst) {
15,118 ✔
1298
            const std::int64_t len = f.len(i);
15,036 ✔
1299
            const std::int64_t total = len * n;
15,036 ✔
1300
            if (total == 0) return;
15,036 ✔
1301
            copy_bytes(dst, f.row(i), len);
11,268 ✔
1302
            // Double the filled prefix until the row is full.
1303
            std::int64_t filled = len;
11,268 ✔
1304
            while (filled < total) {
26,098 ✔
1305
                const std::int64_t c = std::min(filled, total - filled);
14,830 ✔
1306
                std::memcpy(dst + filled, dst, static_cast<std::size_t>(c));
14,830 ✔
1307
                filled += c;
14,830 ✔
1308
            }
7,415 ✔
1309
        });
7,600 !
1310
}
1311

1312
dftu_series* slice_impl(const dftu_series* v, std::int64_t start,
434 ✔
1313
                        std::int64_t length) {
1314
    // The byte range of a row: a negative start counts from the end, a
1315
    // negative length runs to the end (polars slice with no length).
1316
    auto range = [start, length](std::int64_t len) {
114,182 ✔
1317
        std::int64_t b = start < 0 ? start + len : start;
75,832 ✔
1318
        b = std::clamp<std::int64_t>(b, 0, len);
75,832 ✔
1319
        std::int64_t e = length < 0 ? len : b + length;
75,832 ✔
1320
        e = std::clamp<std::int64_t>(e, b, len);
75,832 !
1321
        return dftracer::utils::dstd::Pair<std::int64_t, std::int64_t>(b, e);
75,832 ✔
1322
    };
38,133 ✔
1323
    return map_strings(
1,085 ✔
1324
        v,
217 ✔
1325
        [&range](const auto& f, std::int64_t i) {
38,133 ✔
1326
            const auto [b, e] = range(f.len(i));
37,916 ✔
1327
            return e - b;
56,874 ✔
1328
        },
18,958 ✔
1329
        [&range](const auto& f, std::int64_t i, std::uint8_t* dst) {
38,133 ✔
1330
            const auto [b, e] = range(f.len(i));
37,916 ✔
1331
            copy_bytes(dst, f.row(i) + b, e - b);
37,916 ✔
1332
        });
38,133 ✔
1333
}
217 ✔
1334

1335
template <class OffA, class OffB>
1336
dftu_series* cat_impl(const dftu_series* a, const dftu_series* b) {
1,348 ✔
1337
    FlatStr<OffA> fa(a);
1,348 ✔
1338
    FlatStr<OffB> fb(b);
1,348 ✔
1339
    if (!fa.ok || !fb.ok) return nullptr;
1,348 !
1340
    dftu_series* out = build_flat_string(
4,044 ✔
1341
        fa.n, [&](std::int64_t i) { return fa.is_null(i) || fb.is_null(i); },
135,908 !
1342
        [&](std::int64_t i) { return fa.len(i) + fb.len(i); },
63,500 ✔
1343
        [&](std::int64_t i, std::uint8_t* dst) {
126,326 ✔
1344
            copy_bytes(dst, fa.row(i), fa.len(i));
62,826 ✔
1345
            copy_bytes(dst + fa.len(i), fb.row(i), fb.len(i));
62,826 ✔
1346
        });
31,413 ✔
1347
    if (!out) return nullptr;
1,348 !
1348
    if (fa.validity == nullptr && fb.validity == nullptr) return out;
1,348 !
1349
    // A null on either side is null: the validity is the two ANDed.
1350
    const std::size_t vbytes = buffer_bytes(TypeId::Bool, fa.n);
582 ✔
1351
    auto valid = new_buffer(vbytes);
582 ✔
1352
    std::int64_t valid_rows = 0;
582 ✔
1353
    for (std::size_t k = 0; k < vbytes; ++k) {
5,530 !
1354
        std::uint8_t w =
7,422 ✔
1355
            static_cast<std::uint8_t>((fa.validity ? fa.validity[k] : 0xFF) &
7,422 !
1356
                                      (fb.validity ? fb.validity[k] : 0xFF));
4,948 !
1357
        const std::int64_t rows_here =
7,422 ✔
1358
            std::min<std::int64_t>(8, fa.n - static_cast<std::int64_t>(k) * 8);
4,948 ✔
1359
        if (rows_here < 8)
4,948 !
1360
            w &= static_cast<std::uint8_t>((1u << rows_here) - 1);
494 ✔
1361
        writable(valid)[k] = w;
4,948 ✔
1362
        valid_rows += dstd::bits::popcount_u64(w);
4,948 ✔
1363
    }
2,474 ✔
1364
    out->null_count = fa.n - valid_rows;
582 ✔
1365
    out->validity = out->null_count != 0 ? std::move(valid) : BufferView{};
646 !
1366
    return out;
582 ✔
1367
}
1,348 ✔
1368

1369
template <class ChildOff>
1370
dftu_series* join_impl(const dftu_series* v, const dftu_series& child,
272 ✔
1371
                       dftracer::utils::dstd::StringView sep) {
1372
    FlatStr<ChildOff> c(&child);
272 ✔
1373
    if (!c.ok) return nullptr;
272 !
1374
    const std::int32_t* off = dftu_series_offsets(v);
272 ✔
1375
    const auto sl = static_cast<std::int64_t>(sep.size());
272 ✔
1376
    auto is_null = [&](std::int64_t i) {
97,412 ✔
1377
        return v->validity.block() &&
145,580 !
1378
               !((v->validity.data()[i >> 3] >> (i & 7)) & 1);
96,880 !
1379
    };
1380
    dftu_series* out = build_flat_string(
952 ✔
1381
        v->length, is_null,
408 ✔
1382
        [&](std::int64_t i) {
59,668 ✔
1383
            const std::int64_t cnt = off[i + 1] - off[i];
39,690 ✔
1384
            const std::int64_t bytes =
59,535 ✔
1385
                static_cast<std::int64_t>(c.off[off[i + 1]]) - c.off[off[i]];
39,690 ✔
1386
            return bytes + (cnt > 0 ? (cnt - 1) * sl : 0);
39,690 ✔
1387
        },
19,845 ✔
1388
        [&](std::int64_t i, std::uint8_t* dst) {
236,334 ✔
1389
            const std::int64_t cnt = off[i + 1] - off[i];
39,690 ✔
1390
            if (cnt == 0) return;
39,690 ✔
1391
            if (sl == 0 || cnt == 1) {
39,684 ✔
1392
                // The elements are back to back: one copy.
1393
                copy_bytes(dst, c.data + c.off[off[i]],
48,054 ✔
1394
                           static_cast<std::int64_t>(c.off[off[i + 1]]) -
48,054 ✔
1395
                               c.off[off[i]]);
32,036 ✔
1396
                return;
32,036 ✔
1397
            }
1398
            for (std::int32_t k = off[i]; k < off[i + 1]; ++k) {
87,972 ✔
1399
                if (k != off[i]) {
80,324 ✔
1400
                    std::memcpy(dst, sep.data(), static_cast<std::size_t>(sl));
72,676 ✔
1401
                    dst += sl;
72,676 ✔
1402
                }
36,338 ✔
1403
                copy_bytes(dst, c.row(k), c.len(k));
80,324 ✔
1404
                dst += c.len(k);
80,324 ✔
1405
            }
40,162 ✔
1406
        });
19,845 !
1407
    share_nulls(out, v);
272 ✔
1408
    return out;
272 ✔
1409
}
136 ✔
1410

1411
template <class F>
1412
dftu_series* split_impl(const dftu_series* v, const F& f,
304 ✔
1413
                        dftracer::utils::dstd::StringView sep) {
1414
    const std::int64_t n = f.n;
304 ✔
1415
    const std::int64_t lo = f.lo();
304 ✔
1416
    const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
304 ✔
1417
    const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
304 !
1418
    const std::size_t sl = sep.size();
304 ✔
1419
    Bits cand;
304 ✔
1420
    if (sl != 0)
304 ✔
1421
        cand = compute_bits(dataframe::strsimd::BitKind::Eq, p, nbytes,
560 ✔
1422
                            static_cast<std::uint8_t>(sep[0]), false);
280 ✔
1423

1424
    // Pass 1: where the separator occurs in each row, the part counts and
1425
    // the bytes the parts hold.
1426
    dftracer::utils::dstd::Vector<std::size_t> hits;
304 ✔
1427
    dftracer::utils::dstd::Vector<std::int32_t> list_off(
608 ✔
1428
        static_cast<std::size_t>(n + 1), 0);
304 ✔
1429
    std::int64_t parts = 0, bytes = 0;
304 ✔
1430
    for (std::int64_t i = 0; i < n; ++i) {
315,487 !
1431
        if (!f.is_null(i)) {
315,183 ✔
1432
            const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
308,977 ✔
1433
            const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
308,977 ✔
1434
            const std::size_t before = hits.size();
308,977 ✔
1435
            std::size_t pos = s;
308,977 ✔
1436
            while (sl != 0 && pos < e) {
860,501 !
1437
                const std::size_t q =
1,205,274 ✔
1438
                    find_sep(cand.bad.data(), p, pos, e, sep, false);
803,305 ✔
1439
                if (q == dataframe::strsimd::NPOS) break;
803,338 ✔
1440
                hits.push_back(q);
551,645 ✔
1441
                pos = q + sl;
551,612 ✔
1442
            }
401,936 !
1443
            const std::int64_t h =
463,546 ✔
1444
                static_cast<std::int64_t>(hits.size() - before);
308,977 ✔
1445
            parts += h + 1;
308,977 ✔
1446
            bytes += static_cast<std::int64_t>(e - s) -
463,546 ✔
1447
                     h * static_cast<std::int64_t>(sl);
308,977 ✔
1448
            if (parts > std::numeric_limits<std::int32_t>::max())
308,977 !
1449
                return nullptr;
1450
        }
154,569 !
1451
        list_off[static_cast<std::size_t>(i + 1)] =
315,183 ✔
1452
            static_cast<std::int32_t>(parts);
157,657 ✔
1453
    }
157,657 ✔
1454
    if (bytes > std::numeric_limits<std::int32_t>::max()) return nullptr;
304 !
1455

1456
    // Pass 2: copy the parts.
1457
    auto coff =
304 ✔
1458
        new_buffer(static_cast<std::size_t>(parts + 1) * sizeof(std::int32_t));
304 ✔
1459
    auto cdata = new_buffer(static_cast<std::size_t>(bytes));
304 ✔
1460
    auto* co = reinterpret_cast<std::int32_t*>(writable(coff));
304 ✔
1461
    std::uint8_t* cd = writable(cdata);
304 ✔
1462
    std::int64_t at = 0, k = 0;
304 ✔
1463
    co[0] = 0;
304 ✔
1464
    std::size_t h = 0;
304 ✔
1465
    for (std::int64_t i = 0; i < n; ++i) {
316,472 ✔
1466
        if (f.is_null(i)) continue;
316,168 ✔
1467
        const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
309,988 ✔
1468
        std::size_t start = static_cast<std::size_t>(f.off[i] - lo);
309,988 ✔
1469
        auto emit = [&](std::size_t from, std::size_t to) {
1,605,064 ✔
1470
            copy_bytes(cd + at, p + from, static_cast<std::int64_t>(to - from));
863,384 ✔
1471
            at += static_cast<std::int64_t>(to - from);
863,384 ✔
1472
            co[++k] = static_cast<std::int32_t>(at);
863,384 ✔
1473
        };
431,692 ✔
1474
        while (h < hits.size() && hits[h] < e) {
863,384 ✔
1475
            emit(start, hits[h]);
553,396 ✔
1476
            start = hits[h] + sl;
553,396 ✔
1477
            ++h;
553,396 ✔
1478
        }
1479
        emit(start, e);
309,988 ✔
1480
    }
154,994 ✔
1481
    return make_str_list(v, list_off, parts, std::move(coff), std::move(cdata));
304 !
1482
}
456 !
1483

1484
template <class F>
1485
dftu_series* partition_impl(const dftu_series* v, const F& f,
284 ✔
1486
                            dftracer::utils::dstd::StringView sep, bool right) {
1487
    const std::int64_t n = f.n;
284 ✔
1488
    const std::int64_t lo = f.lo();
284 ✔
1489
    const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
284 ✔
1490
    const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
284 !
1491
    const std::size_t sl = sep.size();
284 ✔
1492
    const Bits cand = compute_bits(dataframe::strsimd::BitKind::Eq, p, nbytes,
426 ✔
1493
                                   static_cast<std::uint8_t>(sep[0]), false);
284 ✔
1494
    dftracer::utils::dstd::Vector<std::size_t> at(static_cast<std::size_t>(n),
284 ✔
1495
                                                  dataframe::strsimd::NPOS);
1496
    dftracer::utils::dstd::Vector<std::int32_t> list_off(
568 ✔
1497
        static_cast<std::size_t>(n + 1), 0);
284 ✔
1498
    std::int64_t parts = 0, bytes = 0;
284 ✔
1499
    for (std::int64_t i = 0; i < n; ++i) {
44,642 !
1500
        if (!f.is_null(i)) {
44,358 ✔
1501
            const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
36,462 ✔
1502
            const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
36,462 ✔
1503
            at[static_cast<std::size_t>(i)] =
36,462 !
1504
                find_sep(cand.bad.data(), p, s, e, sep, right);
36,462 ✔
1505
            parts += 3;
36,462 ✔
1506
            bytes += static_cast<std::int64_t>(e - s);
36,462 ✔
1507
            if (parts > std::numeric_limits<std::int32_t>::max())
36,462 !
1508
                return nullptr;
1509
        }
18,231 !
1510
        list_off[static_cast<std::size_t>(i + 1)] =
44,358 ✔
1511
            static_cast<std::int32_t>(parts);
22,179 ✔
1512
    }
22,179 ✔
1513
    if (bytes > std::numeric_limits<std::int32_t>::max()) return nullptr;
284 !
1514
    auto coff =
284 ✔
1515
        new_buffer(static_cast<std::size_t>(parts + 1) * sizeof(std::int32_t));
284 ✔
1516
    auto cdata = new_buffer(static_cast<std::size_t>(bytes));
284 ✔
1517
    auto* co = reinterpret_cast<std::int32_t*>(writable(coff));
284 ✔
1518
    std::uint8_t* cd = writable(cdata);
284 ✔
1519
    std::int64_t w = 0, k = 0;
284 ✔
1520
    co[0] = 0;
284 ✔
1521
    auto put = [&](const std::uint8_t* src, std::int64_t len) {
164,363 ✔
1522
        copy_bytes(cd + w, src, len);
109,386 ✔
1523
        w += len;
109,386 ✔
1524
        co[++k] = static_cast<std::int32_t>(w);
109,386 ✔
1525
    };
54,693 ✔
1526
    for (std::int64_t i = 0; i < n; ++i) {
44,642 ✔
1527
        if (f.is_null(i)) continue;
44,358 ✔
1528
        const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
36,462 ✔
1529
        const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
36,462 ✔
1530
        const std::size_t q = at[static_cast<std::size_t>(i)];
36,462 ✔
1531
        if (q == dataframe::strsimd::NPOS) {
36,462 ✔
1532
            // Python: (row, "", "") for partition, ("", "", row) for
1533
            // rpartition.
1534
            if (!right) {
23,184 ✔
1535
                put(p + s, static_cast<std::int64_t>(e - s));
10,536 ✔
1536
                put(p, 0);
10,536 ✔
1537
                put(p, 0);
10,536 ✔
1538
            } else {
5,268 ✔
1539
                put(p, 0);
12,648 ✔
1540
                put(p, 0);
12,648 ✔
1541
                put(p + s, static_cast<std::int64_t>(e - s));
12,648 ✔
1542
            }
1543
            continue;
23,184 ✔
1544
        }
1545
        put(p + s, static_cast<std::int64_t>(q - s));
13,278 ✔
1546
        put(p + q, static_cast<std::int64_t>(sl));
13,278 ✔
1547
        put(p + q + sl, static_cast<std::int64_t>(e - q - sl));
13,278 ✔
1548
    }
18,231 !
1549
    return make_str_list(v, list_off, parts, std::move(coff), std::move(cdata));
284 !
1550
}
426 !
1551

1552
template <class F>
1553
dftu_series* rfind_impl(const dftu_series* v, const F& f,
236 ✔
1554
                        dftracer::utils::dstd::StringView needle) {
1555
    const std::int64_t lo = f.lo();
236 ✔
1556
    const std::size_t nbytes = static_cast<std::size_t>(f.hi() - lo);
236 ✔
1557
    const std::uint8_t* p = f.data != nullptr ? f.data + lo : nullptr;
236 !
1558
    Bits cand;
236 ✔
1559
    if (!needle.empty())
236 ✔
1560
        cand = compute_bits(dataframe::strsimd::BitKind::Eq, p, nbytes,
424 ✔
1561
                            static_cast<std::uint8_t>(needle[0]), false);
212 ✔
1562
    auto* out = new dftu_series();
236 ✔
1563
    out->type = TypeId::Int64;
236 ✔
1564
    out->encoding = Encoding::Flat;
236 ✔
1565
    out->length = f.n;
236 ✔
1566
    out->null_count = v->null_count;
236 ✔
1567
    out->validity = v->validity;
236 ✔
1568
    out->data = new_buffer(buffer_bytes(TypeId::Int64, f.n));
236 !
1569
    auto* r = reinterpret_cast<std::int64_t*>(writable(out->data));
236 ✔
1570
    for (std::int64_t i = 0; i < f.n; ++i) {
31,404 ✔
1571
        if (f.is_null(i)) {
31,168 ✔
1572
            r[i] = 0;
5,634 ✔
1573
            continue;
5,634 ✔
1574
        }
1575
        const std::size_t s = static_cast<std::size_t>(f.off[i] - lo);
25,534 ✔
1576
        const std::size_t e = static_cast<std::size_t>(f.off[i + 1] - lo);
25,534 ✔
1577
        if (needle.empty()) {
25,534 ✔
1578
            r[i] = static_cast<std::int64_t>(e - s);
3,592 ✔
1579
            continue;
3,592 ✔
1580
        }
1581
        const std::size_t q = find_sep(cand.bad.data(), p, s, e, needle, true);
21,942 ✔
1582
        r[i] = q == dataframe::strsimd::NPOS ? -1
26,198 ✔
1583
                                             : static_cast<std::int64_t>(q - s);
8,512 ✔
1584
    }
12,767 !
1585
    return out;
236 ✔
1586
}
236 ✔
1587

1588
std::int64_t count_literal(dftracer::utils::dstd::StringView s,
1,698 ✔
1589
                           dftracer::utils::dstd::StringView pat) {
1590
    if (pat.empty()) return static_cast<std::int64_t>(s.size()) + 1;
1,698 ✔
1591
    std::int64_t n = 0;
837 ✔
1592
    std::size_t pos = 0;
837 ✔
1593
    while (true) {
5,175 ✔
1594
        const std::size_t hit = s.find(pat, pos);
4,008 ✔
1595
        if (hit == dftracer::utils::dstd::StringView::npos) break;
4,008 ✔
1596
        ++n;
2,334 ✔
1597
        pos = hit + pat.size();
2,334 ✔
1598
    }
3,171 !
1599
    return n;
837 ✔
1600
}
849 ✔
1601

1602
}  // namespace
1603

1604
dftu_series* dftu_series_str_slice(const dftu_series* v, std::int64_t start,
514 ✔
1605
                                   std::int64_t length) {
1606
    if (!v || !is_string_kind(v->type)) return nullptr;
514 !
1607
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_slice, start, length);
458 !
1608
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_slice(flat_v, start, length));
450 !
1609
    return slice_impl(v, start, length);
434 ✔
1610
}
257 ✔
1611

1612
dftu_series* dftu_series_str_pad_start(const dftu_series* v, std::int64_t width,
324 ✔
1613
                                       char fill) {
1614
    if (!v || !is_string_kind(v->type)) return nullptr;
324 !
1615
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_pad_start, width, fill);
264 !
1616
    DFTU_FLAT_OPERAND(v, flat_v,
256 !
1617
                      dftu_series_str_pad_start(flat_v, width, fill));
1618
    return pad_impl(v, width, fill, 0);
240 ✔
1619
}
162 ✔
1620
dftu_series* dftu_series_str_pad_end(const dftu_series* v, std::int64_t width,
318 ✔
1621
                                     char fill) {
1622
    if (!v || !is_string_kind(v->type)) return nullptr;
318 !
1623
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_pad_end, width, fill);
262 !
1624
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_pad_end(flat_v, width, fill));
254 !
1625
    return pad_impl(v, width, fill, 1);
238 ✔
1626
}
159 ✔
1627
dftu_series* dftu_series_str_center(const dftu_series* v, std::int64_t width,
298 ✔
1628
                                    char fill) {
1629
    if (!v || !is_string_kind(v->type)) return nullptr;
298 !
1630
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_center, width, fill);
242 !
1631
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_center(flat_v, width, fill));
234 !
1632
    return pad_impl(v, width, fill, 2);
218 ✔
1633
}
149 ✔
1634
dftu_series* dftu_series_str_zfill(const dftu_series* v, std::int64_t width) {
302 ✔
1635
    if (!v || !is_string_kind(v->type)) return nullptr;
302 !
1636
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_zfill, width);
246 !
1637
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_zfill(flat_v, width));
238 !
1638
    return zfill_impl(v, width);
222 ✔
1639
}
151 ✔
1640

1641
dftu_series* dftu_series_str_split(const dftu_series* v, const char* sep,
372 ✔
1642
                                   std::int32_t sep_size) {
1643
    if (!v || !is_string_kind(v->type)) return nullptr;
372 !
1644
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_split(flat_v, sep, sep_size));
316 !
1645
    // An empty separator is no split point: one part, the whole row.
1646
    const dftracer::utils::dstd::StringView s_sep(
456 ✔
1647
        sep, static_cast<std::size_t>(sep_size));
304 ✔
1648
    return with_flat(v, [&](const auto& f) { return split_impl(v, f, s_sep); });
608 ✔
1649
}
186 ✔
1650

1651
dftu_series* dftu_series_str_partition(const dftu_series* v, const char* sep,
352 ✔
1652
                                       std::int32_t sep_size,
1653
                                       std::int32_t from_right) {
1654
    if (!v || !is_string_kind(v->type) || sep_size <= 0) return nullptr;
352 !
1655
    DFTU_FLAT_OPERAND(
296 !
1656
        v, flat_v,
1657
        dftu_series_str_partition(flat_v, sep, sep_size, from_right));
1658
    const dftracer::utils::dstd::StringView s_sep(
426 ✔
1659
        sep, static_cast<std::size_t>(sep_size));
284 ✔
1660
    return with_flat(v, [&](const auto& f) {
568 ✔
1661
        return partition_impl(v, f, s_sep, from_right != 0);
284 ✔
1662
    });
1663
}
176 ✔
1664

1665
dftu_series* dftu_series_str_rfind(const dftu_series* v, const char* needle,
304 ✔
1666
                                   std::int32_t needle_size) {
1667
    if (!v || !is_string_kind(v->type)) return nullptr;
304 !
1668
    DFTU_FLAT_OPERAND(v, flat_v,
248 !
1669
                      dftu_series_str_rfind(flat_v, needle, needle_size));
1670
    const dftracer::utils::dstd::StringView n(
354 ✔
1671
        needle, static_cast<std::size_t>(needle_size));
236 ✔
1672
    return with_flat(v, [&](const auto& f) { return rfind_impl(v, f, n); });
472 ✔
1673
}
152 ✔
1674

1675
dftu_series* dftu_series_str_case(const dftu_series* v, std::int32_t op) {
374 ✔
1676
    if (!v || !is_string_kind(v->type)) return nullptr;
374 !
1677
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_case, op);
316 !
1678
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_case(flat_v, op));
306 !
1679
    switch (static_cast<dftu_str_case>(op)) {
290 ✔
1680
        case DFTU_STR_CAPITALIZE:
45 ✔
1681
            return case_impl(v, dataframe::strsimd::CaseKind::Lower, true);
90 ✔
1682
        case DFTU_STR_TITLE_CASE:
73 ✔
1683
            return case_impl(v, dataframe::strsimd::CaseKind::Title, false);
146 ✔
1684
        case DFTU_STR_SWAPCASE:
26 ✔
1685
            return case_impl(v, dataframe::strsimd::CaseKind::Swapcase, false);
52 ✔
1686
    }
1687
    return nullptr;
1 ✔
1688
}
187 ✔
1689

1690
dftu_series* dftu_series_str_is(const dftu_series* v, std::int32_t cls) {
620 ✔
1691
    if (!v) return nullptr;
620 !
1692
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_is(flat_v, cls));
620 !
1693
    return is_impl(v, cls);
592 ✔
1694
}
310 ✔
1695

1696
dftu_series* dftu_series_str_count(const dftu_series* v, const char* pat,
168 ✔
1697
                                   std::int32_t pat_size) {
1698
    if (!v || !is_string_kind(v->type)) return nullptr;
168 !
1699
    dftracer::utils::dstd::StringView p(pat,
156 ✔
1700
                                        static_cast<std::size_t>(pat_size));
104 ✔
1701
    return string_int64(v, [p](dftracer::utils::dstd::StringView s) {
953 ✔
1702
        return count_literal(s, p);
1,698 ✔
1703
    });
52 ✔
1704
}
84 ✔
1705

1706
dftu_series* dftu_series_str_remove_prefix(const dftu_series* v,
296 ✔
1707
                                           const char* prefix,
1708
                                           std::int32_t len) {
1709
    if (!v || !is_string_kind(v->type)) return nullptr;
296 !
1710
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_remove_prefix, prefix, len);
236 !
1711
    DFTU_FLAT_OPERAND(v, flat_v,
228 !
1712
                      dftu_series_str_remove_prefix(flat_v, prefix, len));
1713
    return remove_affix_impl(v,
318 ✔
1714
                             dftracer::utils::dstd::StringView(
106 ✔
1715
                                 prefix, static_cast<std::size_t>(len)),
106 ✔
1716
                             true);
1717
}
148 ✔
1718

1719
dftu_series* dftu_series_str_remove_suffix(const dftu_series* v,
286 ✔
1720
                                           const char* suffix,
1721
                                           std::int32_t len) {
1722
    if (!v || !is_string_kind(v->type)) return nullptr;
286 !
1723
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_remove_suffix, suffix, len);
230 !
1724
    DFTU_FLAT_OPERAND(v, flat_v,
222 !
1725
                      dftu_series_str_remove_suffix(flat_v, suffix, len));
1726
    return remove_affix_impl(v,
309 ✔
1727
                             dftracer::utils::dstd::StringView(
103 ✔
1728
                                 suffix, static_cast<std::size_t>(len)),
103 ✔
1729
                             false);
1730
}
143 ✔
1731

1732
dftu_series* dftu_series_str_repeat(const dftu_series* v, std::int64_t n) {
248 ✔
1733
    if (!v || !is_string_kind(v->type) || n < 0) return nullptr;
248 !
1734
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_repeat, n);
188 !
1735
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_repeat(flat_v, n));
180 !
1736
    return repeat_impl(v, n);
164 ✔
1737
}
124 ✔
1738

1739
dftu_series* dftu_series_str_cat(const dftu_series* a, const dftu_series* b) {
1,462 ✔
1740
    if (!a || !b) return nullptr;
1,462 !
1741
    DFTU_FLAT_OPERAND(a, flat_a, dftu_series_str_cat(flat_a, b));
1,462 !
1742
    DFTU_FLAT_OPERAND(b, flat_b, dftu_series_str_cat(a, flat_b));
1,434 !
1743
    if (!is_string_kind(a->type) || !is_string_kind(b->type) ||
1,406 !
1744
        a->length != b->length)
1,350 ✔
1745
        return nullptr;
29 ✔
1746
    const bool wa = is_wide_offset_type(a->type);
1,348 !
1747
    const bool wb = is_wide_offset_type(b->type);
1,348 ✔
1748
    if (wa && wb) return cat_impl<std::int64_t, std::int64_t>(a, b);
1,348 !
1749
    if (wa) return cat_impl<std::int64_t, std::int32_t>(a, b);
1,348 !
1750
    if (wb) return cat_impl<std::int32_t, std::int64_t>(a, b);
1,348 !
1751
    return cat_impl<std::int32_t, std::int32_t>(a, b);
1,348 ✔
1752
}
731 ✔
1753

1754
namespace dftracer::utils::dataframe {
1755

1756
Series str_affix(const Series& v, dstd::StringView piece, bool before) {
4 ✔
1757
    const Series flat = v.is_flat() ? v.share() : v.materialize();
4 !
1758
    const auto size = static_cast<std::int64_t>(piece.size());
4 ✔
1759
    const auto* bytes = reinterpret_cast<const std::uint8_t*>(piece.data());
4 ✔
1760
    return Series{map_strings(
8 ✔
1761
        flat.handle(),
4 ✔
1762
        [size](const auto& f, std::int64_t i) { return f.len(i) + size; },
10 ✔
1763
        [&](const auto& f, std::int64_t i, std::uint8_t* dst) {
10 ✔
1764
            if (before) {
8 ✔
1765
                copy_bytes(dst, bytes, size);
4 ✔
1766
                copy_bytes(dst + size, f.row(i), f.len(i));
4 ✔
1767
            } else {
2 ✔
1768
                copy_bytes(dst, f.row(i), f.len(i));
4 ✔
1769
                copy_bytes(dst + f.len(i), bytes, size);
4 ✔
1770
            }
1771
        })};
10 !
1772
}
4 ✔
1773

1774
}  // namespace dftracer::utils::dataframe
1775

1776
dftu_series* dftu_series_list_join(const dftu_series* v, const char* sep,
398 ✔
1777
                                   std::int32_t sep_size) {
1778
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_list_join(flat_v, sep, sep_size));
398 !
1779
    DFTU_LIST_OPERAND(v, narrow, dftu_series_list_join(narrow, sep, sep_size));
370 !
1780
    if (!v || v->type != TypeId::List || v->encoding != Encoding::Flat)
368 !
1781
        return nullptr;
48 ✔
1782
    if (!dftu_series_offsets(v) || !v->child() ||
408 !
1783
        !is_string_kind(v->child()->type))
272 !
1784
        return nullptr;
×
1785
    // A string_view, dictionary or sliced child has no flat offsets to join
1786
    // from, so it is materialized first.
1787
    dftu_series* flat_child = v->child()->encoding == Encoding::Flat
272 ✔
1788
                                  ? nullptr
136 ✔
1789
                                  : dftu_series_materialize(v->child().get());
4 ✔
1790
    if (v->child()->encoding != Encoding::Flat && !flat_child) return nullptr;
272 !
1791
    const dftu_series& child = flat_child ? *flat_child : *v->child();
272 ✔
1792
    const dftracer::utils::dstd::StringView s(
408 ✔
1793
        sep, static_cast<std::size_t>(sep_size));
272 !
1794
    dftu_series* out = is_wide_offset_type(child.type)
272 !
1795
                           ? join_impl<std::int64_t>(v, child, s)
136 !
1796
                           : join_impl<std::int32_t>(v, child, s);
272 ✔
1797
    if (flat_child) dftu_series_free(flat_child);
272 ✔
1798
    return out;
136 ✔
1799
}
199 ✔
1800

1801
dftu_series* dftu_series_str_findall(const dftu_series* v, const char* pattern,
136 ✔
1802
                                     std::int32_t pattern_size) {
1803
    if (!v || !is_string_kind(v->type)) return nullptr;
136 !
1804
    DFTU_FLAT_OPERAND(v, flat_v,
80 !
1805
                      dftu_series_str_findall(flat_v, pattern, pattern_size));
1806
    const auto re = compiled(duql::compile_regex(
102 ✔
1807
        dftracer::utils::dstd::StringView(
34 ✔
1808
            pattern, static_cast<std::size_t>(pattern_size)),
34 ✔
1809
        false));
34 ✔
1810
    if (!re) return nullptr;
68 ✔
1811
    dataframe::kernels::LimitedRows limited;
64 ✔
1812
    dftu_series* out = list_transform(
128 ✔
1813
        v, [&](dftracer::utils::dstd::StringView row,
3,974 ✔
1814
               dftracer::utils::dstd::Vector<dftracer::utils::dstd::String>&
1815
                   parts) {
1816
            const auto r = duql::findall(
7,820 ✔
1817
                *re, row, [&](dftracer::utils::dstd::StringView m) {
33,634 ✔
1818
                    parts.emplace_back(m);
27,769 ✔
1819
                });
27,769 ✔
1820
            if (r == duql::MatchResult::Limit) limited.add(row);
3,910 ✔
1821
        });
3,910 ✔
1822
    return limited.apply(out, v);
64 ✔
1823
}
102 ✔
1824

1825
// Unicode text ops over UTF-8 rows: normalize, translate and wrap. A row that
1826
// is not valid UTF-8 is null in the output.
1827
namespace {
1828

1829
// The bytes of the codepoint at p (0 when it is not valid UTF-8: a stray or
1830
// truncated sequence, an overlong form, a surrogate or past U+10FFFF), and the
1831
// codepoint in `cp`.
1832
std::size_t utf8_next(const std::uint8_t* p, const std::uint8_t* end,
11,170 ✔
1833
                      std::uint32_t& cp) {
1834
    std::uint32_t c = *p;
11,170 ✔
1835
    if (c < 0x80) {
11,170 ✔
1836
        cp = c;
10,762 ✔
1837
        return 1;
10,762 ✔
1838
    }
1839
    std::size_t extra;
408 ✔
1840
    std::uint32_t least;
408 ✔
1841
    if (c >= 0xC2 && c <= 0xDF) {
408 ✔
1842
        extra = 1;
226 ✔
1843
        least = 0x80;
226 ✔
1844
        c &= 0x1F;
226 ✔
1845
    } else if ((c & 0xF0) == 0xE0) {
295 ✔
1846
        extra = 2;
74 ✔
1847
        least = 0x800;
74 ✔
1848
        c &= 0x0F;
74 ✔
1849
    } else if (c >= 0xF0 && c <= 0xF4) {
145 ✔
1850
        extra = 3;
82 ✔
1851
        least = 0x10000;
82 ✔
1852
        c &= 0x07;
82 ✔
1853
    } else {
41 ✔
1854
        return 0;
13 ✔
1855
    }
1856
    if (static_cast<std::size_t>(end - p) <= extra) return 0;
382 ✔
1857
    for (std::size_t k = 1; k <= extra; ++k) {
1,002 !
1858
        if ((p[k] & 0xC0) != 0x80) return 0;
620 ✔
1859
        c = (c << 6) | (p[k] & 0x3F);
620 ✔
1860
    }
310 ✔
1861
    if (c < least || c > 0x10FFFF || (c >= 0xD800 && c <= 0xDFFF)) return 0;
382 !
1862
    cp = c;
382 ✔
1863
    return extra + 1;
382 ✔
1864
}
5,585 ✔
1865

1866
bool decode_utf8(dftracer::utils::dstd::StringView s,
1,086 ✔
1867
                 dftracer::utils::dstd::Vector<std::uint32_t>& out) {
1868
    out.clear();
1,086 ✔
1869
    const auto* p = reinterpret_cast<const std::uint8_t*>(s.data());
1,086 ✔
1870
    const auto* end = p + s.size();
1,086 ✔
1871
    while (p < end) {
6,404 ✔
1872
        std::uint32_t cp;
5,332 ✔
1873
        const std::size_t n = utf8_next(p, end, cp);
5,332 ✔
1874
        if (n == 0) return false;
5,332 ✔
1875
        out.push_back(cp);
5,318 ✔
1876
        p += n;
5,318 ✔
1877
    }
2,666 ✔
1878
    return true;
536 ✔
1879
}
543 ✔
1880

1881
void encode_utf8(std::uint32_t c, dftracer::utils::dstd::String& out) {
7,282 ✔
1882
    if (c < 0x80) {
7,282 ✔
1883
        out.push_back(static_cast<char>(c));
6,680 ✔
1884
    } else if (c < 0x800) {
3,942 ✔
1885
        out.push_back(static_cast<char>(0xC0 | (c >> 6)));
282 ✔
1886
        out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
282 ✔
1887
    } else if (c < 0x10000) {
461 !
1888
        out.push_back(static_cast<char>(0xE0 | (c >> 12)));
320 ✔
1889
        out.push_back(static_cast<char>(0x80 | ((c >> 6) & 0x3F)));
320 ✔
1890
        out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
320 ✔
1891
    } else {
160 ✔
1892
        out.push_back(static_cast<char>(0xF0 | (c >> 18)));
×
1893
        out.push_back(static_cast<char>(0x80 | ((c >> 12) & 0x3F)));
×
1894
        out.push_back(static_cast<char>(0x80 | ((c >> 6) & 0x3F)));
×
1895
        out.push_back(static_cast<char>(0x80 | (c & 0x3F)));
×
1896
    }
1897
}
7,282 ✔
1898

1899
bool is_ascii_row(dftracer::utils::dstd::StringView s) {
858 ✔
1900
    for (const char ch : s)
5,187 ✔
1901
        if (static_cast<unsigned char>(ch) >= 0x80) return false;
4,470 ✔
1902
    return true;
288 ✔
1903
}
429 ✔
1904

1905
// A narrow String column whose row i is what `fn(row, buf)` leaves in `buf`;
1906
// `fn` returns false to make the row null. A null input row stays null.
1907
template <class Off, class Fn>
1908
dftu_series* transform_rows_w(const dftu_series* v, Fn& fn) {
324 ✔
1909
    RowReader r(v);
324 ✔
1910
    if (!r.ok()) return nullptr;
324 !
1911
    const std::size_t n = static_cast<std::size_t>(v->length);
324 ✔
1912
    dftracer::utils::dstd::Vector<std::int32_t> offsets(n + 1, 0);
324 ✔
1913
    dftracer::utils::dstd::String data;
324 ✔
1914
    dftracer::utils::dstd::String buf;
324 ✔
1915
    dftracer::utils::dstd::Vector<std::uint8_t> valid((n + 7) / 8, 0);
324 ✔
1916
    bool any_null = false;
324 ✔
1917
    for (std::size_t i = 0; i < n; ++i) {
2,788 !
1918
        bool hit = false;
2,464 ✔
1919
        dftracer::utils::dstd::StringView sv;
2,464 ✔
1920
        if (r.at(static_cast<std::int64_t>(i), sv) && fn(sv, buf)) {
2,464 ✔
1921
            data.append(buf);
2,080 ✔
1922
            hit = true;
2,080 !
1923
            if (!fits_int32_offsets(data.size())) return nullptr;
2,080 !
1924
        }
1,040 ✔
1925
        if (hit)
1,232 ✔
1926
            valid[i >> 3] |= static_cast<std::uint8_t>(1u << (i & 7));
2,080 ✔
1927
        else
1928
            any_null = true;
192 ✔
1929
        offsets[i + 1] = static_cast<std::int32_t>(data.size());
2,464 ✔
1930
    }
1,232 !
1931
    return dftu_series_new_string(DFTU_TYPE_STRING, offsets.data(), data.data(),
614 ✔
1932
                                  static_cast<std::int64_t>(n),
162 ✔
1933
                                  any_null ? valid.data() : nullptr);
452 !
1934
}
324 ✔
1935

1936
template <class Fn>
1937
dftu_series* transform_rows(const dftu_series* v, Fn fn) {
324 ✔
1938
    return is_wide_offset_type(v->type) ? transform_rows_w<std::int64_t>(v, fn)
324 ✔
1939
                                        : transform_rows_w<std::int32_t>(v, fn);
306 ✔
1940
}
1941

1942
bool is_utf8_string(const dftu_series* v) {
796 ✔
1943
    return v && narrow_varwidth_type(v->type) == TypeId::String;
796 !
1944
}
1945

1946
// translate: the codepoint table.
1947
struct TranslateTable {
65 ✔
1948
    // The replacement of an ASCII byte, an index into `reps`, or -1.
1949
    std::int32_t ascii[128];
1950
    // Sorted by codepoint; the other keys.
1951
    dftracer::utils::dstd::Vector<
1952
        dftracer::utils::dstd::Pair<std::uint32_t, std::int32_t>>
1953
        wide;
1954
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> reps;
1955
    TranslateTable() { std::fill(std::begin(ascii), std::end(ascii), -1); }
260 ✔
1956

1957
    std::int32_t find(std::uint32_t cp) const {
5,826 ✔
1958
        if (cp < 0x80) return ascii[cp];
5,826 ✔
1959
        const auto it = std::lower_bound(
584 ✔
1960
            wide.begin(), wide.end(), cp,
292 ✔
1961
            [](const auto& e, std::uint32_t k) { return e.first < k; });
142 ✔
1962
        return it != wide.end() && it->first == cp ? it->second : -1;
292 ✔
1963
    }
2,913 ✔
1964
};
1965

1966
struct StringRows {
128 ✔
1967
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> rows;
1968
    dftracer::utils::dstd::Vector<bool> nulls;
1969
};
1970

1971
template <class Off>
1972
bool read_rows_w(const dftu_series* s, StringRows& out) {
232 ✔
1973
    RowReader r(s);
232 ✔
1974
    if (!r.ok()) return false;
232 !
1975
    for (std::int64_t i = 0; i < s->length; ++i) {
804 ✔
1976
        dftracer::utils::dstd::StringView sv;
572 ✔
1977
        const bool is_null = !r.at(i, sv);
572 ✔
1978
        out.nulls.push_back(is_null);
572 ✔
1979
        out.rows.emplace_back(is_null ? dftracer::utils::dstd::StringView()
605 ✔
1980
                                      : sv);
253 ✔
1981
    }
286 ✔
1982
    return true;
116 ✔
1983
}
116 ✔
1984

1985
bool read_rows(const dftu_series* s, StringRows& out) {
256 ✔
1986
    if (s->length == 0) return true;
256 ✔
1987
    return is_wide_offset_type(s->type) ? read_rows_w<std::int64_t>(s, out)
232 !
1988
                                        : read_rows_w<std::int32_t>(s, out);
232 ✔
1989
}
128 ✔
1990

1991
bool build_translate_table(const dftu_series* from, const dftu_series* to,
130 ✔
1992
                           TranslateTable& t) {
1993
    if (!is_utf8_string(from) || !is_utf8_string(to) ||
130 !
1994
        from->length != to->length)
130 ✔
1995
        return false;
1 ✔
1996
    StringRows keys, vals;
128 ✔
1997
    if (!read_rows(from, keys) || !read_rows(to, vals)) return false;
128 !
1998
    dftracer::utils::dstd::Vector<std::uint32_t> key, val;
128 ✔
1999
    for (std::size_t i = 0; i < keys.rows.size(); ++i) {
408 ✔
2000
        if (keys.nulls[i] || !decode_utf8(keys.rows[i], key) || key.size() != 1)
286 ✔
2001
            return false;
9 ✔
2002
        if (!vals.nulls[i] && !decode_utf8(vals.rows[i], val)) return false;
280 ✔
2003
        const auto rep = static_cast<std::int32_t>(t.reps.size());
278 ✔
2004
        t.reps.push_back(vals.nulls[i] ? dftracer::utils::dstd::String()
417 ✔
2005
                                       : vals.rows[i]);
214 ✔
2006
        if (key[0] < 0x80) {
278 ✔
2007
            if (t.ascii[key[0]] >= 0) return false;
236 ✔
2008
            t.ascii[key[0]] = rep;
232 ✔
2009
        } else {
116 ✔
2010
            t.wide.emplace_back(key[0], rep);
42 ✔
2011
        }
2012
    }
139 ✔
2013
    std::sort(t.wide.begin(), t.wide.end());
116 ✔
2014
    return std::adjacent_find(t.wide.begin(), t.wide.end(),
174 ✔
2015
                              [](const auto& a, const auto& b) {
12 ✔
2016
                                  return a.first == b.first;
12 !
2017
                              }) == t.wide.end();
116 ✔
2018
}
193 ✔
2019

2020
}  // namespace
2021

2022
// wrap: textwrap.TextWrapper of CPython 3.13.10 and 3.14.1 on codepoints. A
2023
// non-ASCII codepoint counts as a letter and a word character in the splitting
2024
// rules.
2025
namespace {
2026

2027
struct WrapChunk {
2028
    std::uint32_t s;
2029
    std::uint32_t e;
2030
    std::int64_t len() const { return static_cast<std::int64_t>(e - s); }
2,040 ✔
2031
};
2032

2033
bool wrap_is_ws(std::uint32_t c) {
7,178 ✔
2034
    return c < 0x80 && dstd::is_ascii_space(static_cast<char>(c));
7,178 ✔
2035
}
2036

2037
bool wrap_is_letter(std::uint32_t c) {
762 ✔
2038
    return c >= 0x80 || c == '_' || dstd::is_ascii_alpha(static_cast<char>(c));
762 ✔
2039
}
2040

2041
bool wrap_is_word(std::uint32_t c) {
722 ✔
2042
    return wrap_is_letter(c) ||
745 !
2043
           (c < 0x80 && dstd::is_ascii_digit(static_cast<char>(c)));
46 ✔
2044
}
2045

2046
bool wrap_is_punct_word(std::uint32_t c) {
722 ✔
2047
    return wrap_is_word(c) || c == '!' || c == '"' || c == '\'' || c == '&' ||
387 !
2048
           c == '.' || c == ',' || c == '?';
374 ✔
2049
}
2050

2051
// Python's str.isspace for one codepoint.
2052
bool py_is_space(std::uint32_t c) {
440 ✔
2053
    return (c >= 9 && c <= 13) || (c >= 0x1C && c <= 0x20) || c == 0x85 ||
582 !
2054
           c == 0xA0 || c == 0x1680 || (c >= 0x2000 && c <= 0x200A) ||
142 !
2055
           c == 0x2028 || c == 0x2029 || c == 0x202F || c == 0x205F ||
142 !
2056
           c == 0x3000;
362 ✔
2057
}
2058

2059
class Wrapper {
2060
   public:
2061
    Wrapper(std::int64_t width, std::int32_t flags)
184 ✔
2062
        : width_(width),
92 ✔
2063
          expand_tabs_((flags & DFTU_WRAP_EXPAND_TABS) != 0),
92 ✔
2064
          replace_ws_((flags & DFTU_WRAP_REPLACE_WHITESPACE) != 0),
92 ✔
2065
          drop_ws_((flags & DFTU_WRAP_DROP_WHITESPACE) != 0),
92 ✔
2066
          break_long_((flags & DFTU_WRAP_BREAK_LONG_WORDS) != 0),
92 ✔
2067
          break_hyphens_((flags & DFTU_WRAP_BREAK_ON_HYPHENS) != 0) {}
184 ✔
2068

2069
    // The lines of `src` joined by "\n" in `out`.
2070
    void run(dftracer::utils::dstd::Span<const std::uint32_t> src,
574 ✔
2071
             dftracer::utils::dstd::String& out) {
2072
        munge(src);
574 ✔
2073
        if (break_hyphens_)
574 ✔
2074
            split_hyphens();
96 ✔
2075
        else
2076
            split_spaces();
478 ✔
2077
        wrap(out);
574 ✔
2078
    }
574 ✔
2079

2080
   private:
2081
    void munge(dftracer::utils::dstd::Span<const std::uint32_t> src) {
574 ✔
2082
        t_.clear();
574 ✔
2083
        std::uint32_t col = 0;
574 ✔
2084
        for (const std::uint32_t c : src) {
5,266 ✔
2085
            if (c == '\t' && expand_tabs_) {
4,692 ✔
2086
                const std::uint32_t k = 8 - col % 8;
4 ✔
2087
                t_.insert(t_.end(), k, std::uint32_t{' '});
4 ✔
2088
                col += k;
4 ✔
2089
                continue;
2 ✔
2090
            }
4 ✔
2091
            col = (c == '\n' || c == '\r') ? 0 : col + 1;
4,688 !
2092
            t_.push_back(replace_ws_ && wrap_is_ws(c) ? std::uint32_t{' '} : c);
5,285 ✔
2093
        }
2,346 !
2094
    }
574 ✔
2095

2096
    void emit(std::size_t s, std::size_t e) {
1,572 ✔
2097
        chunks_.push_back(
3,144 ✔
2098
            {static_cast<std::uint32_t>(s), static_cast<std::uint32_t>(e)});
786 ✔
2099
    }
786 ✔
2100

2101
    void split_spaces() {
478 ✔
2102
        chunks_.clear();
478 ✔
2103
        const std::size_t n = t_.size();
478 ✔
2104
        std::size_t i = 0;
478 ✔
2105
        while (i < n) {
1,628 ✔
2106
            const bool ws = wrap_is_ws(t_[i]);
1,150 ✔
2107
            std::size_t j = i + 1;
1,150 ✔
2108
            while (j < n && wrap_is_ws(t_[j]) == ws) ++j;
3,532 ✔
2109
            emit(i, j);
1,150 ✔
2110
            i = j;
1,150 ✔
2111
        }
575 ✔
2112
    }
478 ✔
2113

2114
    // Whether t_[j..] is two or more '-' followed by a word character.
2115
    bool dashes_then_word(std::size_t j) const {
716 ✔
2116
        const std::size_t n = t_.size();
716 ✔
2117
        std::size_t k = j;
716 ✔
2118
        while (k < n && t_[k] == '-') ++k;
718 ✔
2119
        return k - j >= 2 && k < n && wrap_is_word(t_[k]);
716 !
2120
    }
358 ✔
2121

2122
    // wordsep_re: whitespace runs, an em-dash between words, or a word that
2123
    // ends at whitespace, the end, a hyphen inside a word or before an
2124
    // em-dash.
2125
    void split_hyphens() {
96 ✔
2126
        chunks_.clear();
96 ✔
2127
        const dftracer::utils::dstd::Vector<std::uint32_t>& t = t_;
96 ✔
2128
        const std::size_t n = t.size();
96 ✔
2129
        std::size_t i = 0;
96 ✔
2130
        while (i < n) {
518 ✔
2131
            if (wrap_is_ws(t[i])) {
422 ✔
2132
                std::size_t j = i + 1;
176 ✔
2133
                while (j < n && wrap_is_ws(t[j])) ++j;
198 ✔
2134
                emit(i, j);
176 ✔
2135
                i = j;
176 ✔
2136
                continue;
88 ✔
2137
            }
176 ✔
2138
            if (t[i] == '-' && i > 0 && wrap_is_punct_word(t[i - 1]) &&
246 !
2139
                dashes_then_word(i)) {
×
2140
                std::size_t j = i;
2141
                while (j < n && t[j] == '-') ++j;
×
2142
                emit(i, j);
×
2143
                i = j;
×
2144
                continue;
2145
            }
×
2146
            std::size_t j = i + 1;
246 ✔
2147
            while (true) {
1,329 ✔
2148
                if (j < n && t[j] == '-' && hyphen_break(j)) {
968 ✔
2149
                    emit(i, j + 1);
10 ✔
2150
                    i = j + 1;
10 ✔
2151
                    break;
10 ✔
2152
                }
2153
                if (j >= n || wrap_is_ws(t[j]) ||
1,316 ✔
2154
                    (wrap_is_punct_word(t[j - 1]) && dashes_then_word(j))) {
722 !
2155
                    emit(i, j);
236 ✔
2156
                    i = j;
236 ✔
2157
                    break;
236 ✔
2158
                }
2159
                ++j;
722 ✔
2160
            }
2161
        }
123 ✔
2162
    }
96 ✔
2163

2164
    // The '-' at t_[j] ends a chunk: two letters, or a letter, '-' and a
2165
    // letter, before it, and a letter, an optional '-' and a letter after it.
2166
    bool hyphen_break(std::size_t j) const {
12 ✔
2167
        const dftracer::utils::dstd::Vector<std::uint32_t>& t = t_;
12 ✔
2168
        const std::size_t n = t.size();
12 ✔
2169
        const bool before =
18 ✔
2170
            (j >= 2 && wrap_is_letter(t[j - 2]) && wrap_is_letter(t[j - 1])) ||
13 !
2171
            (j >= 3 && wrap_is_letter(t[j - 3]) && t[j - 2] == '-' &&
1 !
2172
             wrap_is_letter(t[j - 1]));
×
2173
        if (!before) return false;
11 ✔
2174
        if (j + 2 >= n || !wrap_is_letter(t[j + 1])) return false;
10 !
2175
        return wrap_is_letter(t[j + 2]) ||
10 ✔
2176
               (t[j + 2] == '-' && j + 3 < n && wrap_is_letter(t[j + 3]));
×
2177
    }
6 ✔
2178

2179
    bool space_chunk(const WrapChunk& c) const {
412 ✔
2180
        for (std::uint32_t k = c.s; k < c.e; ++k)
710 ✔
2181
            if (!py_is_space(t_[k])) return false;
440 ✔
2182
        return true;
64 ✔
2183
    }
206 ✔
2184

2185
    void handle_long_word(std::size_t pos, std::int64_t cur_size) {
384 ✔
2186
        const std::int64_t space_left = width_ - cur_size;
384 ✔
2187
        if (break_long_ && space_left > 0) {
384 ✔
2188
            std::int64_t end = space_left;
42 ✔
2189
            WrapChunk& chunk = chunks_[pos];
42 ✔
2190
            if (break_hyphens_ && chunk.len() > space_left) {
42 ✔
2191
                std::int64_t hyphen = -1;
40 ✔
2192
                for (std::int64_t k = space_left - 1; k >= 0; --k)
142 ✔
2193
                    if (t_[chunk.s + k] == '-') {
102 ✔
2194
                        hyphen = k;
2195
                        break;
2196
                    }
2197
                bool other = false;
40 ✔
2198
                for (std::int64_t k = 0; k < hyphen && !other; ++k)
40 !
2199
                    other = t_[chunk.s + k] != '-';
×
2200
                if (hyphen > 0 && other) end = hyphen + 1;
40 !
2201
            }
20 ✔
2202
            const auto cut = chunk.s + static_cast<std::uint32_t>(end);
42 ✔
2203
            line_.push_back({chunk.s, cut});
42 ✔
2204
            chunk.s = cut;
42 ✔
2205
        } else if (line_.empty()) {
384 ✔
2206
            line_.push_back(chunks_[pos]);
210 ✔
2207
            taken_ = true;
210 ✔
2208
        }
105 ✔
2209
    }
384 ✔
2210

2211
    void wrap(dftracer::utils::dstd::String& out) {
574 ✔
2212
        out.clear();
574 ✔
2213
        std::size_t pos = 0;
574 ✔
2214
        const std::size_t total = chunks_.size();
574 ✔
2215
        bool any_line = false;
574 ✔
2216
        while (pos < total) {
1,700 ✔
2217
            line_.clear();
1,126 ✔
2218
            std::int64_t cur_size = 0;
1,126 ✔
2219
            if (drop_ws_ && any_line && space_chunk(chunks_[pos])) ++pos;
1,126 ✔
2220
            while (pos < total) {
2,454 ✔
2221
                const std::int64_t l = chunks_[pos].len();
2,068 ✔
2222
                if (cur_size + l > width_) break;
2,068 ✔
2223
                line_.push_back(chunks_[pos++]);
1,328 ✔
2224
                cur_size += l;
1,328 ✔
2225
            }
1,034 ✔
2226
            if (pos < total && chunks_[pos].len() > width_) {
1,126 ✔
2227
                taken_ = false;
384 ✔
2228
                handle_long_word(pos, cur_size);
384 ✔
2229
                if (taken_) ++pos;
384 ✔
2230
                cur_size = 0;
384 ✔
2231
                for (const WrapChunk& c : line_) cur_size += c.len();
876 ✔
2232
            }
192 ✔
2233
            if (drop_ws_ && !line_.empty() && space_chunk(line_.back()))
1,126 !
2234
                line_.pop_back();
94 ✔
2235
            if (line_.empty()) continue;
1,126 ✔
2236
            if (any_line) out.push_back('\n');
1,114 ✔
2237
            any_line = true;
1,114 ✔
2238
            for (const WrapChunk& c : line_)
2,600 ✔
2239
                for (std::uint32_t k = c.s; k < c.e; ++k)
6,038 ✔
2240
                    encode_utf8(t_[k], out);
5,295 ✔
2241
        }
563 ✔
2242
    }
574 ✔
2243

2244
    std::int64_t width_;
2245
    bool expand_tabs_;
2246
    bool replace_ws_;
2247
    bool drop_ws_;
2248
    bool break_long_;
2249
    bool break_hyphens_;
2250
    bool taken_ = false;
46 ✔
2251
    dftracer::utils::dstd::Vector<std::uint32_t> t_;
2252
    dftracer::utils::dstd::Vector<WrapChunk> chunks_;
2253
    dftracer::utils::dstd::Vector<WrapChunk> line_;
2254
};
2255

2256
}  // namespace
2257

2258
dftu_series* dftu_series_str_normalize(const dftu_series* v,
208 ✔
2259
                                       std::int32_t form) {
2260
    if (!is_utf8_string(v)) return nullptr;
208 ✔
2261
    int options = UTF8PROC_STABLE;
150 ✔
2262
    switch (form) {
150 ✔
2263
        case DFTU_NORM_NFC:
2264
            options |= UTF8PROC_COMPOSE;
9 ✔
2265
            break;
9 ✔
2266
        case DFTU_NORM_NFKC:
36 ✔
2267
            options |= UTF8PROC_COMPOSE | UTF8PROC_COMPAT;
72 ✔
2268
            break;
72 ✔
2269
        case DFTU_NORM_NFD:
22 ✔
2270
            options |= UTF8PROC_DECOMPOSE;
44 ✔
2271
            break;
44 ✔
2272
        case DFTU_NORM_NFKD:
6 ✔
2273
            options |= UTF8PROC_DECOMPOSE | UTF8PROC_COMPAT;
12 ✔
2274
            break;
12 ✔
2275
        default:
2276
            return nullptr;
2 ✔
2277
    }
2278
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_normalize, form);
146 !
2279
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_normalize(flat_v, form));
138 !
2280
    const auto opts = static_cast<utf8proc_option_t>(options);
116 ✔
2281
    dftracer::utils::dstd::Vector<utf8proc_int32_t> cps;
116 ✔
2282
    return transform_rows(v, [&](dftracer::utils::dstd::StringView row,
545 ✔
2283
                                 dftracer::utils::dstd::String& out) {
2284
        out.clear();
858 ✔
2285
        if (is_ascii_row(row)) {
858 ✔
2286
            out.assign(row);
576 ✔
2287
            return true;
576 ✔
2288
        }
2289
        const auto* src = reinterpret_cast<const utf8proc_uint8_t*>(row.data());
282 ✔
2290
        const auto len = static_cast<utf8proc_ssize_t>(row.size());
282 ✔
2291
        if (cps.size() < row.size()) cps.resize(row.size());
282 ✔
2292
        auto n =
423 ✔
2293
            utf8proc_decompose(src, len, cps.data(),
564 ✔
2294
                               static_cast<utf8proc_ssize_t>(cps.size()), opts);
282 ✔
2295
        if (n > static_cast<utf8proc_ssize_t>(cps.size())) {
282 ✔
2296
            cps.resize(static_cast<std::size_t>(n));
×
2297
            n = utf8proc_decompose(src, len, cps.data(), n, opts);
×
2298
        }
2299
        if (n < 0) return false;
282 ✔
2300
        n = utf8proc_normalize_utf32(cps.data(), n, opts);
264 ✔
2301
        if (n < 0) return false;
264 !
2302
        for (utf8proc_ssize_t i = 0; i < n; ++i)
2,994 ✔
2303
            encode_utf8(static_cast<std::uint32_t>(cps[i]), out);
2,730 ✔
2304
        return true;
132 ✔
2305
    });
429 ✔
2306
}
104 ✔
2307

2308
dftu_series* dftu_series_str_translate(const dftu_series* v,
146 ✔
2309
                                       const dftu_series* from,
2310
                                       const dftu_series* to) {
2311
    if (!is_utf8_string(v) || !from || !to) return nullptr;
146 !
2312
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_translate, from, to);
146 !
2313
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_translate(flat_v, from, to));
138 !
2314
    TranslateTable table;
130 ✔
2315
    if (!build_translate_table(from, to, table)) return nullptr;
130 ✔
2316
    return transform_rows(v, [&](dftracer::utils::dstd::StringView row,
455 ✔
2317
                                 dftracer::utils::dstd::String& out) {
2318
        out.clear();
678 ✔
2319
        const auto* begin = reinterpret_cast<const std::uint8_t*>(row.data());
678 ✔
2320
        const auto* end = begin + row.size();
678 ✔
2321
        const auto* run = begin;
678 ✔
2322
        for (const auto* p = begin; p < end;) {
6,510 ✔
2323
            std::uint32_t cp;
5,838 ✔
2324
            const std::size_t n = utf8_next(p, end, cp);
5,838 ✔
2325
            if (n == 0) return false;
5,838 ✔
2326
            const std::int32_t rep = table.find(cp);
5,826 ✔
2327
            if (rep >= 0) {
5,826 ✔
2328
                out.append(reinterpret_cast<const char*>(run),
1,551 ✔
2329
                           static_cast<std::size_t>(p - run));
1,034 ✔
2330
                out.append(table.reps[static_cast<std::size_t>(rep)]);
1,034 ✔
2331
                run = p + n;
1,034 ✔
2332
            }
517 ✔
2333
            p += n;
5,826 ✔
2334
        }
2,919 ✔
2335
        out.append(reinterpret_cast<const char*>(run),
999 ✔
2336
                   static_cast<std::size_t>(end - run));
666 ✔
2337
        return true;
666 ✔
2338
    });
397 ✔
2339
}
146 ✔
2340

2341
dftu_series* dftu_series_str_wrap(const dftu_series* v, std::int64_t width,
182 ✔
2342
                                  std::int32_t flags) {
2343
    constexpr std::int32_t ALL_FLAGS =
182 ✔
2344
        DFTU_WRAP_EXPAND_TABS | DFTU_WRAP_REPLACE_WHITESPACE |
2345
        DFTU_WRAP_DROP_WHITESPACE | DFTU_WRAP_BREAK_LONG_WORDS |
2346
        DFTU_WRAP_BREAK_ON_HYPHENS;
2347
    if (!is_utf8_string(v) || width < 1 || (flags & ~ALL_FLAGS) != 0)
182 ✔
2348
        return nullptr;
31 ✔
2349
    DFTU_DICTIONARY_ELEMENTWISE(v, dftu_series_str_wrap, width, flags);
120 !
2350
    DFTU_FLAT_OPERAND(v, flat_v, dftu_series_str_wrap(flat_v, width, flags));
112 !
2351
    Wrapper wrapper(width, flags);
92 ✔
2352
    dftracer::utils::dstd::Vector<std::uint32_t> cps;
92 ✔
2353
    return transform_rows(v, [&](dftracer::utils::dstd::StringView row,
385 ✔
2354
                                 dftracer::utils::dstd::String& out) {
2355
        if (!decode_utf8(row, cps)) return false;
586 ✔
2356
        wrapper.run(cps, out);
574 ✔
2357
        return true;
574 ✔
2358
    });
293 ✔
2359
}
137 ✔
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