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 base_u = base as u64;
79    // Precompute the overflow bounds once: the previous code performed a
80    // 64-bit division for every digit.
81    let cutoff = limit / base_u;
82    let cut_rem = limit % base_u;
83    let mut val: u64 = 0;
84    let mut any = false;
85    loop {
86        let d = if base == 10 {
87            let c = *p;
88            if c < b'0' || c > b'9' { break; }
89            (c - b'0') as u64
90        } else {
91            match parse_digit(*p, base) {
92                Some(d) => d as u64,
93                None => break,
94            }
95        };
96        any = true;
97        if val > cutoff || (val == cutoff && d > cut_rem) {
98            while parse_digit(*p, base).is_some() { p = p.add(1); }
99            if !endptr.is_null() { *endptr = p as *mut c_char; }
100            ERRNO!() = ERANGE;
101            return (limit, true, neg);
102        }
103        val = val * base_u + d;
104        p = p.add(1);
105    }
106
107    if !endptr.is_null() {
108        *endptr = if any { p as *mut c_char } else { s as *mut c_char };
109    }
110    (val, false, neg)
111}
112
113#[no_mangle]
114pub unsafe extern "C" fn strtol(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_long {
115    let pos_limit = c_long::MAX as u64;
116    let neg_limit = pos_limit.wrapping_add(1);
117    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
118    if overflow {
119        return if neg { c_long::MIN } else { c_long::MAX };
120    }
121    if neg { val.wrapping_neg() as c_long } else { val as c_long }
122}
123
124#[no_mangle]
125pub unsafe extern "C" fn strtoul(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulong {
126    let limit = c_ulong::MAX as u64;
127    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
128    if overflow {
129        return c_ulong::MAX;
130    }
131    if neg { val.wrapping_neg() as c_ulong } else { val as c_ulong }
132}
133
134#[no_mangle]
135pub unsafe extern "C" fn strtoll(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_longlong {
136    let pos_limit = c_longlong::MAX as u64;
137    let neg_limit = pos_limit.wrapping_add(1);
138    let (val, overflow, neg) = strtox(s, endptr, base, pos_limit, neg_limit);
139    if overflow {
140        return if neg { c_longlong::MIN } else { c_longlong::MAX };
141    }
142    if neg { val.wrapping_neg() as c_longlong } else { val as c_longlong }
143}
144
145#[no_mangle]
146pub unsafe extern "C" fn strtoull(s: *const c_char, endptr: *mut *mut c_char, base: c_int) -> c_ulonglong {
147    let limit = c_ulonglong::MAX as u64;
148    let (val, overflow, neg) = strtox(s, endptr, base, limit, limit);
149    if overflow {
150        return c_ulonglong::MAX;
151    }
152    if neg { val.wrapping_neg() as c_ulonglong } else { val as c_ulonglong }
153}
154
155#[no_mangle]
156pub unsafe extern "C" fn atoi(s: *const c_char) -> c_int {
157    strtol(s, core::ptr::null_mut(), 10) as c_int
158}
159
160#[no_mangle]
161pub unsafe extern "C" fn atol(s: *const c_char) -> c_long {
162    strtol(s, core::ptr::null_mut(), 10)
163}
164
165#[no_mangle]
166pub unsafe extern "C" fn atoll(s: *const c_char) -> c_longlong {
167    strtoll(s, core::ptr::null_mut(), 10)
168}
169
170#[no_mangle]
171pub extern "C" fn abs(n: c_int) -> c_int {
172    if n < 0 {
173        -n
174    } else {
175        n
176    }
177}
178
179#[no_mangle]
180pub extern "C" fn labs(n: c_long) -> c_long {
181    if n < 0 {
182        -n
183    } else {
184        n
185    }
186}
187
188#[no_mangle]
189pub extern "C" fn llabs(n: c_longlong) -> c_longlong {
190    if n < 0 {
191        -n
192    } else {
193        n
194    }
195}
196
197static mut RAND_STATE: c_uint = 1;
198
199#[no_mangle]
200pub extern "C" fn srand(seed: c_uint) {
201    unsafe {
202        RAND_STATE = seed;
203    }
204}
205
206#[no_mangle]
207pub extern "C" fn rand() -> c_int {
208    unsafe {
209        RAND_STATE = RAND_STATE.wrapping_mul(1103515245).wrapping_add(12345);
210        ((RAND_STATE >> 16) & 0x7fff) as c_int
211    }
212}
213
214// ============================================================
215// stdlib.h: div, ldiv, lldiv
216// ============================================================
217
218#[repr(C)]
219pub struct div_t { pub quot: c_int, pub rem: c_int }
220#[repr(C)]
221pub struct ldiv_t { pub quot: c_long, pub rem: c_long }
222#[repr(C)]
223pub struct lldiv_t { pub quot: c_longlong, pub rem: c_longlong }
224
225#[no_mangle]
226pub extern "C" fn div(num: c_int, den: c_int) -> div_t {
227    div_t { quot: num / den, rem: num % den }
228}
229
230#[no_mangle]
231pub extern "C" fn ldiv(num: c_long, den: c_long) -> ldiv_t {
232    ldiv_t { quot: num / den, rem: num % den }
233}
234
235#[no_mangle]
236pub extern "C" fn lldiv(num: c_longlong, den: c_longlong) -> lldiv_t {
237    lldiv_t { quot: num / den, rem: num % den }
238}
239
240// ============================================================
241// bsearch
242// ============================================================
243
244type CmpFn = unsafe extern "C" fn(*const c_void, *const c_void) -> c_int;
245
246#[no_mangle]
247pub unsafe extern "C" fn bsearch(
248    key: *const c_void,
249    base: *const c_void,
250    nel: usize,
251    width: usize,
252    cmp: CmpFn,
253) -> *mut c_void {
254    let mut base = base as *const u8;
255    let mut nel = nel;
256    while nel > 0 {
257        let trial = base.add(width * (nel / 2));
258        let sign = cmp(key, trial as *const c_void);
259        if sign < 0 {
260            nel /= 2;
261        } else if sign > 0 {
262            base = trial.add(width);
263            nel -= nel / 2 + 1;
264        } else {
265            return trial as *mut c_void;
266        }
267    }
268    null_mut()
269}
270
271include!("signal.rs");
272include!("process.rs");