Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created November 4, 2025 20:42
Show Gist options
  • Save rust-play/ab516638005b619a940a3f600449e9db to your computer and use it in GitHub Desktop.
Save rust-play/ab516638005b619a940a3f600449e9db to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// Only using standard library features for this illustrative concept,
// as the listed crates don't provide a direct, safe XOR-list implementation.
use std::ptr;
use std::mem;
// --- A simplified structure for an XOR-linked list node ---
struct Node {
pub value: u32,
// The "link" is the XOR of the *pointers* to the previous and next nodes.
// In a real implementation, this would involve unsafe pointer casting.
pub link: usize,
}
// --- Illustration of the core XOR-linking logic ---
fn main() {
println!("📦 XOR-Linked Memory Concept Demonstration 📦");
// 1. Setup - Create three nodes
// In a real scenario, these would be heap-allocated Boxed nodes.
let mut node_a = Node { value: 10, link: 0 };
let mut node_b = Node { value: 20, link: 0 };
let mut node_c = Node { value: 30, link: 0 };
// Get the memory addresses (pointers) as usize values
// WARNING: This is *highly* unsafe and non-portable in a real application!
// It's for demonstration only.
let ptr_a = &node_a as *const Node as usize;
let ptr_b = &mut node_b as *mut Node as usize; // Needs mut for link update
let ptr_c = &node_c as *const Node as usize;
println!("\nAddresses:");
println!("Node A Address: {:#x}", ptr_a);
println!("Node B Address: {:#x}", ptr_b);
println!("Node C Address: {:#x}", ptr_c);
// 2. Linking
// --- Link A -> B ---
// A's link = (0) XOR (Pointer to B)
node_a.link = 0 ^ ptr_b;
// --- Link B ---
// B's link = (Pointer to A) XOR (Pointer to C)
// We need 'mut' to modify B's link:
let node_b_mut = unsafe { &mut *(ptr_b as *mut Node) };
node_b_mut.link = ptr_a ^ ptr_c;
// --- Link C <- B ---
// C's link = (Pointer to B) XOR (0)
node_c.link = ptr_b ^ 0;
println!("\nLinks (XOR Pointers):");
println!("Node A Link (0 ^ B): {:#x}", node_a.link);
println!("Node B Link (A ^ C): {:#x}", node_b_mut.link);
println!("Node C Link (B ^ 0): {:#x}", node_c.link);
// 3. Traversal (Forward: A -> B -> C)
println!("\nTraversal (A -> B -> C):");
let mut current_ptr = ptr_a;
let mut prev_ptr = 0; // Previous is NULL (0) for the start node
while current_ptr != 0 {
let current_node = unsafe { &*(current_ptr as *const Node) };
println!(" - Value: {}", current_node.value);
// Calculate the next pointer: Next = Link XOR Previous
let next_ptr = current_node.link ^ prev_ptr;
// Move to the next node
prev_ptr = current_ptr;
current_ptr = next_ptr;
// Safety break for cycles, though none expected here
if current_ptr == ptr_a && prev_ptr != 0 { break; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment