tp_runtime/
runtime_string.rs1use codec::{Encode, Decode};
19use tet_core::RuntimeDebug;
20use tetcore_std::vec::Vec;
21
22#[derive(Eq, RuntimeDebug, Clone)]
24pub enum RuntimeString {
25 Borrowed(&'static str),
27 #[cfg(feature = "std")]
29 Owned(String),
30 #[cfg(not(feature = "std"))]
32 Owned(Vec<u8>),
33}
34
35#[macro_export]
37macro_rules! format_runtime_string {
38 ($($args:tt)*) => {{
39 #[cfg(feature = "std")]
40 {
41 tp_runtime::RuntimeString::Owned(format!($($args)*))
42 }
43 #[cfg(not(feature = "std"))]
44 {
45 tp_runtime::RuntimeString::Owned(tetcore_std::alloc::format!($($args)*).as_bytes().to_vec())
46 }
47 }};
48}
49
50
51impl From<&'static str> for RuntimeString {
52 fn from(data: &'static str) -> Self {
53 Self::Borrowed(data)
54 }
55}
56
57#[cfg(feature = "std")]
58impl From<RuntimeString> for String {
59 fn from(string: RuntimeString) -> Self {
60 match string {
61 RuntimeString::Borrowed(data) => data.to_owned(),
62 RuntimeString::Owned(data) => data,
63 }
64 }
65}
66
67impl Default for RuntimeString {
68 fn default() -> Self {
69 Self::Borrowed(Default::default())
70 }
71}
72
73impl PartialEq for RuntimeString {
74 fn eq(&self, other: &Self) -> bool {
75 self.as_ref() == other.as_ref()
76 }
77}
78
79impl AsRef<[u8]> for RuntimeString {
80 fn as_ref(&self) -> &[u8] {
81 match self {
82 Self::Borrowed(val) => val.as_ref(),
83 Self::Owned(val) => val.as_ref(),
84 }
85 }
86}
87
88impl Encode for RuntimeString {
89 fn encode(&self) -> Vec<u8> {
90 match self {
91 Self::Borrowed(val) => val.encode(),
92 Self::Owned(val) => val.encode(),
93 }
94 }
95}
96
97impl Decode for RuntimeString {
98 fn decode<I: codec::Input>(value: &mut I) -> Result<Self, codec::Error> {
99 Decode::decode(value).map(Self::Owned)
100 }
101}
102
103#[cfg(feature = "std")]
104impl std::fmt::Display for RuntimeString {
105 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
106 match self {
107 Self::Borrowed(val) => write!(f, "{}", val),
108 Self::Owned(val) => write!(f, "{}", val),
109 }
110 }
111}
112
113#[cfg(feature = "std")]
114impl serde::Serialize for RuntimeString {
115 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
116 match self {
117 Self::Borrowed(val) => val.serialize(serializer),
118 Self::Owned(val) => val.serialize(serializer),
119 }
120 }
121}
122
123#[cfg(feature = "std")]
124impl<'de> serde::Deserialize<'de> for RuntimeString {
125 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
126 String::deserialize(de).map(Self::Owned)
127 }
128}
129
130#[macro_export]
132macro_rules! create_runtime_str {
133 ( $y:expr ) => {{ $crate::RuntimeString::Borrowed($y) }}
134}