Skip to main content

xmtp_proto/traits/
short_hex.rs

1use crate::types::{GroupId, InstallationId};
2
3const SHORT_LEN: usize = 4;
4
5pub trait ShortHex {
6    fn short_hex(&self) -> String;
7}
8
9impl ShortHex for &[u8] {
10    fn short_hex(&self) -> String {
11        short_hex(self)
12    }
13}
14impl ShortHex for InstallationId {
15    fn short_hex(&self) -> String {
16        self.as_slice().short_hex()
17    }
18}
19impl ShortHex for GroupId {
20    fn short_hex(&self) -> String {
21        self.as_slice().short_hex()
22    }
23}
24impl ShortHex for Vec<u8> {
25    fn short_hex(&self) -> String {
26        self.as_slice().short_hex()
27    }
28}
29
30fn short_hex(bytes: &[u8]) -> String {
31    let len = SHORT_LEN.min(bytes.len());
32    hex::encode(&bytes[..len])
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_short_hex() {
41        let hex = "5bf078bd83995fe83092d93c5655f059";
42        let bytes = hex::decode(hex).unwrap();
43        let short_hex = short_hex(&bytes);
44
45        assert_eq!(short_hex.len(), SHORT_LEN * 2);
46        assert_eq!(hex[..short_hex.len()], short_hex);
47    }
48
49    #[test]
50    fn test_short_hex_group_id() {
51        let hex = "5bf078bd83995fe83092d93c5655f059";
52        let bytes = hex::decode(hex).unwrap();
53        let group_id = GroupId::try_from(bytes).unwrap();
54        assert_eq!(group_id.short_hex(), &hex[..SHORT_LEN * 2]);
55    }
56}