ss58_registry/
registry.rs

1// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18include!(concat!(env!("OUT_DIR"), "/registry_gen.rs"));
19
20#[cfg(feature = "std")]
21impl std::fmt::Display for Ss58AddressFormatRegistry {
22	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
23		let lookup = PREFIX_TO_INDEX
24			.binary_search_by_key(&from_known_address_format(*self), |(prefix, _)| *prefix)
25			.expect("always be found");
26		let (_, idx) = PREFIX_TO_INDEX[lookup];
27		write!(f, "{}", ALL_SS58_ADDRESS_FORMAT_NAMES[idx])
28	}
29}
30
31impl TryFrom<Ss58AddressFormat> for Ss58AddressFormatRegistry {
32	type Error = ParseError;
33
34	fn try_from(x: Ss58AddressFormat) -> Result<Ss58AddressFormatRegistry, ParseError> {
35		PREFIX_TO_INDEX
36			.binary_search_by_key(&x.prefix(), |(prefix, _)| *prefix)
37			.map(|lookup| {
38				let (_, idx) = PREFIX_TO_INDEX[lookup];
39				ALL_SS58_ADDRESS_FORMATS[idx]
40			})
41			.map_err(|_| ParseError)
42	}
43}
44
45/// const function to convert [`Ss58AddressFormat`] to u16
46pub const fn from_known_address_format(x: Ss58AddressFormatRegistry) -> u16 {
47	x as u16
48}
49
50impl core::fmt::Debug for TokenRegistry {
51	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
52		let token: Token = (*self).into();
53		f.debug_struct("TokenRegistry")
54			.field("name", &token.name)
55			.field("decimals", &token.decimals)
56			.finish()
57	}
58}