Skip to main content

wechat_protocol/
sticker_id.rs

1//! Validated identities shared by sticker callers and account operations.
2use anyhow::{ensure, Result};
3use serde::{Deserialize, Serialize};
4use std::{fmt, str::FromStr};
5/// Canonical lowercase MD5 identity of one sticker original.
6#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
7#[serde(try_from = "String", into = "String")]
8pub struct StickerId(String);
9impl StickerId {
10    /// Validate and normalize a 32-character hexadecimal content identity.
11    pub fn parse(value: impl AsRef<str>) -> Result<Self> {
12        let value = value.as_ref();
13        ensure!(
14            value.len() == 32 && value.bytes().all(|b| b.is_ascii_hexdigit()),
15            "invalid_sticker_id"
16        );
17        Ok(Self(value.to_ascii_lowercase()))
18    }
19    /// Borrow the canonical content identity.
20    pub fn as_str(&self) -> &str {
21        &self.0
22    }
23}
24/// Opaque official product identity, independent of account membership.
25#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
26#[serde(try_from = "String", into = "String")]
27pub struct StickerPackId(String);
28impl StickerPackId {
29    /// Validate a nonempty bounded product identity without interpreting its spelling.
30    pub fn parse(value: impl AsRef<str>) -> Result<Self> {
31        let value = value.as_ref();
32        ensure!(
33            !value.is_empty() && value.len() <= 1024 && !value.chars().any(char::is_control),
34            "invalid_sticker_pack_id"
35        );
36        Ok(Self(value.into()))
37    }
38    /// Borrow the original product identity.
39    pub fn as_str(&self) -> &str {
40        &self.0
41    }
42}
43macro_rules! identity_traits {
44    ($kind:ty) => {
45        impl FromStr for $kind {
46            type Err = anyhow::Error;
47            fn from_str(value: &str) -> Result<Self> {
48                Self::parse(value)
49            }
50        }
51        impl TryFrom<String> for $kind {
52            type Error = anyhow::Error;
53            fn try_from(value: String) -> Result<Self> {
54                Self::parse(value)
55            }
56        }
57        impl From<$kind> for String {
58            fn from(value: $kind) -> Self {
59                value.0
60            }
61        }
62        impl AsRef<str> for $kind {
63            fn as_ref(&self) -> &str {
64                self.as_str()
65            }
66        }
67        impl std::ops::Deref for $kind {
68            type Target = str;
69            fn deref(&self) -> &str {
70                self.as_str()
71            }
72        }
73        impl fmt::Display for $kind {
74            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75                f.write_str(self.as_str())
76            }
77        }
78    };
79}
80identity_traits!(StickerId);
81identity_traits!(StickerPackId);