tp_runtime/
runtime_string.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2020-2021 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 codec::{Encode, Decode};
19use tet_core::RuntimeDebug;
20use tetcore_std::vec::Vec;
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
35/// Convenience macro to use the format! interface to get a `RuntimeString::Owned`
36#[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/// Create a const [`RuntimeString`].
131#[macro_export]
132macro_rules! create_runtime_str {
133	( $y:expr ) => {{ $crate::RuntimeString::Borrowed($y) }}
134}