m10_sdk/types/
public_key.rs1use serde::de::Error;
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3use std::str::FromStr;
4
5#[derive(Debug, Clone, Eq, PartialEq)]
6pub struct PublicKey(pub Vec<u8>);
7
8impl PublicKey {
9 pub fn to_vec(&self) -> Vec<u8> {
10 self.0.clone()
11 }
12}
13
14#[cfg(feature = "format")]
15impl std::fmt::Display for PublicKey {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 write!(f, "{}", base64::encode(&self.0))
18 }
19}
20
21impl Serialize for PublicKey {
22 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
23 serializer.collect_str(&base64::display::Base64Display::with_config(
24 &self.0,
25 base64::STANDARD,
26 ))
27 }
28}
29
30impl<'de> Deserialize<'de> for PublicKey {
31 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
32 struct Vis;
33 impl serde::de::Visitor<'_> for Vis {
34 type Value = PublicKey;
35
36 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
37 formatter.write_str("a base64 string")
38 }
39
40 fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
41 base64::decode(v).map(PublicKey).map_err(Error::custom)
42 }
43 }
44 deserializer.deserialize_str(Vis)
45 }
46}
47
48impl FromStr for PublicKey {
49 type Err = base64::DecodeError;
50
51 fn from_str(s: &str) -> Result<Self, Self::Err> {
52 let key = base64::decode(s)?;
53 Ok(Self(key))
54 }
55}
56
57impl From<PublicKey> for Vec<u8> {
58 fn from(val: PublicKey) -> Self {
59 val.0
60 }
61}