Skip to content

Commit 2363ee6

Browse files
committed
database: add Events::force_insert
Signed-off-by: Yuki Kishimoto <[email protected]>
1 parent 8c3a3bb commit 2363ee6

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@
9292
* nostr: impl `FromIterator<Tag>` for `Tags` ([Yuki Kishimoto])
9393
* nostr: add `EventDeletionRequest` struct ([Yuki Kishimoto])
9494
* nostr: add `notifications` field to NIP47 `GetInfoResponse` ([Yuki Kishimoto])
95+
* database: add `Events::force_insert` ([Yuki Kishimoto])
9596
* pool: event verification cache ([Yuki Kishimoto])
9697
* pool: add `AdmitPolicy` trait ([Yuki Kishimoto])
9798
* ffi: add Mac Catalyst support in Swift package ([Yuki Kishimoto])

crates/nostr-database/src/collections/events.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,22 @@ impl Events {
7070
/// Insert [`Event`]
7171
///
7272
/// If the set did not previously contain an equal value, `true` is returned.
73+
/// If the collection is full, the older events will be discarded.
74+
/// Use [`Events::force_insert`] to always make sure the event is inserted.
7375
#[inline]
7476
pub fn insert(&mut self, event: Event) -> bool {
7577
self.set.insert(event).inserted
7678
}
7779

80+
/// Force insert [`Event`]
81+
///
82+
/// Use [`Events::insert`] to respect the max collection capacity (if any).
83+
/// If the collection capacity is full, this method will increase it.
84+
#[inline]
85+
pub fn force_insert(&mut self, event: Event) -> bool {
86+
self.set.force_insert(event).inserted
87+
}
88+
7889
/// Insert events
7990
#[inline]
8091
pub fn extend<I>(&mut self, events: I)

crates/nostr-database/src/collections/tree.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,28 @@ where
237237
}
238238
}
239239

240+
/// Force insert the value
241+
///
242+
/// If the capacity is full, automatically increases the capacity.
243+
pub fn force_insert(&mut self, value: T) -> InsertResult<T> {
244+
let inserted: bool = self.set.insert(value);
245+
246+
// If successfully inserted, check if the capacity must be increased
247+
if inserted {
248+
if let Capacity::Bounded { max, .. } = self.capacity {
249+
if self.set.len() >= max {
250+
self.capacity = Capacity::bounded(max + 1);
251+
}
252+
}
253+
}
254+
255+
// Insert value
256+
InsertResult {
257+
inserted,
258+
pop: None,
259+
}
260+
}
261+
240262
/// Extend with values
241263
pub fn extend<I>(&mut self, values: I)
242264
where

0 commit comments

Comments
 (0)