ultimate_common/
string.rs

1use crate::{Error, Result};
2use base64ct::{Base64UrlUnpadded, Encoding};
3use rand::{distributions::Alphanumeric, thread_rng, Rng};
4use serde::{de::Visitor, Deserializer, Serializer};
5
6pub fn repeat_str(s: &str, n: usize) -> String {
7  let mut v = String::with_capacity(s.len() * n);
8  for _ in 0..n {
9    v.push_str(s);
10  }
11  v
12}
13
14pub fn repeat_char(c: char, n: usize) -> String {
15  let mut v = String::with_capacity(n);
16  for _ in 0..n {
17    v.push(c);
18  }
19  v
20}
21
22pub fn random_string(n: usize) -> String {
23  thread_rng().sample_iter(&Alphanumeric).take(n).map(char::from).collect()
24}
25
26pub fn b64u_encode(content: impl AsRef<[u8]>) -> String {
27  Base64UrlUnpadded::encode_string(content.as_ref())
28}
29
30pub fn b64u_decode(b64u: &str) -> Result<Vec<u8>> {
31  Base64UrlUnpadded::decode_vec(b64u).map_err(|_| Error::FailToB64uDecode(format!("Input string: {b64u}")))
32}
33
34pub fn b64u_decode_to_string(b64u: &str) -> Result<String> {
35  b64u_decode(b64u)
36    .ok()
37    .and_then(|r| String::from_utf8(r).ok())
38    .ok_or(Error::FailToB64uDecode(format!("Input string: {b64u}")))
39}
40
41pub fn deser_str_to_vecu8<'de, D>(d: D) -> core::result::Result<Vec<u8>, D::Error>
42where
43  D: Deserializer<'de>,
44{
45  struct StrToVecU8;
46  impl<'d> Visitor<'d> for StrToVecU8 {
47    type Value = Vec<u8>;
48
49    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
50      formatter.write_str("expect 'str'.")
51    }
52
53    fn visit_str<E>(self, v: &str) -> core::result::Result<Self::Value, E>
54    where
55      E: serde::de::Error,
56    {
57      Ok(v.as_bytes().into())
58    }
59  }
60
61  d.deserialize_str(StrToVecU8)
62}
63
64pub fn ser_vecu8_to_str<S>(v: &[u8], s: S) -> core::result::Result<S::Ok, S::Error>
65where
66  S: Serializer,
67{
68  let string = std::str::from_utf8(v).unwrap();
69  s.serialize_str(string)
70}
71
72/// 对需要保密的数据进行脱敏
73pub fn ser_str_secret<S>(v: &str, s: S) -> core::result::Result<S::Ok, S::Error>
74where
75  S: Serializer,
76{
77  s.serialize_str(v)
78}