Skip to main content

oxabl_cache_format/
text_ids.rs

1//! Text forms of ids: `c_` and `t_` ids, and request ids.
2
3use crate::base32;
4use crate::error::{FormatError, Result};
5use crate::ids::{CacheId, RequestId, TenantId};
6
7fn with_prefix(prefix: &str, bytes: &[u8]) -> String {
8    format!("{prefix}{}", base32::encode(bytes))
9}
10
11fn strip<'a>(prefix: &str, s: &'a str) -> Result<&'a str> {
12    s.strip_prefix(prefix)
13        .ok_or(FormatError::Invalid("id prefix"))
14}
15
16impl CacheId {
17    /// `c_` and 26 base32 characters.
18    pub fn to_text(&self) -> String {
19        with_prefix("c_", &self.0)
20    }
21
22    pub fn from_text(s: &str) -> Result<Self> {
23        base32::decode(strip("c_", s)?).map(Self)
24    }
25}
26
27impl TenantId {
28    /// `t_` and 26 base32 characters.
29    pub fn to_text(&self) -> String {
30        with_prefix("t_", &self.0)
31    }
32
33    pub fn from_text(s: &str) -> Result<Self> {
34        base32::decode(strip("t_", s)?).map(Self)
35    }
36}
37
38impl RequestId {
39    /// 26 base32 characters.
40    pub fn to_text(&self) -> String {
41        base32::encode(&self.0)
42    }
43
44    pub fn from_text(s: &str) -> Result<Self> {
45        base32::decode(s).map(Self)
46    }
47}