solana_program/
slot_hashes.rs1pub use crate::clock::Slot;
10use {
11 crate::hash::Hash,
12 std::{
13 iter::FromIterator,
14 ops::Deref,
15 sync::atomic::{AtomicUsize, Ordering},
16 },
17};
18
19pub const MAX_ENTRIES: usize = 512; static NUM_ENTRIES: AtomicUsize = AtomicUsize::new(MAX_ENTRIES);
24
25pub fn get_entries() -> usize {
26 NUM_ENTRIES.load(Ordering::Relaxed)
27}
28
29pub fn set_entries_for_tests_only(entries: usize) {
30 NUM_ENTRIES.store(entries, Ordering::Relaxed);
31}
32
33pub type SlotHash = (Slot, Hash);
34
35#[repr(C)]
36#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default)]
37pub struct SlotHashes(Vec<SlotHash>);
38
39impl SlotHashes {
40 pub fn add(&mut self, slot: Slot, hash: Hash) {
41 match self.binary_search_by(|(probe, _)| slot.cmp(probe)) {
42 Ok(index) => (self.0)[index] = (slot, hash),
43 Err(index) => (self.0).insert(index, (slot, hash)),
44 }
45 (self.0).truncate(get_entries());
46 }
47 pub fn position(&self, slot: &Slot) -> Option<usize> {
48 self.binary_search_by(|(probe, _)| slot.cmp(probe)).ok()
49 }
50 #[allow(clippy::trivially_copy_pass_by_ref)]
51 pub fn get(&self, slot: &Slot) -> Option<&Hash> {
52 self.binary_search_by(|(probe, _)| slot.cmp(probe))
53 .ok()
54 .map(|index| &self[index].1)
55 }
56 pub fn new(slot_hashes: &[SlotHash]) -> Self {
57 let mut slot_hashes = slot_hashes.to_vec();
58 slot_hashes.sort_by(|(a, _), (b, _)| b.cmp(a));
59 Self(slot_hashes)
60 }
61 pub fn slot_hashes(&self) -> &[SlotHash] {
62 &self.0
63 }
64}
65
66impl FromIterator<(Slot, Hash)> for SlotHashes {
67 fn from_iter<I: IntoIterator<Item = (Slot, Hash)>>(iter: I) -> Self {
68 Self(iter.into_iter().collect())
69 }
70}
71
72impl Deref for SlotHashes {
73 type Target = Vec<SlotHash>;
74 fn deref(&self) -> &Self::Target {
75 &self.0
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use {super::*, crate::hash::hash};
82
83 #[test]
84 fn test() {
85 let mut slot_hashes = SlotHashes::new(&[(1, Hash::default()), (3, Hash::default())]);
86 slot_hashes.add(2, Hash::default());
87 assert_eq!(
88 slot_hashes,
89 SlotHashes(vec![
90 (3, Hash::default()),
91 (2, Hash::default()),
92 (1, Hash::default()),
93 ])
94 );
95
96 let mut slot_hashes = SlotHashes::new(&[]);
97 for i in 0..MAX_ENTRIES + 1 {
98 slot_hashes.add(
99 i as u64,
100 hash(&[(i >> 24) as u8, (i >> 16) as u8, (i >> 8) as u8, i as u8]),
101 );
102 }
103 for i in 0..MAX_ENTRIES {
104 assert_eq!(slot_hashes[i].0, (MAX_ENTRIES - i) as u64);
105 }
106
107 assert_eq!(slot_hashes.len(), MAX_ENTRIES);
108 }
109}