diff --git a/Cargo.lock b/Cargo.lock index 493e304e..6c0e653a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5285,6 +5285,7 @@ dependencies = [ "arrayvec", "axum", "axum-extra", + "base64", "bytes", "bytesize", "cargo_toml", diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 0bb22988..390ddb29 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -55,6 +55,7 @@ argon2.workspace = true arrayvec.workspace = true axum.workspace = true axum-extra.workspace = true +base64.workspace = true bytes.workspace = true bytesize.workspace = true cargo_toml.workspace = true diff --git a/src/core/utils/rand.rs b/src/core/utils/rand.rs index e627fbbc..1346d708 100644 --- a/src/core/utils/rand.rs +++ b/src/core/utils/rand.rs @@ -5,6 +5,7 @@ use std::{ use arrayvec::ArrayString; use rand::{Rng, seq::SliceRandom, thread_rng}; +use ruma::OwnedEventId; pub fn shuffle(vec: &mut [T]) { let mut rng = thread_rng(); @@ -31,6 +32,29 @@ pub fn string_array() -> ArrayString { ret } +#[must_use] +pub fn event_id() -> OwnedEventId { + use base64::{ + Engine, + alphabet::URL_SAFE, + engine::{GeneralPurpose, general_purpose::NO_PAD}, + }; + + let mut binary: [u8; 32] = [0; _]; + thread_rng().fill(&mut binary); + + let mut encoded: [u8; 43] = [0; _]; + GeneralPurpose::new(&URL_SAFE, NO_PAD) + .encode_slice(binary, &mut encoded) + .expect("Failed to encode binary to base64"); + + let event_id: &str = str::from_utf8(&encoded) + .expect("Failed to convert array of base64 bytes to valid utf8 str"); + + OwnedEventId::from_parts('$', event_id, None) + .expect("Failed to generate valid random event_id") +} + #[must_use] pub fn truncate_string(mut str: String, range: Range) -> String { let len = thread_rng()