4 ms·
Thus I give you my first Rust program ;) // needs in main.rs or lib.rs #![feature(const_fn)] use std::os::raw::c_schar; use std::mem; const A
by scotty79 10y ago
Thus I give you my first Rust program ;)
// needs in main.rs or lib.rs #![feature(const_fn)]
use std::os::raw::c_schar;
use std::mem;
const ALLSET:usize = (-1_isize) as usize;
const MAXCHR:usize = u8::max_value() as usize;
const ONES:usize = ALLSET / MAXCHR;
const HIGHS:usize = ONES * ((MAXCHR+1)/2);
const ALIGN:usize = 8; // mem::size_of::<usize>(); // mem::size_of<T>() is not const fn (yet?)
pub unsafe extern "C" fn strlen(s: *const c_schar) -> usize {
let mut i:usize = 0;
loop {
if *s.offset(i as isize) == 0 { return i; }
i += 1;
if (i % ALIGN) == 0 { break; }
}
loop {
let v = *mem::transmute::<*const c_schar, *const usize>(s.offset(i as isize));
if v.wrapping_sub(ONES) & !v & HIGHS != 0 {
break;
}
i += ALIGN;
}
loop {
if *s.offset(i as isize) == 0 { return i; }
i += 1;
}
}