How to use XOR to swap two characters in a string in Rust

1 Answer

0 votes
/// Swaps two ASCII characters in a mutable byte slice using the XOR swap algorithm.
///
/// # Arguments
///
/// * `bytes` - A mutable slice of bytes containing ASCII characters to swap.
/// * `left` - Zero-based index of the first character.
/// * `right` - Zero-based index of the second character.
///
/// # Safety / Validity
///
/// This function is intended for ASCII strings. For non-ASCII UTF-8 strings,
/// modifying arbitrary bytes directly may produce invalid UTF-8 sequences.
/// In production Rust code, prefers using `bytes.swap(left, right)` or `std::mem::swap`.
pub fn xor_swap_characters(bytes: &mut [u8], left: usize, right: usize) {
    // Bounds checking and empty slice validation
    if bytes.is_empty() || left >= bytes.len() || right >= bytes.len() {
        return;
    }

    // XOR swap fails if left == right because (x ^ x) evaluates to 0
    if left == right {
        return;
    }

    bytes[left] ^= bytes[right];
    bytes[right] ^= bytes[left];
    bytes[left] ^= bytes[right];
}

fn main() {
    let mut text = String::from("hello");

    println!("Before: {text}");

    // Mutably convert the String into a byte slice representation for in-place modification
    xor_swap_characters(unsafe { text.as_bytes_mut() }, 1, 4);

    println!("After:  {text}");
}


/*
run:

Before: hello
After:  holle

*/

 



answered Sep 30 by avibootz
...