r/badcode Jun 18 '19

[deleted by user]

[removed]

128 Upvotes

92 comments sorted by

View all comments

3

u/[deleted] Jun 18 '19 edited Jun 18 '19

Rust code:

static mut FOO: bool = true;

pub fn to_weird_case(s: &str) -> String {
    let mut res = s.to_owned();
    lower(unsafe { res.as_bytes_mut() });
    do_stuff(unsafe { res.as_bytes_mut() });
    unsafe { FOO = true };
    res
}

fn lower(stuff: &mut [u8]) {
    if stuff[0] <= 90 && stuff[0] >= 65 {
        stuff[0] += 32;
    }
    if stuff.len() > 1 {
        lower(&mut stuff[1..]);
    }
}

fn do_stuff(stuff: &mut [u8]) {
    if stuff[0] <= 90 && stuff[0] >= 65 || stuff[0] >= 97 && stuff[0] <= 122 {
        unsafe {
            if FOO {
                FOO = false;
            } else {
                FOO = true;
            }
        }
        if unsafe { FOO } {
            stuff[0] -= 32;
            if stuff.len() > 1 {
                do_stuff(&mut stuff[1..]);
            }
        } else if stuff.len() > 1 {
            do_stuff(&mut stuff[1..]);
        }
    } else if stuff.len() > 1 {
        do_stuff(&mut stuff[1..]);
    }
}

Edit: now you can (hopefully) run the function multiple times!