From 1f5070e5694f41198503875764f4eb021816d7e6 Mon Sep 17 00:00:00 2001 From: sakridge Date: Fri, 10 Jul 2020 11:53:24 -0700 Subject: [PATCH] Add custom print for Bloom object (#10971) --- runtime/src/bloom.rs | 45 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/runtime/src/bloom.rs b/runtime/src/bloom.rs index 7f09d291d7..8b3f40aee5 100644 --- a/runtime/src/bloom.rs +++ b/runtime/src/bloom.rs @@ -3,6 +3,7 @@ use bv::BitVec; use fnv::FnvHasher; use rand::{self, Rng}; use serde::{Deserialize, Serialize}; +use std::fmt; use std::{cmp, hash::Hasher, marker::PhantomData}; /// Generate a stable hash of `self` for each `hash_index` @@ -11,7 +12,7 @@ pub trait BloomHashIndex { fn hash_at_index(&self, hash_index: u64) -> u64; } -#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, AbiExample)] +#[derive(Serialize, Deserialize, Default, Clone, PartialEq, AbiExample)] pub struct Bloom { pub keys: Vec, pub bits: BitVec, @@ -19,6 +20,30 @@ pub struct Bloom { _phantom: PhantomData, } +impl fmt::Debug for Bloom { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "Bloom {{ keys.len: {} bits.len: {} num_set: {} bits: ", + self.keys.len(), + self.bits.len(), + self.num_bits_set + )?; + const MAX_PRINT_BITS: u64 = 10; + for i in 0..std::cmp::min(MAX_PRINT_BITS, self.bits.len()) { + if self.bits.get(i) { + write!(f, "1")?; + } else { + write!(f, "0")?; + } + } + if self.bits.len() > MAX_PRINT_BITS { + write!(f, "..")?; + } + write!(f, " }}") + } +} + impl solana_sdk::sanitize::Sanitize for Bloom {} impl Bloom { @@ -162,4 +187,22 @@ mod test { //ensure min keys is 1 assert_eq!(Bloom::::num_keys(20f64, 1000f64) as u64, 1u64); } + + #[test] + fn test_debug() { + let mut b: Bloom = Bloom::new(3, vec![100]); + b.add(&Hash::default()); + assert_eq!( + format!("{:?}", b), + "Bloom { keys.len: 1 bits.len: 3 num_set: 1 bits: 001 }" + ); + + let mut b: Bloom = Bloom::new(1000, vec![100]); + b.add(&Hash::default()); + b.add(&hash(&[1, 2])); + assert_eq!( + format!("{:?}", b), + "Bloom { keys.len: 1 bits.len: 1000 num_set: 2 bits: 0000000000.. }" + ); + } }