Skip to main content

c/
stdlib_num.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// stdlib.h: integer conversion, abs, rand
6// ============================================================
7
8unsafe fn parse_digit(c: u8, base: c_int) -> Option<u8> {
9    if c == 0 { return None; }
10    let d = if c >= b'0' && c <= b'9' {
11        c - b'0'
12    } else if c >= b'a' && c <= b'z' {
13        c - b'a' + 10
14    } else if c >= b'A' && c <= b'Z' {
15        c - b'A' + 10
16    } else {
17        return None;
18    };
19    if (d as c_int) < base {
20        Some(d)
21    } else {
22        None
23    }
24}
25
26unsafe fn parse_prefix(s: *const u8, base: *mut c_int) -> *const u8 {
27    let mut p = s;
28    if *base == 0 {
29        if *p == b'0' {
30            if (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
31                *base = 16;
32                p = p.add(2);
33            } else {
34                *base = 8;
35            }
36        } else {
37            *base = 10;
38        }
39    } else if *base == 16 {
40        if *p == b'0' && (*p.add(1) == b'x' || *p.add(1) == b'X') && parse_digit(*p.add(2), 16).is_some() {
41            p = p.add(2);
42        }
43    }
44    p
45}
46
47unsafe fn strtox(
48    s: *const c_char,
49    endptr: *mut *mut c_char,
50    mut base: c_int,
51    pos_limit: u64,
52    neg_limit: u64,
53) -> (u64, bool, bool) {
54    let s0 = s as *const u8;
55    let mut p = s0;
56    while isspace(*p as c_int) != 0 {
57        p = p.add(1);
58    }
59
60    if base < 0 || base == 1 || base > 36 {
61        if !endptr.is_null() {
62            *endptr = s as *mut c_char;
63        }
64        ERRNO!() = EINVAL;
65        return (0, false, false);
66    }
67
68    let mut neg = false;
69    match *p {
70        b'-' => { neg = true; p = p.add(1); }
71        b'+' => p = p.add(1),
72        _ => {}
73    }
74
75    p = parse_prefix(p, &mut base);
76
77    let limit = if neg { neg_limit } else { pos_limit };
78    let mut val: u64 = 0;
79    let mut any = false;
80    while let Some(d) = parse_digit(*p, base) {
81        any = true;
82        if val > (limit - d as u64) / base as u64 {
83            while parse_digit(*p, base).is_some() { p = p.add(1); }
84            if !endptr.is_null() { *endptr = p as *mut c_char; }
85            ERRNO!() = ERANGE;
86            return (limit, true, neg);
87        }
88        val = val * base as u64 + d as u64;
89        p = p.add(1);
90    }
91
92    if !endptr.is_null() {
93        *endptr = if any { p as *mut c_char } else { s as *mut c_char };
94    }
95    (val, false, neg)
96}
97
98#[no_mangle]
99pub unsafe extern "C" fn strtol(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_long {
100    let pos_limit = c_long::MAX as u64;
101    let neg_limit = pos_limit.wrapping_add(1);
102    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
103    if overflow {
104        return if neg { c_long::MIN } else { c_long::MAX };
105    }
106    if neg { val.wrapping_neg() as c_long } else { val as c_long }
107}
108
109#[no_mangle]
110pub unsafe extern "C" fn strtoul(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulong {
111    let limit = c_ulong::MAX as u64;
112    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
113    if overflow {
114        return c_ulong::MAX;
115    }
116    if neg { val.wrapping_neg() as c_ulong } else { val as c_ulong }
117}
118
119#[no_mangle]
120pub unsafe extern "C" fn strtoll(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_longlong {
121    let pos_limit = c_longlong::MAX as u64;
122    let neg_limit = pos_limit.wrapping_add(1);
123    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
124    if overflow {
125        return if neg { c_longlong::MIN } else { c_longlong::MAX };
126    }
127    if neg { val.wrapping_neg() as c_longlong } else { val as c_longlong }
128}
129
130#[no_mangle]
131pub unsafe extern "C" fn strtoull(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulonglong {
132    let limit = c_ulonglong::MAX as u64;
133    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
134    if overflow {
135        return c_ulonglong::MAX;
136    }
137    if neg { val.wrapping_neg() as c_ulonglong } else { val as c_ulonglong }
138}
139
140#[no_mangle]
141pub unsafe extern "C" fn atoi(s: *const c_char) -> c_int {
142    strtol(s, core::ptr::null_mut(), 10) as c_int
143}
144
145#[no_mangle]
146pub unsafe extern "C" fn atol(s: *const c_char) -> c_long {
147    strtol(s, core::ptr::null_mut(), 10)
148}
149
150#[no_mangle]
151pub unsafe extern "C" fn atoll(s: *const c_char) -> c_longlong {
152    strtoll(s, core::ptr::null_mut(), 10)
153}
154
155#[no_mangle]
156pub extern "C" fn abs(n: c_int) -> c_int {
157    if n < 0 {
158        -n
159    } else {
160        n
161    }
162}
163
164#[no_mangle]
165pub extern "C" fn labs(n: c_long) -> c_long {
166    if n < 0 {
167        -n
168    } else {
169        n
170    }
171}
172
173#[no_mangle]
174pub extern "C" fn llabs(n: c_longlong) -> c_longlong {
175    if n < 0 {
176        -n
177    } else {
178        n
179    }
180}
181
182static mut RAND_STATE: c_uint = 1;
183
184#[no_mangle]
185pub extern "C" fn srand(seed: c_uint) {
186    unsafe {
187        RAND_STATE = seed;
188    }
189}
190
191#[no_mangle]
192pub extern "C" fn rand() -> c_int {
193    unsafe {
194        RAND_STATE = RAND_STATE.wrapping_mul(1103515245).wrapping_add(12345);
195        ((RAND_STATE >> 16) & 0x7fff) as c_int
196    }
197}
198
199// ============================================================
200// stdlib.h: div, ldiv, lldiv
201// ============================================================
202
203#[repr(C)]
204pub struct div_t { pub quot: c_int, pub rem: c_int }
205#[repr(C)]
206pub struct ldiv_t { pub quot: c_long, pub rem: c_long }
207#[repr(C)]
208pub struct lldiv_t { pub quot: c_longlong, pub rem: c_longlong }
209
210#[no_mangle]
211pub extern "C" fn div(num: c_int, den: c_int) -> div_t {
212    div_t { quot: num / den, rem: num % den }
213}
214
215#[no_mangle]
216pub extern "C" fn ldiv(num: c_long, den: c_long) -> ldiv_t {
217    ldiv_t { quot: num / den, rem: num % den }
218}
219
220#[no_mangle]
221pub extern "C" fn lldiv(num: c_longlong, den: c_longlong) -> lldiv_t {
222    lldiv_t { quot: num / den, rem: num % den }
223}
224
225// ============================================================
226// bsearch
227// ============================================================
228
229type CmpFn = unsafe extern "C" fn(*const c_void, *const c_void) -> c_int;
230
231#[no_mangle]
232pub unsafe extern "C" fn bsearch(
233    key: *const c_void,
234    base: *const c_void,
235    nel: usize,
236    width: usize,
237    cmp: CmpFn,
238) -> *mut c_void {
239    let mut base = base as *const u8;
240    let mut nel = nel;
241    while nel > 0 {
242        let trial = base.add(width * (nel / 2));
243        let sign = cmp(key, trial as *const c_void);
244        if sign < 0 {
245            nel /= 2;
246        } else if sign > 0 {
247            base = trial.add(width);
248            nel -= nel / 2 + 1;
249        } else {
250            return trial as *mut c_void;
251        }
252    }
253    null_mut()
254}
255
256include!("signal.rs");
257include!("process.rs");