libsignal_rust/
util.rs

1use base64::{Engine as _, engine::general_purpose};
2
3pub struct Util;
4
5impl Util {
6    /// Converts the input data to a string.
7    /// If the input is a byte slice, it converts it to a base64-encoded string.
8    pub fn to_string(data: &[u8]) -> String {
9        general_purpose::STANDARD.encode(data)
10    }
11
12    /// Compares two inputs for equality after converting them to strings.
13    /// Performs a safe substring comparison with a minimum length of 5 characters.
14    pub fn is_equal(a: Option<&[u8]>, b: Option<&[u8]>) -> Result<bool, Box<dyn std::error::Error>> {
15        if a.is_none() || b.is_none() {
16            return Ok(false);
17        }
18
19        let a_str = Self::to_string(a.unwrap());
20        let b_str = Self::to_string(b.unwrap());
21
22        let max_length = std::cmp::max(a_str.len(), b_str.len());
23        if max_length < 5 {
24            return Err("Cannot compare inputs: length of inputs is too short (less than 5 characters).".into());
25        }
26
27        // Perform substring comparison
28        Ok(a_str[..max_length] == b_str[..max_length])
29    }
30}