1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
//! This crate is a Base58 encoder/decoder library.
//!
//! The library is intended to be used to implement a [Bitmessage](https://bitmessage.org/) address encoder/decoder.
//!
//! # Examples
//!
//! ```rust
//! use koibumi_base58 as base58;
//!
//! let test = base58::encode(b"hello");
//! let expected = "Cn8eVZg";
//! assert_eq!(test, expected);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ```rust
//! use koibumi_base58 as base58;
//!
//! let test = base58::decode("Cn8eVZg")?;
//! let expected = b"hello";
//! assert_eq!(test, expected);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#![deny(unsafe_code)]
#![warn(missing_docs)]

#[macro_use]
extern crate lazy_static;

use std::{convert::TryInto, fmt};

use num_bigint::{BigUint, ToBigUint};
use num_integer::Integer;
use num_traits::Zero;

const ALPHABET: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const INVALID: u8 = ALPHABET.len() as u8;

lazy_static! {
    static ref ALPHABET_INDEX: [u8; 0x100] = {
        let mut index = [INVALID; 0x100];
        for i in 0..ALPHABET.len() {
            index[ALPHABET[i] as usize] = i as u8;
        }
        index
    };
}

/// Encodes byte array into Base58 string.
///
/// # Examples
///
/// ```rust
/// use koibumi_base58 as base58;
///
/// let test = base58::encode(b"hello");
/// let expected = "Cn8eVZg";
/// assert_eq!(test, expected);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn encode(bytes: impl AsRef<[u8]>) -> String {
    let bytes = bytes.as_ref();
    if bytes.is_empty() {
        return String::with_capacity(0);
    }
    let mut n = BigUint::from_bytes_be(bytes);
    if n == Zero::zero() {
        return String::from_utf8(vec![ALPHABET[0]]).unwrap();
    }
    let mut list: Vec<u8> = Vec::new();
    let base = ALPHABET.len().to_biguint().unwrap();
    while n != Zero::zero() {
        let (q, r) = n.div_mod_floor(&base);
        list.push(r.try_into().unwrap());
        n = q;
    }
    let mut s = Vec::new();
    for i in list.iter().rev() {
        s.push(ALPHABET[*i as usize]);
    }
    String::from_utf8(s).unwrap()
}

#[test]
fn test_encode() {
    assert_eq!(encode(b""), "");
}

/// Indicates that an invalid Base58 character was found.
///
/// This error is used as the error type for the [`decode`] function.
///
/// [`decode`]: fn.decode.html
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct InvalidCharacter(char);

impl InvalidCharacter {
    /// Returns the actual character found invalid.
    pub fn char(&self) -> char {
        self.0
    }
}

impl fmt::Display for InvalidCharacter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ch = self.0;
        let code = u32::from(ch);
        if ch.is_control() {
            write!(f, "invalid character ({:#08x}) found", code)
        } else {
            write!(f, "invalid character '{}' ({:#08x}) found", ch, code)
        }
    }
}

impl std::error::Error for InvalidCharacter {}

fn to_num(ch: char) -> Result<u8, InvalidCharacter> {
    let i = ch as usize;
    if i > 0xff {
        return Err(InvalidCharacter(ch));
    }
    let v = ALPHABET_INDEX[i];
    if v == INVALID {
        Err(InvalidCharacter(ch))
    } else {
        Ok(v)
    }
}

/// Decodes Base58 string into byte array.
///
/// # Examples
///
/// ```rust
/// use koibumi_base58 as base58;
///
/// let test = base58::decode("Cn8eVZg")?;
/// let expected = b"hello";
/// assert_eq!(test, expected);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn decode(s: impl AsRef<str>) -> Result<Vec<u8>, InvalidCharacter> {
    let s = s.as_ref();
    if s.is_empty() {
        return Ok(Vec::with_capacity(0));
    }
    let base = ALPHABET.len();
    let mut n: BigUint = Zero::zero();
    for c in s.chars() {
        n *= base;
        n += to_num(c)?;
    }
    Ok(n.to_bytes_be())
}

#[test]
fn test_decode() {
    assert_eq!(decode("").unwrap(), b"");
}