Skip to content

Commit

Permalink
added common generate_id() function and refactored a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
proycon committed Feb 20, 2024
1 parent 120b476 commit 43ba060
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/annotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ impl<'a> AnnotationBuilder<'a> {
Self::default()
}

/// Set an explicit ID. If you want to generate a random one, pass the result of `generate_id()` to the first parameter.
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = BuildItem::Id(id.into());
self
Expand Down
10 changes: 8 additions & 2 deletions src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ pub trait Storable: PartialEq + TypeInfo + Debug + Sized {
if let Some(intid) = self.handle() {
if let Some(idmap) = idmap {
loop {
let id = format!("{}{}", idmap.autoprefix, nanoid!());
let id = generate_id(&idmap.autoprefix, "");
let id_copy = id.clone();
if idmap.data.insert(id, intid).is_none() {
//checks for collisions (extremely unlikely)
Expand All @@ -530,7 +530,7 @@ pub trait Storable: PartialEq + TypeInfo + Debug + Sized {
}
}
// if the item is not bound or has no IDmap, we can't check collisions, but that's okay
self.with_id(format!("X{}", nanoid!()))
self.with_id(generate_id("X", ""))
}

/// Builder pattern to set the public ID
Expand Down Expand Up @@ -1683,3 +1683,9 @@ pub(crate) fn resolve_temp_id(id: &str) -> Option<usize> {
}
None
}

/// Generate an ID with a random 21-byte and ID/URI-safe component
/// This does no collision check (but they will be *extremely* unlikely)
pub fn generate_id(prefix: &str, suffix: &str) -> String {
format!("{}{}{}", prefix, nanoid!(), suffix)
}

0 comments on commit 43ba060

Please sign in to comment.