multibase/
lib.rs

1//! # multibase
2//!
3//! Implementation of [multibase](https://github.com/multiformats/multibase) in Rust.
4
5#![deny(missing_docs)]
6#![cfg_attr(not(feature = "std"), no_std)]
7
8#[cfg(not(feature = "std"))]
9extern crate alloc;
10
11#[cfg(not(feature = "std"))]
12use alloc::{string::String, vec::Vec};
13
14mod base;
15mod encoding;
16mod error;
17mod impls;
18
19pub use self::base::Base;
20pub use self::error::{Error, Result};
21
22/// Decode the base string.
23///
24/// # Examples
25///
26/// ```
27/// use multibase::{Base, decode};
28///
29/// assert_eq!(
30///     decode("zCn8eVZg").unwrap(),
31///     (Base::Base58Btc, b"hello".to_vec())
32/// );
33/// ```
34pub fn decode<T: AsRef<str>>(input: T) -> Result<(Base, Vec<u8>)> {
35    let input = input.as_ref();
36    let code = input.chars().next().ok_or(Error::InvalidBaseString)?;
37    let base = Base::from_code(code)?;
38    let decoded = base.decode(&input[code.len_utf8()..])?;
39    Ok((base, decoded))
40}
41
42/// Encode with the given byte slice to base string.
43///
44/// # Examples
45///
46/// ```
47/// use multibase::{Base, encode};
48///
49/// assert_eq!(encode(Base::Base58Btc, b"hello"), "zCn8eVZg");
50/// ```
51pub fn encode<T: AsRef<[u8]>>(base: Base, input: T) -> String {
52    let input = input.as_ref();
53    let mut encoded = base.encode(input.as_ref());
54    encoded.insert(0, base.code());
55    encoded
56}