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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
//! This crate is a Base32 encoder/decoder library without padding.
//!
//! Intended to use to implement an Onion address encoder/decoder.
//! Using RFC 4648 Base32 alphabet,
//! but encoded string is lowercase by default.
//!
//! This crate does not support padding,
//! so the input length for the encode function is limited to multiple of 5
//! and the input length for the decode function is limited to multiple of 8.
//!
//! # Examples
//!
//! ```rust
//! use koibumi_base32 as base32;
//!
//! let test = base32::encode(b"hello")?;
//! let expected = "nbswy3dp";
//! assert_eq!(test, expected);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ```rust
//! use koibumi_base32 as base32;
//!
//! let test = base32::decode("nbswy3dp")?;
//! let expected = b"hello";
//! assert_eq!(test, expected);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#[macro_use]
extern crate lazy_static;

use std::fmt;

const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
const NOT_ALPHABET: u8 = ALPHABET.len() as u8;

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

fn is_alphabet(ch: char) -> bool {
    ALPHABET_INDEX[ch as usize] != NOT_ALPHABET
}

fn is_bytes_base32(bytes: &[u8]) -> bool {
    bytes.len() % 5 == 0
}

fn is_str_base32(str: &[char]) -> bool {
    if str.len() % 8 != 0 {
        return false;
    }
    for b in str {
        if !is_alphabet(*b) {
            return false;
        }
    }
    true
}

/// An error which can be returned when encoding a byte array into Base32 format.
///
/// This error is used as the error type for the [`encode`] function.
///
/// [`encode`]: fn.encode.html
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum EncodeError {
    /// The length of the input was not multiple of 5.
    /// The actual length of the input is returned
    /// as a payload of this variant.
    InvalidLength(usize),
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EncodeError::InvalidLength(len) => {
                write!(f, "length must be multiple of 5, but {}", len)
            }
        }
    }
}

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

fn to_ch(byte: u8) -> u8 {
    ALPHABET[(byte & 31) as usize]
}

/// Encodes byte array into Base32 string.
///
/// The input is arbitrary `[u8]` slice
/// and the output is lowercase `String`.
/// Using lowercase RFC4648 alphabet and can be used for Onion addresses.
/// Padding is not supported,
/// so if the length of the input is not multiple of 5,
/// an error will be returned.
///
/// # Examples
///
/// ```rust
/// use koibumi_base32 as base32;
///
/// let test = base32::encode(b"hello")?;
/// let expected = "nbswy3dp";
/// assert_eq!(test, expected);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn encode(bytes: impl AsRef<[u8]>) -> Result<String, EncodeError> {
    let bytes = bytes.as_ref();
    if !is_bytes_base32(bytes) {
        return Err(EncodeError::InvalidLength(bytes.len()));
    }
    let blocks = bytes.len() / 5;
    let mut r = vec![0; blocks * 8];
    let mut i = 0;
    let mut j = 0;
    for _ in 0..blocks {
        // 0      1      2     3      4      5     6      7
        // |xxxxx xxx|xx xxxxx x|xxxx xxxx|x xxxxx xx|xxx xxxxx|
        // 0         1          2         3          4

        r[j] = to_ch(bytes[i] >> 3);
        r[j + 1] = to_ch(bytes[i] << 2 | bytes[i + 1] >> 6);
        r[j + 2] = to_ch(bytes[i + 1] >> 1);
        r[j + 3] = to_ch(bytes[i + 1] << 4 | bytes[i + 2] >> 4);
        r[j + 4] = to_ch(bytes[i + 2] << 1 | bytes[i + 3] >> 7);
        r[j + 5] = to_ch(bytes[i + 3] >> 2);
        r[j + 6] = to_ch(bytes[i + 3] << 3 | bytes[i + 4] >> 5);
        r[j + 7] = to_ch(bytes[i + 4]);
        i += 5;
        j += 8;
    }
    Ok(String::from_utf8(r).unwrap())
}

/// An error which can be returned when decoding a Base32 encoded string.
///
/// This error is used as the error type for the [`decode`] function.
///
/// [`decode`]: fn.decode.html
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum DecodeError {
    /// The length of the input was not multiple of 8.
    /// The actual length of the input is returned as a payload of this variant.
    InvalidLength(usize),
    /// An invalid Base32 character was found.
    /// The actual character found invalid is returned
    /// as a payload of this variant.
    InvalidCharacter(char),
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DecodeError::InvalidLength(len) => {
                write!(f, "length must be multiple of 8, but {}", len)
            }
            DecodeError::InvalidCharacter(ch) => {
                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 DecodeError {}

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

/// Decodes Base32 string into byte array.
///
/// The input is Base32 encoded lowercase `str` reference
/// and the output is arbitrary `Vec<u8>`.
/// Using lowercase RFC4648 alphabet and can be used for Onion addresses.
/// Padding is not supported,
/// so if the length of the input is not multiple of 8,
/// an error will be returned.
///
/// # Examples
///
/// ```rust
/// use koibumi_base32 as base32;
///
/// let test = base32::decode("nbswy3dp")?;
/// let expected = b"hello";
/// assert_eq!(test, expected);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn decode(s: impl AsRef<str>) -> Result<Vec<u8>, DecodeError> {
    let s: Vec<char> = s.as_ref().chars().collect();
    if !is_str_base32(&s) {
        return Err(DecodeError::InvalidLength(s.len()));
    }
    let blocks = s.len() / 8;
    let mut r = vec![0; blocks * 5];
    let mut i = 0;
    let mut j = 0;
    for _ in 0..blocks {
        // 0         1          2         3          4
        // |xxxxx xxx|xx xxxxx x|xxxx xxxx|x xxxxx xx|xxx xxxxx|
        // 0      1      2     3      4      5     6      7

        r[j] = to_num(s[i])? << 3 | to_num(s[i + 1])? >> 2;
        r[j + 1] = to_num(s[i + 1])? << 6 | to_num(s[i + 2])? << 1 | to_num(s[i + 3])? >> 4;
        r[j + 2] = to_num(s[i + 3])? << 4 | to_num(s[i + 4])? >> 1;
        r[j + 3] = to_num(s[i + 4])? << 7 | to_num(s[i + 5])? << 2 | to_num(s[i + 6])? >> 3;
        r[j + 4] = to_num(s[i + 6])? << 5 | to_num(s[i + 7])?;
        i += 8;
        j += 5;
    }
    Ok(r)
}