Skip to content

Commit

Permalink
add lowest_pubkey_from_bin (#19617)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffwashington authored Sep 4, 2021
1 parent b3fae0a commit 7578db7
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion runtime/src/pubkey_bins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ impl PubkeyBinCalculator16 {
std::mem::size_of::<T>() * 8
}

fn log_2(x: u32) -> u32 {
pub fn log_2(x: u32) -> u32 {
assert!(x > 0);
Self::num_bits::<u32>() as u32 - x.leading_zeros() - 1
}
Expand All @@ -32,6 +32,15 @@ impl PubkeyBinCalculator16 {
let as_ref = pubkey.as_ref();
((as_ref[0] as usize * 256 + as_ref[1] as usize) as usize) >> self.shift_bits
}

pub fn lowest_pubkey_from_bin(&self, mut bin: usize, bins: usize) -> Pubkey {
assert!(bin < bins);
bin <<= self.shift_bits;
let mut pubkey = Pubkey::new(&[0; 32]);
pubkey.as_mut()[0] = (bin / 256) as u8;
pubkey.as_mut()[1] = (bin & 0xff) as u8;
pubkey
}
}

#[cfg(test)]
Expand All @@ -53,6 +62,12 @@ pub mod tests {
let bins = 2u32.pow(i);
let calc = PubkeyBinCalculator16::new(bins as usize);
assert_eq!(calc.shift_bits, 16 - i, "i: {}", i);
for bin in 0..bins {
assert_eq!(
bin as usize,
calc.bin_from_pubkey(&calc.lowest_pubkey_from_bin(bin as usize, bins as usize))
);
}
}
}

Expand Down

0 comments on commit 7578db7

Please sign in to comment.