ferray-strings 0.4.9

String operations on character arrays for ferray
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// ferray-strings: Case manipulation operations (REQ-5)
//
// Implements upper, lower, capitalize, title — elementwise on StringArray.
//
// `capitalize` and `title` match Python `str.capitalize`/`str.title`
// (the semantics `numpy.char`/`numpy.strings` delegate to via `_vec_string`,
// numpy/_core/strings.py:1239 capitalize, :1282 title). The word-initial
// character uses the Unicode TITLECASE mapping (not uppercase): the ligature
// `fi` titlecases to `Fi` (not `FI`), `ß` to `Ss` (not `SS`), and the Lt
// digraph `Dž` titlecases to itself (not `DŽ`). Tail characters use full
// lowercase with final-sigma context (word-final `Σ` -> `ς`). Rust's
// `str::to_lowercase` already implements the Unicode Final_Sigma rule, so the
// tail is routed through it; only the word-initial titlecase needs a table,
// since Rust's stdlib has no `to_titlecase`.
//
// ## REQ status
//
// SHIPPED:
//   - REQ-5 case manipulation — `upper`, `lower`, `capitalize`, `title`
//     (all `pub fn` in this file). `upper`/`lower` route through Rust's
//     Unicode `to_uppercase`/`to_lowercase` (full case folding, e.g.
//     `ß` -> `SS`), matching CPython `str.upper`/`str.lower`.
//     `capitalize`/`title` reproduce CPython `str.capitalize`/`str.title`
//     (the semantics `numpy.char`/`numpy.strings` delegate to via
//     `_vec_string`): word-initial characters use the Unicode TITLECASE
//     mapping, tails use lowercase with the Final_Sigma rule.
//     (`swapcase` lives in `str_ops.rs`.)
//
// Consumers (non-test): re-exported from the crate root
// (`ferray-strings/src/lib.rs` `pub use case::{capitalize, lower, title,
// upper}`) and bound at the Python surface by the `#[pyfunction]` shims
// generated via `bind_unary_string_op!(lower, fs::lower)`,
// `(upper, fs::upper)`, `(capitalize, fs::capitalize)`, `(title, fs::title)`
// in `ferray-python/src/char.rs`, which back `numpy.char`/`numpy.strings`.

use ferray_core::dimension::Dimension;
use ferray_core::error::FerrayResult;

use crate::string_array::StringArray;

