Add Pubkey::new_unique()/Hash::new_unique()

This commit is contained in:
Michael Vines
2020-10-22 16:42:08 -07:00
committed by mergify[bot]
parent b095a52027
commit 884d68ddcf
2 changed files with 36 additions and 4 deletions

View File

@@ -100,9 +100,20 @@ impl Hash {
self.0
}
/// New random hash value for tests and benchmarks.
/// unique Hash for tests and benchmarks.
pub fn new_unique() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static I: AtomicU64 = AtomicU64::new(1);
let mut b = [0u8; HASH_BYTES];
let i = I.fetch_add(1, Ordering::Relaxed);
b[0..8].copy_from_slice(&i.to_le_bytes());
Self::new(&b)
}
/// random hash value for tests and benchmarks.
#[cfg(not(feature = "program"))]
#[deprecated(since = "1.3.9", note = "Please use 'hash::new_rand' instead")]
#[deprecated(since = "1.3.9", note = "Please use 'Hash::new_unique' instead")]
pub fn new_rand<R: ?Sized>(rng: &mut R) -> Self
where
R: rand::Rng,
@@ -134,6 +145,11 @@ pub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {
mod tests {
use super::*;
#[test]
fn test_new_unique() {
assert!(Hash::new_unique() != Hash::new_unique());
}
#[test]
fn test_hash_fromstr() {
let hash = hash(&[1u8]);

View File

@@ -200,12 +200,23 @@ impl Pubkey {
}
#[cfg(not(feature = "program"))]
#[deprecated(since = "1.3.9", note = "Please use 'pubkey::new_rand' instead")]
#[deprecated(since = "1.3.9", note = "Please use 'Pubkey::new_unique' instead")]
pub fn new_rand() -> Self {
// Consider removing solana_sdk::pubkey::new_rand() entirely in the v1.5 or v1.6 timeframe
// Consider removing Pubkey::new_rand() entirely in the v1.5 or v1.6 timeframe
new_rand()
}
/// unique Pubkey for tests and benchmarks.
pub fn new_unique() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static I: AtomicU64 = AtomicU64::new(1);
let mut b = [0u8; 32];
let i = I.fetch_add(1, Ordering::Relaxed);
b[0..8].copy_from_slice(&i.to_le_bytes());
Self::new(&b)
}
pub fn to_bytes(self) -> [u8; 32] {
self.0
}
@@ -266,6 +277,11 @@ mod tests {
use super::*;
use std::{fs::remove_file, str::from_utf8};
#[test]
fn test_new_unique() {
assert!(Pubkey::new_unique() != Pubkey::new_unique());
}
#[test]
fn pubkey_fromstr() {
let pubkey = solana_sdk::pubkey::new_rand();