starberry_lib/lib.rs
1use percent_encoding::{percent_decode, percent_encode, NON_ALPHANUMERIC};
2use rand::Rng;
3
4/// Encodes a string for URL safety and returns an owned `String`
5///
6/// # Example
7/// ```
8/// let encoded = encode_url_owned("Hello World!");
9/// assert_eq!(encoded, "Hello%20World%21");
10/// ```
11pub fn encode_url_owned(input: &str) -> String {
12 percent_encode(input.as_bytes(), NON_ALPHANUMERIC).to_string()
13}
14
15/// Encodes a string in place for URL safety
16///
17/// # Example
18/// ```
19/// let mut s = String::from("Hello World!");
20/// encode_url(&mut s);
21/// assert_eq!(s, "Hello%20World%21");
22/// ```
23pub fn encode_url(input: &mut String) {
24 let encoded = encode_url_owned(input);
25 *input = encoded;
26}
27
28/// Decodes a URL-encoded string and returns an owned `String`.
29///
30/// # Arguments
31///
32/// * `input` - A URL-encoded string as a `&str`.
33///
34/// # Returns
35///
36/// A new `String` containing the decoded value.
37pub fn decode_url_owned(input: &str) -> String {
38 percent_decode(input.as_bytes())
39 .decode_utf8_lossy()
40 .into_owned()
41}
42
43/// Decodes a URL-encoded string in place by updating the provided `String`.
44///
45/// # Arguments
46///
47/// * `input` - A mutable reference to a `String` holding a URL-encoded value.
48/// After the call, it will contain the decoded version.
49pub fn decode_url(input: &mut String) {
50 let decoded = decode_url_owned(input);
51 *input = decoded;
52}
53
54/// Generates a random string of the specified length using printable ASCII characters.
55pub fn random_string(length: usize) -> String {
56 let mut rng = rand::rng();
57 let bytes: Vec<u8> = (0..length).map(|_| rng.random_range(33..127)).collect();
58 String::from_utf8(bytes).unwrap()
59}
60
61
62pub fn random_alphanumeric_string(length: usize) -> String {
63 const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
64 let mut rng = rand::thread_rng();
65 (0..length)
66 .map(|_| {
67 let idx = rng.gen_range(0..CHARSET.len());
68 CHARSET[idx] as char
69 })
70 .collect()
71}
72