surrealcs_kernel/logging/messages/connections/
id.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! Defines basic functions for creating IDs for connections. These should be called once per connection
//! in the connection constructor and then passed to emitting actors.

/// Creates a connection ID based on the connection index and the current timestamp.
///
/// # Arguments
/// * `connection_index`: The index of the connection in the allocator
///
/// # Returns
/// A string representing the connection ID
pub fn create_id(connection_index: usize) -> String {
	let timestamp = chrono::Utc::now().timestamp().to_string();
	format!("{}-{}", connection_index, timestamp)
}

/// Gets the connection index from the connection ID.
///
/// # Arguments
/// * `id`: The connection ID
///
/// # Returns
/// The connection index
pub fn get_connection_index(id: &str) -> usize {
	let parts: Vec<&str> = id.split("-").collect();
	parts[0].parse::<usize>().unwrap()
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_create_id() {
		let id = create_id(1);
		assert_eq!(id.len(), 12);
		assert!(id.contains("1-"));
	}

	#[test]
	fn test_get_connection_index() {
		let id = create_id(1);
		let index = get_connection_index(&id);
		assert_eq!(index, 1);
	}
}