/// The Unicode titlecase mapping for the characters whose titlecase differs
/// from their uppercase. For every other character titlecase == uppercase, so
/// the fallback uses `char::to_uppercase`.
///
/// Derived live from CPython/Unicode (matches the numpy 2.4 oracle):
/// `[chr(c) for c in range(0x110000) if chr(c).title() != chr(c).upper()]`,
/// mapping each to `chr(c).title()`. Covers the case ligatures
/// (`fi`->`Fi`, `ß`->`Ss`, …), the Latin/Greek titlecase digraphs (Lt chars
/// that titlecase to themselves), and the Armenian/Greek/Georgian forms.
fn titlecase_char(c: char) -> String {
    let mapped: &str = match c as u32 {
        0x00DF => "Ss",
        0x01C4 => "Dž",
        0x01C5 => "Dž",
        0x01C6 => "Dž",
        0x01C7 => "Lj",
        0x01C8 => "Lj",
        0x01C9 => "Lj",
        0x01CA => "Nj",
        0x01CB => "Nj",
        0x01CC => "Nj",
        0x01F1 => "Dz",
        0x01F2 => "Dz",
        0x01F3 => "Dz",
        0x0587 => "Եւ",
        0x10D0 => "",
        0x10D1 => "",
        0x10D2 => "",
        0x10D3 => "",
        0x10D4 => "",
        0x10D5 => "",
        0x10D6 => "",
        0x10D7 => "",
        0x10D8 => "",
        0x10D9 => "",
        0x10DA => "",
        0x10DB => "",
        0x10DC => "",
        0x10DD => "",
        0x10DE => "",
        0x10DF => "",
        0x10E0 => "",
        0x10E1 => "",
        0x10E2 => "",
        0x10E3 => "",
        0x10E4 => "",
        0x10E5 => "",
        0x10E6 => "",
        0x10E7 => "",
        0x10E8 => "",
        0x10E9 => "",
        0x10EA => "",
        0x10EB => "",
        0x10EC => "",
        0x10ED => "",
        0x10EE => "",
        0x10EF => "",
        0x10F0 => "",
        0x10F1 => "",
        0x10F2 => "",
        0x10F3 => "",
        0x10F4 => "",
        0x10F5 => "",
        0x10F6 => "",
        0x10F7 => "",
        0x10F8 => "",
        0x10F9 => "",
        0x10FA => "",
        0x10FD => "",
        0x10FE => "",
        0x10FF => "",
        0x1F80 => "",
        0x1F81 => "",
        0x1F82 => "",
        0x1F83 => "",
        0x1F84 => "",
        0x1F85 => "",
        0x1F86 => "",
        0x1F87 => "",
        0x1F88 => "",
        0x1F89 => "",
        0x1F8A => "",
        0x1F8B => "",
        0x1F8C => "",
        0x1F8D => "",
        0x1F8E => "",
        0x1F8F => "",
        0x1F90 => "",
        0x1F91 => "",
        0x1F92 => "",
        0x1F93 => "",
        0x1F94 => "",
        0x1F95 => "",
        0x1F96 => "",
        0x1F97 => "",
        0x1F98 => "",
        0x1F99 => "",
        0x1F9A => "",
        0x1F9B => "",
        0x1F9C => "",
        0x1F9D => "",
        0x1F9E => "",
        0x1F9F => "",
        0x1FA0 => "",
        0x1FA1 => "",
        0x1FA2 => "",
        0x1FA3 => "",
        0x1FA4 => "",
        0x1FA5 => "",
        0x1FA6 => "",
        0x1FA7 => "",
        0x1FA8 => "",
        0x1FA9 => "",
        0x1FAA => "",
        0x1FAB => "",
        0x1FAC => "",
        0x1FAD => "",
        0x1FAE => "",
        0x1FAF => "",
        0x1FB2 => "Ὰͅ",
        0x1FB3 => "",
        0x1FB4 => "Άͅ",
        0x1FB7 => "ᾼ͂",
        0x1FBC => "",
        0x1FC2 => "Ὴͅ",
        0x1FC3 => "",
        0x1FC4 => "Ήͅ",
        0x1FC7 => "ῌ͂",
        0x1FCC => "",
        0x1FF2 => "Ὼͅ",
        0x1FF3 => "",
        0x1FF4 => "Ώͅ",
        0x1FF7 => "ῼ͂",
        0x1FFC => "",
        0xFB00 => "Ff",
        0xFB01 => "Fi",
        0xFB02 => "Fl",
        0xFB03 => "Ffi",
        0xFB04 => "Ffl",
        0xFB05 => "St",
        0xFB06 => "St",
        0xFB13 => "Մն",
        0xFB14 => "Մե",
        0xFB15 => "Մի",
        0xFB16 => "Վն",
        0xFB17 => "Մխ",
        _ => return c.to_uppercase().collect(),
    };
    mapped.to_string()
}

/// Whether `c` has the Unicode `Cased` property — used to find word
/// boundaries for `title` (Python's `str.title` treats a character as
/// word-initial when the previous character is not cased). Rust's
/// `char::is_lowercase` / `char::is_uppercase` cover the `Lowercase` /
/// `Uppercase` properties but miss the titlecase (`Lt`) characters, which are
/// added explicitly. (The `Lt` set: U+01C5/01C8/01CB/01F2 and the Greek
/// titlecase ranges — derived from `category(chr(c)) == 'Lt'`.)
fn is_cased(c: char) -> bool {
    c.is_lowercase()
        || c.is_uppercase()
        || matches!(
            c,
            '\u{1C5}'
                | '\u{1C8}'
                | '\u{1CB}'
                | '\u{1F2}'
                | '\u{1F88}'..='\u{1F8F}'
                | '\u{1F98}'..='\u{1F9F}'
                | '\u{1FA8}'..='\u{1FAF}'
                | '\u{1FBC}'
                | '\u{1FCC}'
                | '\u{1FFC}'
        )
}

