common_access_token/
util.rs

1//! Utility functions for the Common Access Token library.
2//!
3//! This module provides various utility functions used throughout the library:
4//! - Base64 encoding and decoding
5//! - Random string generation
6//! - Time-related functions
7//!
8//! These functions are primarily used internally by other modules but
9//! may also be useful for applications working with CAT tokens.
10
11use base64::{engine::general_purpose, Engine as _};
12use rand::distr::Alphanumeric;
13use rand::Rng;
14
15/// Encodes binary data to base64 URL-safe format without padding
16pub fn to_base64_no_padding(data: &[u8]) -> String {
17    general_purpose::URL_SAFE_NO_PAD.encode(data)
18}
19
20/// Decodes base64 URL-safe format (with or without padding) to binary data
21pub fn from_base64_url(data: &str) -> Result<Vec<u8>, base64::DecodeError> {
22    general_purpose::URL_SAFE_NO_PAD.decode(data)
23}
24
25/// Generates a random hex string of the specified length
26pub fn generate_random_hex(len: usize) -> String {
27    let random_bytes: Vec<u8> = rand::rng().sample_iter(&Alphanumeric).take(len).collect();
28
29    hex::encode(&random_bytes[0..len / 2])
30}
31
32/// Gets the current time in seconds since the UNIX epoch
33pub fn current_time_secs() -> i64 {
34    std::time::SystemTime::now()
35        .duration_since(std::time::UNIX_EPOCH)
36        .unwrap_or_default()
37        .as_secs() as i64
38}