cypher/
display.rs

1// Set of libraries for privacy-preserving networking apps
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Written in 2019-2023 by
6//     Dr. Maxim Orlovsky <orlovsky@cyphernet.org>
7//
8// Copyright 2022-2023 Cyphernet DAO, Switzerland
9//
10// Licensed under the Apache License, Version 2.0 (the "License");
11// you may not use this file except in compliance with the License.
12// You may obtain a copy of the License at
13//
14//     http://www.apache.org/licenses/LICENSE-2.0
15//
16// Unless required by applicable law or agreed to in writing, software
17// distributed under the License is distributed on an "AS IS" BASIS,
18// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19// See the License for the specific language governing permissions and
20// limitations under the License.
21
22// TODO: Move to amplify crate
23
24use std::fmt::Display;
25
26use amplify::hex::ToHex;
27
28#[derive(Clone, Eq, PartialEq, Debug)]
29#[non_exhaustive]
30pub enum Encoding {
31    Base16,
32
33    #[cfg(feature = "multibase")]
34    Base32,
35
36    #[cfg(feature = "multibase")]
37    Base58,
38
39    #[cfg(feature = "multibase")]
40    Base64,
41
42    #[cfg(feature = "multibase")]
43    Multibase(multibase::Base),
44}
45
46impl Encoding {
47    pub fn encode(&self, data: &[u8]) -> String {
48        #[cfg(feature = "multibase")]
49        use multibase::{encode, Base};
50
51        match self {
52            Encoding::Base16 => data.to_hex(),
53
54            #[cfg(feature = "multibase")]
55            Encoding::Base32 => {
56                let mut s: String = encode(Base::Base32Lower, data);
57                s.remove(0);
58                s
59            }
60
61            #[cfg(feature = "multibase")]
62            Encoding::Base58 => {
63                let mut s: String = encode(Base::Base58Btc, data);
64                s.remove(0);
65                s
66            }
67
68            #[cfg(feature = "multibase")]
69            Encoding::Base64 => {
70                let mut s: String = encode(Base::Base64, data);
71                s.remove(0);
72                s
73            }
74
75            #[cfg(feature = "multibase")]
76            Encoding::Multibase(base) => encode(*base, data),
77        }
78    }
79}
80
81pub trait MultiDisplay<F> {
82    type Display: Display;
83
84    fn display(&self) -> Self::Display
85    where F: Default {
86        self.display_fmt(&default!())
87    }
88    fn display_fmt(&self, f: &F) -> Self::Display;
89}