Ad

It's like doing code golf if it were.. football? Codeball? I don't know, I've lost enough of my sanity as it is to name this monstrosity.

Code
Diff
  • use std::arch::asm;
    
    // Yes, why not make it longer. I invite the next person to over-engineer it further.
    // (an INTERCAL interpreter implemented using Rust macros would be kinda funny)
    
    fn reverse(s: &str) -> String {
        let mut reversed = s.to_string();
    
        unsafe fn reverse_string_asm(s: &mut str) {
            let strlen = s.len();
            let strptr = s.as_ptr();
    
            asm!(
                "mov rcx, {strlen}",
                "shr rcx, 1",
                "jz 2f",
                "mov rsi, {strptr}",
                "mov rdi, {strptr}",
                "add rdi, {strlen}",
                "dec rdi",
                "2:",
                    "mov al, [rsi]",
                    "mov bl, [rdi]",
                    "mov [rsi], bl",
                    "mov [rdi], al",
                    "inc rsi",
                    "dec rdi",
                    "loop 2b",
                "2:",
    
                strlen = in(reg) strlen,
                strptr = in(reg) strptr,
                options(nostack, preserves_flags)
            );
        }
    
        if reversed.len() != 0 {
            unsafe { reverse_string_asm(reversed.as_mut()) };
        }
    
        reversed
    }
    • use std::arch::asm;
    • // Yes, why not make it longer. I invite the next person to over-engineer it further.
    • // (an INTERCAL interpreter implemented using Rust macros would be kinda funny)
    • fn reverse(s: &str) -> String {
    • s.chars().fold(String::new(), |acc, c| format!("{}{}", c, acc))
    • let mut reversed = s.to_string();
    • unsafe fn reverse_string_asm(s: &mut str) {
    • let strlen = s.len();
    • let strptr = s.as_ptr();
    • asm!(
    • "mov rcx, {strlen}",
    • "shr rcx, 1",
    • "jz 2f",
    • "mov rsi, {strptr}",
    • "mov rdi, {strptr}",
    • "add rdi, {strlen}",
    • "dec rdi",
    • "2:",
    • "mov al, [rsi]",
    • "mov bl, [rdi]",
    • "mov [rsi], bl",
    • "mov [rdi], al",
    • "inc rsi",
    • "dec rdi",
    • "loop 2b",
    • "2:",
    • strlen = in(reg) strlen,
    • strptr = in(reg) strptr,
    • options(nostack, preserves_flags)
    • );
    • }
    • if reversed.len() != 0 {
    • unsafe { reverse_string_asm(reversed.as_mut()) };
    • }
    • reversed
    • }