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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
//! Generate Youtube-Like IDs with Rust.
//! 
//! ## Basic Usage
//!
//! ```rust
//! use alphaid::AlphaId;
//!
//! let alphaid = AlphaId::new();
//! assert_eq!(alphaid.encode(1350997667), b"90F7qb");
//! assert_eq!(alphaid.decode(b"90F7qb"), Ok(1350997667));
//! ```
//!
//! ## Padding
//! Specifies the minimum length of the encoded result.
//! 
//! ```rust
//! use alphaid::AlphaId;
//!
//! let alphaid = AlphaId::new();
//! assert_eq!(alphaid.encode(0), b"a");
//! assert_eq!(alphaid.decode(b"a"), Ok(0));
//!
//!
//! let alphaid = AlphaId::builder().pad(5).build();
//! assert_eq!(alphaid.encode(0), b"aaaab");
//! assert_eq!(alphaid.decode(b"aaaab"), Ok(0));
//! ```
//!
//! ## Charaters set
//! Sets the characters set. Default to `abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_`
//!
//! ```rust
//! use alphaid::AlphaId;
//! let alphaid = AlphaId::builder().pad(2)
//!     .chars("ABCDEFGHIJKLMNOPQRSTUVWXYZ".as_bytes().to_vec())
//!     .build();
//! assert_eq!(alphaid.encode(0), b"AB");
//! assert_eq!(alphaid.decode(b"AB"), Ok(0));
//! ```
//!
//!
//! ## Reference
//!
//! [Create Youtube-Like IDs](https://kvz.io/create-short-ids-with-php-like-youtube-or-tinyurl.html)
use std::collections::HashMap;

static DEFAULT_SEED: &'static str =
    "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";

#[derive(Debug, PartialEq)]
pub enum DecodeError {
    Overflow,
    UnexpectedChar,
}

/// A builder for a `AlphaId`.
pub struct Builder {
    chars: Option<Vec<u8>>,
    pad: Option<u32>,
}

impl Default for Builder {
    fn default() -> Self {
        Self {
            chars: None,
            pad: None,
        }
    }
}

impl Builder {
    /// Constructs a new `Builder`.
    ///
    /// Parameters are initialized with their default values.
    pub fn new() -> Self {
        Default::default()
    }

    /// Sets the characters set.
    /// 
    /// Default to `abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_`.
    ///
    /// # Panics
    /// 
    /// Panics if chars' size is less than `16`.
    pub fn chars(mut self, chars: Vec<u8>) -> Self {
        assert!(chars.len() > 16, "chars size must large than 16");
        self.chars = Some(chars);
        self
    }

    /// Sets the pad which specifies the minimum 
    /// length of the encoded result.
    ///
    /// Default to 1.
    ///
    /// # Panics
    ///
    /// Panics if pad is less than 0.
    pub fn pad(mut self, pad: u32) -> Self {
        assert!(pad > 0, "pad must large than 1");
        self.pad = Some(pad);
        self
    }

    /// Consumes the builder, returning a `AlphaId`.
    ///
    /// # Panics
    ///
    /// Panics if there are duplicate characters in chars.
    pub fn build(self) -> AlphaId {
        let chars = self
            .chars
            .unwrap_or_else(|| DEFAULT_SEED.as_bytes().to_vec());
        
        let index: HashMap<u8, u128> = chars
            .iter()
            .enumerate()
            .map(|(i, v)| (*v, i as u128))
            .collect();

        assert!(
            chars.len() == index.len(),
            "duplicate characters are not allowed"
        );
        let base = chars.len() as u128;
        let max_pow_i = (u128::max_value() as f64).log(base as f64) as u32;
        AlphaId {
            chars,
            index,
            base,
            pad: self.pad.unwrap_or(1),
            max_pow_i,
        }
    }
}

/// Used for encoding and decoding.
pub struct AlphaId {
    chars: Vec<u8>,
    index: HashMap<u8, u128>,
    base: u128,
    pad: u32,
    max_pow_i: u32,
}

impl AlphaId {
    /// Returns a builder type to configure a new `AlphaId`.
    pub fn builder() -> Builder {
        Builder::new()
    }

    /// Creates a new `AlphaId` with a default configuration.
    pub fn new() -> Self {
        Builder::new().build()
    }


    /// Encode the numbers.
    ///
    /// # Example
    /// 
    /// ```rust
    /// use alphaid::AlphaId;
    ///
    /// let alphaid = AlphaId::new();
    /// assert_eq!(alphaid.encode(0), b"a");
    /// assert_eq!(alphaid.encode(1), b"b");
    /// assert_eq!(alphaid.encode(1350997667), b"90F7qb");
    /// ```
    pub fn encode(&self, mut n: u128) -> Vec<u8> {
        let mut out = vec![];
        let mut i = 0;
        loop {
            i += 1;
            if self.pad > 1 && self.pad == i {
                n += 1;
            }

            if n == 0 {
                if i <= self.pad {
                    out.push(self.chars[0]);
                    continue;
                }
                break;
            }

            let a = n % self.base;
            out.push(self.chars[a as usize]);
            n = n / self.base;
        }

        out
    }

    /// Decode into numbers.
    ///
    /// # Example
    ///
    /// ```rust
    /// use alphaid::AlphaId;
    ///
    /// let alphaid = AlphaId::new();
    /// assert_eq!(alphaid.decode(b"a"), Ok(0));
    /// assert_eq!(alphaid.decode(b"b"), Ok(1));
    /// assert_eq!(alphaid.decode(b"90F7qb"), Ok(1350997667)); 
    ///```
    pub fn decode<V: AsRef<[u8]>>(&self, v: V) -> Result<u128, DecodeError> {
        let v = v.as_ref();
        let mut i = 0;
        let mut n = 0;
        let mut unpad = self.pad > 1;
        let mut prev = 0;

        while i < v.len() as u32 {
            match self.index.get(&v[i as usize]) {
                Some(t) => {
                    let mut x = *t as u128;

                    if unpad && i >= self.pad - 1 {
                        if i > 1 {
                            n += self.base.pow(i - 1) * (63 - prev);
                        }

                        match x {
                            0 => (),
                            _ => {
                                unpad = false;
                                x -= 1;
                            }
                        }
                    };

                    prev = *t;

                    if x == 0 {
                        i += 1;
                        continue;
                    }

                    if i > self.max_pow_i {
                        return Err(DecodeError::Overflow);
                    }

                    let pow = self.base.pow(i);
                    if u128::max_value() / pow < x {
                        return Err(DecodeError::Overflow);
                    }
                    let add = pow * x;
                    if u128::max_value() - n < add {
                        return Err(DecodeError::Overflow);
                    }
                    n += add;
                }
                None => return Err(DecodeError::UnexpectedChar),
            }
            i += 1;
        }

        Ok(n)
    }
}