Skip to main content

solana_pubkey_compare/
lib.rs

1#![allow(unexpected_cfgs)]
2#![feature(asm_experimental_arch)]
3#![doc = include_str!("../README.md")]
4
5unsafe extern "C" {
6    fn __solana_pubkey_compare__fast_eq(lhs_ptr: *const u8, rhs_ptr: *const u8) -> bool;
7}
8
9/// High-performance Solana public key comparison library
10///
11/// This crate provides ultra-fast public key comparison for Solana blockchain programs,
12/// achieving significant performance improvements through hand-optimized BPF assembly.
13///
14/// ## Performance
15///
16/// - **Assembly implementation**: 19 compute units on Solana BPF
17/// - **Standard comparison**: 28 compute units on Solana BPF
18/// - **Improvement**: ~32% reduction in compute units
19///
20/// ## Features
21///
22/// - Zero dependencies and `#[no_std]` compatible
23/// - Hand-optimized BPF assembly for Solana runtime
24/// - Automatic fallback to standard comparison for native testing
25/// - Generic interface supporting any 32-byte key types
26/// - Compile-time safety with Rust's type system
27///
28/// ## Usage
29///
30/// ```rust
31/// use solana_pubkey_compare::fast_eq;
32/// use solana_program::pubkey::Pubkey;
33///
34/// // Compare Solana Pubkeys
35/// let key1 = Pubkey::new_unique();
36/// let key2 = Pubkey::new_unique();
37///
38/// if fast_eq(&key1, &key2) {
39///     // Keys are equal
40/// }
41///
42/// // Works with any 32-byte types
43/// let bytes1: [u8; 32] = [0; 32];
44/// let bytes2: [u8; 32] = [1; 32];
45/// assert!(!fast_eq(&bytes1, &bytes2));
46/// ```
47///
48/// ## Implementation Details
49///
50/// The assembly implementation performs parallel 64-bit comparisons:
51/// 1. Loads four 8-byte chunks from each key simultaneously
52/// 2. Uses BPF conditional jumps for early exit on first mismatch
53/// 3. Minimizes instruction count and memory access overhead
54///
55/// On native platforms, falls back to the standard `PartialEq` implementation
56/// for compatibility with testing and development workflows.
57
58
59/// Ultra-fast public key equality comparison using optimized BPF assembly
60///
61/// This function provides maximum performance for comparing 32-byte public keys
62/// on Solana's BPF runtime. It uses hand-crafted assembly that performs four
63/// parallel 64-bit comparisons with early exit on first mismatch.
64///
65/// # Performance
66///
67/// - **On Solana BPF**: 19 compute units (32% faster than standard comparison)
68/// - **On native**: Falls back to `PartialEq` for testing compatibility
69///
70/// # Examples
71///
72/// ```rust
73/// use solana_pubkey_compare::fast_eq;
74/// use solana_program::pubkey::Pubkey;
75///
76/// let pubkey1 = Pubkey::new_unique();
77/// let pubkey2 = Pubkey::new_unique();
78///
79/// // Fast comparison - uses assembly on Solana BPF
80/// if fast_eq(&pubkey1, &pubkey2) {
81///     // Handle equal keys
82/// }
83///
84/// // Works with any 32-byte array-like types
85/// let array1 = [1u8; 32];
86/// let array2 = [1u8; 32];
87/// assert!(fast_eq(&array1, &array2));
88/// ```
89///
90/// # Type Requirements
91///
92/// The generic type `T` must implement:
93/// - `AsRef<[u8]>` - For accessing the underlying byte data
94/// - `PartialEq` - For the native fallback implementation
95///
96/// # Safety
97///
98/// This function is safe to call. Internally it uses unsafe code to cast
99/// references to raw pointers for the assembly function, but all safety
100/// invariants are maintained:
101///
102/// - References are valid for the duration of the call
103/// - Data alignment is handled by the BPF runtime
104/// - No memory is mutated - this is a pure comparison
105///
106/// # Implementation Notes
107///
108/// The assembly implementation (`cmp_pubkey_eq.s`) performs:
109/// 1. Four 64-bit memory loads (8 bytes each)
110/// 2. Four conditional comparisons with early exit
111/// 3. Single return instruction with cmp result
112///
113/// This eliminates the overhead of Rust's slice comparison and provides
114/// direct control over the BPF instruction sequence.
115#[inline(always)]
116pub fn fast_eq<T>(lhs: &T, rhs: &T) -> bool
117where
118    T: AsRef<[u8]> + PartialEq,
119{
120    #[cfg(target_os = "solana")]
121    unsafe {
122        __solana_pubkey_compare__fast_eq(
123            lhs as *const _ as *const u8,
124            rhs as *const _ as *const u8)
125    }
126
127    #[cfg(not(target_os = "solana"))]
128    {
129        lhs == rhs
130    }
131}