/// Convert each string element to uppercase.
///
/// # Errors
/// Returns an error if the internal array construction fails.
///
/// # Examples
/// ```ignore
/// let a = strings::array(&["hello", "world"]).unwrap();
/// let b = strings::upper(&a).unwrap();
/// assert_eq!(b.as_slice(), &["HELLO", "WORLD"]);
/// ```
pub fn upper<D: Dimension>(a: &StringArray<D>) -> FerrayResult<StringArray<D>> {
    a.map(str::to_uppercase)
}

/// Convert each string element to lowercase.
///
/// # Errors
/// Returns an error if the internal array construction fails.
pub fn lower<D: Dimension>(a: &StringArray<D>) -> FerrayResult<StringArray<D>> {
    a.map(str::to_lowercase)
}

/// Capitalize each string element: the first character is titlecased and the
/// rest is lowercased (final-sigma aware), matching Python `str.capitalize`.
///
/// The first character uses the Unicode titlecase mapping (`fi`->`Fi`,
/// `ß`->`Ss`); the tail is the whole-string lowercase with the first
/// character's lowercase span removed, so the final-sigma decision sees the
/// (cased) first character as preceding context.
///
/// # Errors
/// Returns an error if the internal array construction fails.
pub fn capitalize<D: Dimension>(a: &StringArray<D>) -> FerrayResult<StringArray<D>> {
    a.map(|s| {
        let mut chars = s.chars();
        match chars.next() {
            None => String::new(),
            Some(first) => {
                // `str::to_lowercase` resolves every final-sigma against the
                // whole-string context; the first character's lowercase is
                // context-free (nothing precedes it), so slicing it off the
                // front leaves the correctly-lowered tail.
                let lowered = s.to_lowercase();
                let first_lower_len: usize = first.to_lowercase().map(char::len_utf8).sum();
                let tail = &lowered[first_lower_len..];
                let head = titlecase_char(first);
                format!("{head}{tail}")
            }
        }
    })
}

