Skip to main content

c/
wchar.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// wchar: wide string functions
6// ============================================================
7
8#[no_mangle]
9pub unsafe extern "C" fn wcslen(s: *const wchar_t) -> usize {
10    let mut len = 0;
11    while *s.add(len) != 0 { len += 1; }
12    len
13}
14
15#[no_mangle]
16pub unsafe extern "C" fn wcschr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
17    let mut i = 0;
18    loop {
19        let ch = *s.add(i);
20        if ch == c { return s.add(i) as *mut wchar_t; }
21        if ch == 0 { return null_mut(); }
22        i += 1;
23    }
24}
25
26#[no_mangle]
27pub unsafe extern "C" fn wcsrchr(s: *const wchar_t, c: wchar_t) -> *mut wchar_t {
28    let mut i = 0;
29    let mut last: *mut wchar_t = null_mut();
30    loop {
31        let ch = *s.add(i);
32        if ch == c { last = s.add(i) as *mut wchar_t; }
33        if ch == 0 { return last; }
34        i += 1;
35    }
36}
37
38#[no_mangle]
39pub unsafe extern "C" fn wcsstr(haystack: *const wchar_t, needle: *const wchar_t) -> *mut wchar_t {
40    if *needle == 0 { return haystack as *mut wchar_t; }
41    let mut i = 0;
42    loop {
43        let h = *haystack.add(i);
44        if h == 0 { return null_mut(); }
45        if h == *needle {
46            let mut j = 0;
47            loop {
48                let n = *needle.add(j);
49                if n == 0 { return haystack.add(i) as *mut wchar_t; }
50                if *haystack.add(i + j) != n { break; }
51                j += 1;
52            }
53        }
54        i += 1;
55    }
56}
57
58#[no_mangle]
59pub unsafe extern "C" fn wcscmp(s1: *const wchar_t, s2: *const wchar_t) -> c_int {
60    let mut i = 0;
61    loop {
62        let a = *s1.add(i);
63        let b = *s2.add(i);
64        if a != b { return a - b; }
65        if a == 0 { return 0; }
66        i += 1;
67    }
68}
69
70#[no_mangle]
71pub unsafe extern "C" fn wcsncmp(s1: *const wchar_t, s2: *const wchar_t, n: usize) -> c_int {
72    let mut i = 0;
73    while i < n {
74        let a = *s1.add(i);
75        let b = *s2.add(i);
76        if a != b { return a - b; }
77        if a == 0 { return 0; }
78        i += 1;
79    }
80    0
81}
82
83#[no_mangle]
84pub unsafe extern "C" fn wcscpy(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
85    let mut i = 0;
86    loop {
87        let c = *src.add(i);
88        *dst.add(i) = c;
89        if c == 0 { break; }
90        i += 1;
91    }
92    dst
93}
94
95#[no_mangle]
96pub unsafe extern "C" fn wcsncpy(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
97    let mut i = 0;
98    while i < n && *src.add(i) != 0 { *dst.add(i) = *src.add(i); i += 1; }
99    while i < n { *dst.add(i) = 0; i += 1; }
100    dst
101}
102
103#[no_mangle]
104pub unsafe extern "C" fn wcscat(dst: *mut wchar_t, src: *const wchar_t) -> *mut wchar_t {
105    let mut i = 0;
106    while *dst.add(i) != 0 { i += 1; }
107    let mut j = 0;
108    loop {
109        let c = *src.add(j);
110        *dst.add(i + j) = c;
111        if c == 0 { break; }
112        j += 1;
113    }
114    dst
115}
116
117#[no_mangle]
118pub unsafe extern "C" fn wcsncat(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> *mut wchar_t {
119    let mut i = 0;
120    while *dst.add(i) != 0 { i += 1; }
121    let mut j = 0;
122    while j < n && *src.add(j) != 0 { *dst.add(i + j) = *src.add(j); j += 1; }
123    *dst.add(i + j) = 0;
124    dst
125}
126
127#[no_mangle]
128pub unsafe extern "C" fn wcsdup(s: *const wchar_t) -> *mut wchar_t {
129    let len = wcslen(s);
130    let p = malloc((len + 1) * core::mem::size_of::<wchar_t>()) as *mut wchar_t;
131    if p.is_null() { return null_mut(); }
132    core::ptr::copy_nonoverlapping(s, p, len + 1);
133    p
134}
135
136#[no_mangle]
137pub unsafe extern "C" fn wcsnlen(s: *const wchar_t, maxlen: usize) -> usize {
138    let mut i = 0;
139    while i < maxlen && *s.add(i) != 0 { i += 1; }
140    i
141}
142
143#[no_mangle]
144pub unsafe extern "C" fn wcsspn(s: *const wchar_t, accept: *const wchar_t) -> usize {
145    let mut i = 0;
146    loop {
147        let c = *s.add(i);
148        if c == 0 { return i; }
149        let mut found = false;
150        let mut j = 0;
151        loop {
152            let a = *accept.add(j);
153            if a == 0 { break; }
154            if c == a { found = true; break; }
155            j += 1;
156        }
157        if !found { return i; }
158        i += 1;
159    }
160}
161
162#[no_mangle]
163pub unsafe extern "C" fn wcscspn(s: *const wchar_t, reject: *const wchar_t) -> usize {
164    let mut i = 0;
165    loop {
166        let c = *s.add(i);
167        if c == 0 { return i; }
168        let mut j = 0;
169        loop {
170            let r = *reject.add(j);
171            if r == 0 { break; }
172            if c == r { return i; }
173            j += 1;
174        }
175        i += 1;
176    }
177}
178
179#[no_mangle]
180pub unsafe extern "C" fn wcspbrk(s: *const wchar_t, accept: *const wchar_t) -> *mut wchar_t {
181    let mut i = 0;
182    loop {
183        let c = *s.add(i);
184        if c == 0 { return null_mut(); }
185        let mut j = 0;
186        loop {
187            let a = *accept.add(j);
188            if a == 0 { break; }
189            if c == a { return s.add(i) as *mut wchar_t; }
190            j += 1;
191        }
192        i += 1;
193    }
194}
195
196#[no_mangle]
197pub unsafe extern "C" fn wcsxfrm(dst: *mut wchar_t, src: *const wchar_t, n: usize) -> usize {
198    let len = wcslen(src);
199    if !dst.is_null() {
200        let copy = if len < n { len } else { if n > 0 { n - 1 } else { 0 } };
201        for i in 0..copy { *dst.add(i) = *src.add(i); }
202        if n > 0 { *dst.add(copy) = 0; }
203    }
204    len
205}
206
207// ============================================================
208// wchar: wcsto* number conversions
209// ============================================================
210
211unsafe fn wcs_to_bytes(ws: *const wchar_t, buf: *mut u8, bufsz: usize) -> usize {
212    if bufsz == 0 {
213        return 0;
214    }
215    let mut i = 0;
216    while i < bufsz - 1 {
217        let c = *ws.add(i);
218        if c == 0 { break; }
219        if (c as u32) > 127 { break; }
220        *buf.add(i) = c as u8;
221        i += 1;
222    }
223    *buf.add(i) = 0;
224    i
225}
226
227macro_rules! wcsto_int {
228    ($name:ident, $ret:ty, $conv:ident) => {
229        #[no_mangle]
230        pub unsafe extern "C" fn $name(
231            s: *const wchar_t,
232            endptr: *mut *mut wchar_t,
233            base: c_int,
234        ) -> $ret {
235            let cap = wcslen(s).saturating_add(1);
236            let heap = cap > 256;
237            let mut stack = [0u8; 256];
238            let buf = if heap {
239                crate::malloc(cap) as *mut u8
240            } else {
241                stack.as_mut_ptr()
242            };
243            if buf.is_null() {
244                ERRNO!() = ENOMEM;
245                return 0;
246            }
247            wcs_to_bytes(s, buf, cap);
248            let mut end: *mut c_char = core::ptr::null_mut();
249            let r = $conv(buf as *const c_char, &mut end, base);
250            if !endptr.is_null() {
251                let offset = end as usize - buf as usize;
252                *endptr = s.add(offset) as *mut wchar_t;
253            }
254            if heap {
255                crate::free(buf as *mut c_void);
256            }
257            r
258        }
259    };
260}
261
262wcsto_int!(wcstol, c_long, strtol);
263wcsto_int!(wcstoul, c_ulong, strtoul);
264wcsto_int!(wcstoll, c_longlong, strtoll);
265wcsto_int!(wcstoull, c_ulonglong, strtoull);
266
267#[no_mangle]
268pub unsafe extern "C" fn wcstod(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f64 {
269    let cap = wcslen(s).saturating_add(1);
270    let heap = cap > 256;
271    let mut stack = [0u8; 256];
272    let buf = if heap {
273        crate::malloc(cap) as *mut u8
274    } else {
275        stack.as_mut_ptr()
276    };
277    if buf.is_null() {
278        ERRNO!() = ENOMEM;
279        return 0.0;
280    }
281    wcs_to_bytes(s, buf, cap);
282    let mut end: *mut c_char = core::ptr::null_mut();
283    let r = strtod(buf as *const c_char, &mut end);
284    if !endptr.is_null() {
285        let offset = end as usize - buf as usize;
286        *endptr = s.add(offset) as *mut wchar_t;
287    }
288    if heap {
289        crate::free(buf as *mut c_void);
290    }
291    r
292}
293
294#[no_mangle]
295pub unsafe extern "C" fn wcstof(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f32 { wcstod(s, endptr) as f32 }
296
297#[no_mangle]
298#[cfg(target_arch = "aarch64")]
299pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { f64_to_f128(wcstod(s, endptr)) }
300
301#[no_mangle]
302#[cfg(any(target_arch = "riscv64", target_arch = "powerpc64", target_arch = "loongarch64"))]
303pub unsafe extern "C" fn wcstold(s: *const wchar_t, endptr: *mut *mut wchar_t) -> f128 { f64_to_f128(wcstod(s, endptr)) }
304
305#[no_mangle]
306pub unsafe extern "C" fn wcstoimax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_longlong { wcstoll(s, endptr, base) }
307
308#[no_mangle]
309pub unsafe extern "C" fn wcstoumax(s: *const wchar_t, endptr: *mut *mut wchar_t, base: c_int) -> c_ulonglong { wcstoull(s, endptr, base) }
310
311// ============================================================
312// wctype: classification functions
313// ============================================================
314
315const WC_ALPHA: c_int = 1;
316const WC_DIGIT: c_int = 2;
317const WC_SPACE: c_int = 4;
318const WC_UPPER: c_int = 8;
319const WC_LOWER: c_int = 16;
320const WC_ALNUM: c_int = WC_ALPHA | WC_DIGIT;
321const WC_BLANK: c_int = 32;
322const WC_CNTRL: c_int = 64;
323const WC_PUNCT: c_int = 128;
324const WC_GRAPH: c_int = WC_ALNUM | WC_PUNCT;
325const WC_PRINT: c_int = WC_GRAPH | WC_BLANK;
326const WC_XDIGIT: c_int = 256;
327
328#[inline]
329fn wctable_bit(table: &[u8], wc: wint_t) -> bool {
330    let wc = wc as u32;
331    let page = table[(wc >> 8) as usize] as usize;
332    (table[page * 32 + ((wc & 255) >> 3) as usize] >> (wc & 7)) & 1 != 0
333}
334
335/// Port of musl's iswalpha: table lookup below U+20000, then a broad
336/// alphabetic range up to U+2FFFD.
337#[no_mangle]
338pub extern "C" fn iswalpha(c: wint_t) -> c_int {
339    let wc = c as u32;
340    if wc < 0x20000 {
341        return wctable_bit(&WCTYPE_ALPHA_TABLE, c) as c_int;
342    }
343    if wc < 0x2fffe { 1 } else { 0 }
344}
345
346/// Port of musl's iswpunct.
347#[no_mangle]
348pub extern "C" fn iswpunct(c: wint_t) -> c_int {
349    let wc = c as u32;
350    if wc < 0x20000 {
351        wctable_bit(&WCTYPE_PUNCT_TABLE, c) as c_int
352    } else {
353        0
354    }
355}
356
357/// Port of musl's iswprint.
358#[no_mangle]
359pub extern "C" fn iswprint(c: wint_t) -> c_int {
360    let wc = c as u32;
361    if wc < 0xff {
362        return (((wc + 1) & 0x7f) >= 0x21) as c_int;
363    }
364    if wc < 0x2028
365        || wc.wrapping_sub(0x202a) < 0xd800 - 0x202a
366        || wc.wrapping_sub(0xe000) < 0xfff9 - 0xe000
367    {
368        return 1;
369    }
370    if wc.wrapping_sub(0xfffc) > 0x10ffff - 0xfffc || (wc & 0xfffe) == 0xfffe {
371        return 0;
372    }
373    1
374}
375
376/// Port of musl's iswspace: Unicode White_Space minus U+00A0/U+2007/U+202F,
377/// plus U+1680 and U+180E are excluded (they have non-blank glyphs).
378#[no_mangle]
379pub extern "C" fn iswspace(c: wint_t) -> c_int {
380    matches!(
381        c as u32,
382        0x20 | 0x09 | 0x0a | 0x0d | 0x0b | 0x0c | 0x85
383            | 0x2000..=0x2006 | 0x2008..=0x200a
384            | 0x2028 | 0x2029 | 0x205f | 0x3000
385    ) as c_int
386}
387
388/// Port of musl's iswcntrl.
389#[no_mangle]
390pub extern "C" fn iswcntrl(c: wint_t) -> c_int {
391    let wc = c as u32;
392    ((wc < 32)
393        || wc.wrapping_sub(0x7f) < 33
394        || wc.wrapping_sub(0x2028) < 2
395        || wc.wrapping_sub(0xfff9) < 3) as c_int
396}
397
398#[no_mangle]
399pub extern "C" fn iswdigit(c: wint_t) -> c_int {
400    ((c as u32).wrapping_sub(b'0' as u32) < 10) as c_int
401}
402
403#[no_mangle]
404pub extern "C" fn iswxdigit(c: wint_t) -> c_int {
405    let wc = c as u32;
406    ((wc.wrapping_sub(b'0' as u32) < 10) || ((wc | 32).wrapping_sub(b'a' as u32) < 6)) as c_int
407}
408
409#[no_mangle]
410pub extern "C" fn iswalnum(c: wint_t) -> c_int {
411    (iswdigit(c) != 0 || iswalpha(c) != 0) as c_int
412}
413
414#[no_mangle]
415pub extern "C" fn iswblank(c: wint_t) -> c_int {
416    (c == b' ' as wint_t || c == b'\t' as wint_t) as c_int
417}
418
419#[no_mangle]
420pub extern "C" fn iswgraph(c: wint_t) -> c_int {
421    (iswspace(c) == 0 && iswprint(c) != 0) as c_int
422}
423
424#[no_mangle]
425pub extern "C" fn iswlower(c: wint_t) -> c_int {
426    (unsafe { towupper(c) } != c) as c_int
427}
428
429#[no_mangle]
430pub extern "C" fn iswupper(c: wint_t) -> c_int {
431    (unsafe { towlower(c) } != c) as c_int
432}
433
434static WCTYPE_ALNUM: c_int = WC_ALNUM;
435static WCTYPE_ALPHA: c_int = WC_ALPHA;
436static WCTYPE_BLANK: c_int = WC_BLANK;
437static WCTYPE_CNTRL: c_int = WC_CNTRL;
438static WCTYPE_DIGIT: c_int = WC_DIGIT;
439static WCTYPE_GRAPH: c_int = WC_GRAPH;
440static WCTYPE_LOWER: c_int = WC_LOWER;
441static WCTYPE_PRINT: c_int = WC_PRINT;
442static WCTYPE_PUNCT: c_int = WC_PUNCT;
443static WCTYPE_SPACE: c_int = WC_SPACE;
444static WCTYPE_UPPER: c_int = WC_UPPER;
445static WCTYPE_XDIGIT: c_int = WC_XDIGIT;
446
447#[no_mangle]
448pub unsafe extern "C" fn wctype(name: *const c_char) -> wctype_t {
449    if name.is_null() { return core::ptr::null(); }
450    let n = name as *const u8;
451    if crate::cstr_eq(n, b"alnum") { return &WCTYPE_ALNUM; }
452    if crate::cstr_eq(n, b"alpha") { return &WCTYPE_ALPHA; }
453    if crate::cstr_eq(n, b"blank") { return &WCTYPE_BLANK; }
454    if crate::cstr_eq(n, b"cntrl") { return &WCTYPE_CNTRL; }
455    if crate::cstr_eq(n, b"digit") { return &WCTYPE_DIGIT; }
456    if crate::cstr_eq(n, b"graph") { return &WCTYPE_GRAPH; }
457    if crate::cstr_eq(n, b"lower") { return &WCTYPE_LOWER; }
458    if crate::cstr_eq(n, b"print") { return &WCTYPE_PRINT; }
459    if crate::cstr_eq(n, b"punct") { return &WCTYPE_PUNCT; }
460    if crate::cstr_eq(n, b"space") { return &WCTYPE_SPACE; }
461    if crate::cstr_eq(n, b"upper") { return &WCTYPE_UPPER; }
462    if crate::cstr_eq(n, b"xdigit") { return &WCTYPE_XDIGIT; }
463    core::ptr::null()
464}
465
466#[no_mangle]
467pub unsafe extern "C" fn iswctype(c: wint_t, desc: wctype_t) -> c_int {
468    if desc.is_null() { return 0; }
469    if desc == core::ptr::addr_of!(WCTYPE_ALNUM) { return iswalnum(c); }
470    if desc == core::ptr::addr_of!(WCTYPE_ALPHA) { return iswalpha(c); }
471    if desc == core::ptr::addr_of!(WCTYPE_BLANK) { return iswblank(c); }
472    if desc == core::ptr::addr_of!(WCTYPE_CNTRL) { return iswcntrl(c); }
473    if desc == core::ptr::addr_of!(WCTYPE_DIGIT) { return iswdigit(c); }
474    if desc == core::ptr::addr_of!(WCTYPE_GRAPH) { return iswgraph(c); }
475    if desc == core::ptr::addr_of!(WCTYPE_LOWER) { return iswlower(c); }
476    if desc == core::ptr::addr_of!(WCTYPE_PRINT) { return iswprint(c); }
477    if desc == core::ptr::addr_of!(WCTYPE_PUNCT) { return iswpunct(c); }
478    if desc == core::ptr::addr_of!(WCTYPE_SPACE) { return iswspace(c); }
479    if desc == core::ptr::addr_of!(WCTYPE_UPPER) { return iswupper(c); }
480    if desc == core::ptr::addr_of!(WCTYPE_XDIGIT) { return iswxdigit(c); }
481    0
482}
483
484static WCTRANS_LOWER: c_int = 1;
485static WCTRANS_UPPER: c_int = 2;
486
487/// Port of musl's casemap() from ctype/towctrans.c.
488fn casemap(c: wint_t, dir: i32) -> wint_t {
489    let c0 = c;
490    if c0 >= 0x20000 {
491        return c0;
492    }
493    let b = (c0 >> 8) as usize;
494    let cc = c0 & 255;
495    let x = (cc / 3) as usize;
496    let y = (cc % 3) as usize;
497    const MT: [u32; 3] = [2048, 342, 57];
498    let v = WCTYPE_CASEMAP_TAB[WCTYPE_CASEMAP_TAB[b] as usize * 86 + x] as u32;
499    let v = (v * MT[y] >> 11) % 6;
500    let r = WCTYPE_CASEMAP_RULES[(WCTYPE_CASEMAP_RULEBASES[b] + v as u8) as usize];
501    let rt = (r & 255) as i32;
502    let rd = r >> 8;
503    if rt < 2 {
504        return (c0 as i32 + (rd & -((rt) ^ dir))) as wint_t;
505    }
506    let mut xn = (rd & 0xff) as u32;
507    let mut xb = (rd as u32) >> 8;
508    while xn != 0 {
509        let idx = (xb + xn / 2) as usize;
510        let try_ = WCTYPE_CASEMAP_EXCEPTIONS[idx][0] as u32;
511        if try_ == cc {
512            let r2 = WCTYPE_CASEMAP_RULES[WCTYPE_CASEMAP_EXCEPTIONS[idx][1] as usize];
513            let rt2 = (r2 & 255) as i32;
514            let rd2 = r2 >> 8;
515            if rt2 < 2 {
516                return (c0 as i32 + (rd2 & -((rt2) ^ dir))) as wint_t;
517            }
518            return (c0 as i32 + if dir != 0 { -1 } else { 1 }) as wint_t;
519        } else if try_ > cc {
520            xn /= 2;
521        } else {
522            xb += xn / 2;
523            xn -= xn / 2;
524        }
525    }
526    c0
527}
528
529#[no_mangle]
530pub unsafe extern "C" fn towlower(c: wint_t) -> wint_t {
531    casemap(c, 0)
532}
533
534#[no_mangle]
535pub unsafe extern "C" fn towupper(c: wint_t) -> wint_t {
536    casemap(c, 1)
537}
538
539#[no_mangle]
540pub unsafe extern "C" fn wctrans(name: *const c_char) -> wctrans_t {
541    if name.is_null() { return core::ptr::null(); }
542    let n = name as *const u8;
543    if crate::cstr_eq(n, b"tolower") { return &WCTRANS_LOWER; }
544    if crate::cstr_eq(n, b"toupper") { return &WCTRANS_UPPER; }
545    core::ptr::null()
546}
547
548#[no_mangle]
549pub unsafe extern "C" fn towctrans(c: wint_t, desc: wctrans_t) -> wint_t {
550    if desc.is_null() { return c; }
551    match *desc {
552        1 => towlower(c),
553        2 => towupper(c),
554        _ => c,
555    }
556}
557