sp_runtime/
runtime_string.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use alloc::vec::Vec;
19use codec::{Decode, Encode};
20use sp_core::RuntimeDebug;
21
22/// A string that wraps a `&'static str` in the runtime and `String`/`Vec<u8>` on decode.
23#[derive(Eq, RuntimeDebug, Clone)]
24pub enum RuntimeString {
25	/// The borrowed mode that wraps a `&'static str`.
26	Borrowed(&'static str),
27	/// The owned mode that wraps a `String`.
28	#[cfg(feature = "std")]
29	Owned(String),
30	/// The owned mode that wraps a `Vec<u8>`.
31	#[cfg(not(feature = "std"))]
32	Owned(Vec<u8>),
33}
34
35impl scale_info::TypeInfo for RuntimeString {
36	type Identity = str;
37
38	fn type_info() -> scale_info::Type {
39		Self::Identity::type_info()
40	}
41}
42
43/// Convenience macro to use the format! interface to get a `RuntimeString::Owned`
44#[macro_export]
45macro_rules! format_runtime_string {
46	($($args:tt)*) => {{
47		#[cfg(feature = "std")]
48		{
49			sp_runtime::RuntimeString::Owned(format!($($args)*))
50		}
51		#[cfg(not(feature = "std"))]
52		{
53			sp_runtime::RuntimeString::Owned($crate::format!($($args)*).as_bytes().to_vec())
54		}
55	}};
56}
57
58impl From<&'static str> for RuntimeString {
59	fn from(data: &'static str) -> Self {
60		Self::Borrowed(data)
61	}
62}
63
64impl<'a> TryFrom<&'a RuntimeString> for &'a str {
65	type Error = core::str::Utf8Error;
66	fn try_from(from: &'a RuntimeString) -> core::result::Result<&'a str, Self::Error> {
67		match from {
68			#[cfg(feature = "std")]
69			RuntimeString::Owned(string) => Ok(string.as_str()),
70			#[cfg(not(feature = "std"))]
71			RuntimeString::Owned(vec) => core::str::from_utf8(&vec),
72			RuntimeString::Borrowed(str) => Ok(str),
73		}
74	}
75}
76
77#[cfg(feature = "std")]
78impl From<RuntimeString> for String {
79	fn from(string: RuntimeString) -> Self {
80		match string {
81			RuntimeString::Borrowed(data) => data.to_owned(),
82			RuntimeString::Owned(data) => data,
83		}
84	}
85}
86
87impl Default for RuntimeString {
88	fn default() -> Self {
89		Self::Borrowed(Default::default())
90	}
91}
92
93impl PartialEq for RuntimeString {
94	fn eq(&self, other: &Self) -> bool {
95		self.as_ref() == other.as_ref()
96	}
97}
98
99impl AsRef<[u8]> for RuntimeString {
100	fn as_ref(&self) -> &[u8] {
101		match self {
102			Self::Borrowed(val) => val.as_ref(),
103			Self::Owned(val) => val.as_ref(),
104		}
105	}
106}
107
108#[cfg(feature = "std")]
109impl std::ops::Deref for RuntimeString {
110	type Target = str;
111
112	fn deref(&self) -> &str {
113		match self {
114			Self::Borrowed(val) => val,
115			Self::Owned(val) => val,
116		}
117	}
118}
119
120impl Encode for RuntimeString {
121	fn encode(&self) -> Vec<u8> {
122		match self {
123			Self::Borrowed(val) => val.encode(),
124			Self::Owned(val) => val.encode(),
125		}
126	}
127}
128
129impl Decode for RuntimeString {
130	fn decode<I: codec::Input>(value: &mut I) -> Result<Self, codec::Error> {
131		Decode::decode(value).map(Self::Owned)
132	}
133}
134
135#[cfg(feature = "std")]
136impl std::fmt::Display for RuntimeString {
137	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
138		match self {
139			Self::Borrowed(val) => write!(f, "{}", val),
140			Self::Owned(val) => write!(f, "{}", val),
141		}
142	}
143}
144
145#[cfg(feature = "serde")]
146impl serde::Serialize for RuntimeString {
147	fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
148		match self {
149			Self::Borrowed(val) => val.serialize(serializer),
150			Self::Owned(val) => val.serialize(serializer),
151		}
152	}
153}
154
155#[cfg(feature = "serde")]
156impl<'de> serde::Deserialize<'de> for RuntimeString {
157	fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
158		Ok(Self::Owned(serde::Deserialize::deserialize(de)?))
159	}
160}
161
162/// Create a const [`RuntimeString`].
163#[macro_export]
164macro_rules! create_runtime_str {
165	( $y:expr ) => {{
166		$crate::RuntimeString::Borrowed($y)
167	}};
168}