Skip to main content

luaur_vm/functions/
scanformat.rs

1use crate::macros::lua_l_error::luaL_error;
2use crate::macros::uchar::uchar;
3use crate::type_aliases::lua_state::lua_State;
4use core::ffi::c_char;
5use core::ptr;
6
7#[no_mangle]
8pub unsafe fn scanformat(
9    L: *mut lua_State,
10    strfrmt: *const c_char,
11    mut form: *mut c_char,
12    size: *mut usize,
13) -> *const c_char {
14    const FLAGS: &[u8] = b"-+ #0";
15
16    let mut p = strfrmt;
17    while *p != 0 && FLAGS.contains(&(uchar(*p as i32) as u8)) {
18        p = p.offset(1);
19    }
20
21    if (p as usize - strfrmt as usize) >= FLAGS.len() {
22        luaL_error!(L, "invalid format (repeated flags)");
23    }
24
25    if (uchar(*p as i32) as u8).is_ascii_digit() {
26        p = p.offset(1);
27    }
28    if (uchar(*p as i32) as u8).is_ascii_digit() {
29        p = p.offset(1);
30    }
31
32    if *p == b'.' as c_char {
33        p = p.offset(1);
34        if (uchar(*p as i32) as u8).is_ascii_digit() {
35            p = p.offset(1);
36        }
37        if (uchar(*p as i32) as u8).is_ascii_digit() {
38            p = p.offset(1);
39        }
40    }
41
42    if (uchar(*p as i32) as u8).is_ascii_digit() {
43        luaL_error!(L, "invalid format (width or precision too long)");
44    }
45
46    ptr::write(form, b'%' as c_char);
47    form = form.offset(1);
48    *size = (p as usize - strfrmt as usize) + 1;
49    core::ptr::copy_nonoverlapping(strfrmt, form, *size);
50    form = form.offset(*size as isize);
51    ptr::write(form, 0);
52
53    p
54}