/// Title-case each string element: each word starts with a titlecased
/// character and all remaining cased characters are lowercased, matching
/// Python `str.title` / `numpy.char.title`.
///
/// A character is word-initial when the preceding character is not cased
/// (digits and punctuation are not cased, so a letter following one is
/// titlecased). The tail uses the whole-string lowercase so a word-final
/// `Σ` becomes `ς` (final sigma) per the Unicode Final_Sigma rule.
///
/// # Errors
/// Returns an error if the internal array construction fails.
pub fn title<D: Dimension>(a: &StringArray<D>) -> FerrayResult<StringArray<D>> {
    a.map(|s| {
        // Whole-string lowercase resolves final-sigma at every position; each
        // original character maps to a span of `lowered` whose byte length
        // equals `char::to_lowercase(c)` (final sigma `ς` and `σ` are both two
        // bytes, so the only context-sensitive case preserves the span width).
        let lowered = s.to_lowercase();
        let mut result = String::with_capacity(lowered.len());
        let mut previous_is_cased = false;
        let mut lowered_offset = 0usize;
        for ch in s.chars() {
            let lower_len: usize = ch.to_lowercase().map(char::len_utf8).sum();
            if is_cased(ch) && !previous_is_cased {
                result.push_str(&titlecase_char(ch));
            } else {
                result.push_str(&lowered[lowered_offset..lowered_offset + lower_len]);
            }
            lowered_offset += lower_len;
            previous_is_cased = is_cased(ch);
        }
        result
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::string_array::array;

    #[test]
    fn test_upper() {
        let a = array(&["hello", "world"]).unwrap();
        let b = upper(&a).unwrap();
        assert_eq!(b.as_slice(), &["HELLO", "WORLD"]);
    }

    #[test]
    fn test_lower() {
        let a = array(&["HELLO", "World"]).unwrap();
        let b = lower(&a).unwrap();
        assert_eq!(b.as_slice(), &["hello", "world"]);
    }

    #[test]
    fn test_capitalize() {
        let a = array(&["hello world", "fOO BAR", ""]).unwrap();
        let b = capitalize(&a).unwrap();
        assert_eq!(b.as_slice(), &["Hello world", "Foo bar", ""]);
    }

    #[test]
    fn test_title() {
        let a = array(&["hello world", "foo bar baz"]).unwrap();
        let b = title(&a).unwrap();
        assert_eq!(b.as_slice(), &["Hello World", "Foo Bar Baz"]);
    }

    #[test]
    fn test_title_mixed_case() {
        let a = array(&["hELLO wORLD"]).unwrap();
        let b = title(&a).unwrap();
        assert_eq!(b.as_slice(), &["Hello World"]);
    }

    #[test]
    fn test_upper_empty() {
        let a = array(&[""]).unwrap();
        let b = upper(&a).unwrap();
        assert_eq!(b.as_slice(), &[""]);
    }

    // ---- Titlecase / final-sigma divergence regression (#915) ----------
    // Expected values come from Python `str.capitalize`/`str.title`, the
    // semantics numpy.char delegates to (R-CHAR-3).

    #[test]
    fn test_capitalize_ligature_titlecase() {
        // 'finery'.capitalize() == 'Finery' (fi titlecases to "Fi", not "FI").
        let a = array(&["\u{FB01}nery"]).unwrap();
        let b = capitalize(&a).unwrap();
        assert_eq!(b.as_slice(), &["Finery"]);
    }

    #[test]
    fn test_capitalize_sharp_s_titlecase() {
        // 'ßeta'.capitalize() == 'Sseta' (ß -> "Ss", not "SS").
        let a = array(&["\u{DF}eta"]).unwrap();
        let b = capitalize(&a).unwrap();
        assert_eq!(b.as_slice(), &["Sseta"]);
    }

    #[test]
    fn test_capitalize_digraph_titlecase() {
        // 'Džungla'.capitalize() == 'Džungla' (U+01C5 titlecases to itself).
        let a = array(&["\u{1C5}ungla"]).unwrap();
        let b = capitalize(&a).unwrap();
        assert_eq!(b.as_slice(), &["\u{1C5}ungla"]);
    }

    #[test]
    fn test_capitalize_final_sigma() {
        // 'ΟΔΟΣ'.capitalize() == 'Οδος' (word-final Σ -> ς).
        let a = array(&["\u{39F}\u{394}\u{39F}\u{3A3}"]).unwrap();
        let b = capitalize(&a).unwrap();
        assert_eq!(b.as_slice(), &["\u{39F}\u{3B4}\u{3BF}\u{3C2}"]);
    }

    #[test]
    fn test_title_ligature_titlecase() {
        // 'file file'.title() == 'File File'.
        let a = array(&["\u{FB01}le \u{FB01}le"]).unwrap();
        let b = title(&a).unwrap();
        assert_eq!(b.as_slice(), &["File File"]);
    }

    #[test]
    fn test_title_sharp_s_titlecase() {
        // 'ßtraße ßeta'.title() == 'Sstraße Sseta'.
        let a = array(&["\u{DF}tra\u{DF}e \u{DF}eta"]).unwrap();
        let b = title(&a).unwrap();
        assert_eq!(b.as_slice(), &["Sstra\u{DF}e Sseta"]);
    }

    #[test]
    fn test_title_final_sigma() {
        // 'ΟΔΟΣ ΟΔΟΣ'.title() == 'Οδος Οδος' (word-final Σ -> ς per word).
        let a = array(&["\u{39F}\u{394}\u{39F}\u{3A3} \u{39F}\u{394}\u{39F}\u{3A3}"]).unwrap();
        let b = title(&a).unwrap();
        assert_eq!(
            b.as_slice(),
            &["\u{39F}\u{3B4}\u{3BF}\u{3C2} \u{39F}\u{3B4}\u{3BF}\u{3C2}"]
        );
    }

    #[test]
    fn test_title_digit_word_boundary() {
        // 'a1b c'.title() == 'A1B C' — a digit is not cased, so the letter
        // after it is word-initial (titlecased).
        let a = array(&["a1b c"]).unwrap();
        let b = title(&a).unwrap();
        assert_eq!(b.as_slice(), &["A1B C"]);
    }
}