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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// License: see LICENSE file at root directory of `master` branch

//! # An implementation of Base64 - <https://en.wikipedia.org/wiki/Base64>
//!
//! # Project
//!
//! - Repository: <https://bitbucket.org/haibison/debt64>
//! - License: Nice License 1.0.0 _(see LICENSE file at root directory of `master` branch)_
//! - _This project follows [Semantic Versioning 2.0.0]_
//!
//! ---
//!
//! # Features
//!
//! ## No debts (no dependencies)
//!
//! When introducing the first iPhone, Mr. Steve Jobs had a famous line about the stylus. Thanks to young people writing a·ma·teur crates, I
//! have a chance to borrow his line here:
//!
//! > _Debts, who uses debts? Yuck! Let's not use debts._
//!
//! And here is my own line: It's a tiny implementation, so let's not use debts!
//!
//! ## Errors
//!
//! Since it's a tiny implementation, no new errors are introduced. `std::io::Error` is good enough.
//!
//! ## Panics
//!
//! It's guaranteed that there are _no_ panics.
//!
//! [Semantic Versioning 2.0.0]: https://semver.org/spec/v2.0.0.html

// ╔═════════════════╗
// ║   IDENTIFIERS   ║
// ╚═════════════════╝

macro_rules! code_name  { () => { "debt64" }}
macro_rules! version    { () => { "2.0.0" }}

/// # Crate name
pub const NAME: &'static str = "Debt64";

/// # Crate code name
pub const CODE_NAME: &'static str = code_name!();

/// # Crate version
pub const VERSION: &'static str = version!();

/// # Crate release date (year/month/day)
pub const RELEASE_DATE: (u16, u8, u8) = (2019, 3, 28);

/// # Unique universally identifier of this crate
pub const UUID: &'static str = "6e07c48e-cc38-45d0-8265-4bc1a82def63";

/// # Tag, which can be used for logging...
pub const TAG: &'static str = concat!(code_name!(), "::6e07c48e::", version!());

// ╔════════════════════╗
// ║   IMPLEMENTATION   ║
// ╚════════════════════╝

#[test]
fn test_crate_version() {
    assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
}

mod encoder;
mod decoder;

pub use encoder::*;
pub use decoder::*;

pub mod version_info;

/// # Base62 digits
const BASE62_DIGITS: [char; 62] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
];

/// # Pad char
const PAD_CHAR: char = '=';

/// # Last chars (#62 and #63)
#[derive(Debug, Eq, PartialEq)]
struct LastChars {

    /// # The #62 char
    first: char,

    /// # The #63 char
    last: char,

}

/// # Kinds
///
/// Not all variants are supported. Please follow the wiki article for details.
#[derive(Debug)]
pub enum Kind {

    /// # Standard
    ///
    /// | Character #62 | Character #63 | Padding | Fixed line length | Max. line length | Line separators | Characters outside alphabet
    /// | ------------- | ------------- | ------- | ----------------- | ---------------- | --------------- | ---------------------------
    /// | `+`           | `/`           | `=`     | No                | None             | None            | Forbidden
    Standard,

    /// # IMAP mailbox names
    ///
    /// | Character #62 | Character #63 | Padding | Fixed line length | Max. line length | Line separators | Characters outside alphabet
    /// | ------------- | ------------- | ------- | ----------------- | ---------------- | --------------- | ---------------------------
    /// | `+`           | `,`           | None    | No                | None             | None            | Forbidden
    IMAP,

    /// # For MIME
    ///
    /// | Character #62 | Character #63 | Padding | Fixed line length | Max. line length | Line separators | Characters outside alphabet
    /// | ------------- | ------------- | ------- | ----------------- | ---------------- | --------------- | ---------------------------
    /// | `+`           | `/`           | `=`     | No                | `76`             | `\r\n`          | Accepted (discarded)
    ///
    /// ## Notes
    ///
    /// - Encoding produces above line separators.
    /// - Decoding accepts above line separators and also just a single line feed `\n`.
    /// - Decoding does _**not**_ allow consecutive line separators. For instance `\r\n\r\n` are not allowed.
    MIME,

    /// # URLs and filenames
    ///
    /// | Character #62 | Character #63 | Padding        | Fixed line length | Max. line length | Line separators | Characters outside alphabet
    /// | ------------- | ------------- | -------------- | ----------------- | ---------------- | --------------- | ---------------------------
    /// | `-`           | `_`           | `=` (optional) | No                | Optional         | None            | Forbidden
    ///
    /// ## Notes
    ///
    /// - This implementation has no limit on max line length.
    /// - Encoding doesn't produce pad characters.
    URL,

    /// # URLs and filenames in Freenet
    ///
    /// | Character #62 | Character #63 | Padding        | Fixed line length | Max. line length | Line separators | Characters outside alphabet
    /// | ------------- | ------------- | -------------- | ----------------- | ---------------- | --------------- | ---------------------------
    /// | `~`           | `-`           | `=`            | No                | Optional         | None            | Forbidden
    ///
    /// ## Notes
    ///
    /// - This implementation has no limit on max line length.
    ///
    /// _Freenet: <https://en.wikipedia.org/wiki/Freenet>_
    FreenetURL,

}

impl Kind {

    const STANDARD_LAST_CHARS: LastChars = LastChars { first: '+', last: '/' };
    const IMAP_LAST_CHARS: LastChars = LastChars { first: '+', last: ',' };
    const MIME_LAST_CHARS: LastChars = LastChars { first: '+', last: '/' };
    const URL_LAST_CHARS: LastChars = LastChars { first: '-', last: '_' };
    const FREENET_URL_LAST_CHARS: LastChars = LastChars { first: '~', last: '-' };

    const MIME_LINE_SEPARATORS: [char; 2] = ['\r', '\n'];

    /// # Gets last characters (#62 and #63)
    fn last_chars(&self) -> &LastChars {
        match *self {
            Kind::Standard => &Self::STANDARD_LAST_CHARS,
            Kind::IMAP => &Self::IMAP_LAST_CHARS,
            Kind::MIME => &Self::MIME_LAST_CHARS,
            Kind::URL => &Self::URL_LAST_CHARS,
            Kind::FreenetURL => &Self::FREENET_URL_LAST_CHARS,
        }
    }

    /// # Gets line separators
    fn line_separators(&self) -> Option<&[char]> {
        match *self {
            Kind::Standard => None,
            Kind::IMAP => None,
            Kind::MIME => Some(&Self::MIME_LINE_SEPARATORS),
            Kind::URL => None,
            Kind::FreenetURL => None,
        }
    }

    /// # Gets max line length
    fn max_line_len(&self) -> Option<usize> {
        match *self {
            Kind::Standard => None,
            Kind::IMAP => None,
            Kind::MIME => Some(76),
            Kind::URL => None,
            Kind::FreenetURL => None,
        }
    }

    /// # Checks if pad character is a must
    fn must_use_pad(&self) -> bool {
        match *self {
            Kind::Standard => true,
            Kind::IMAP => false,
            Kind::MIME => true,
            Kind::URL => false,
            Kind::FreenetURL => true,
        }
    }

    /// # Checks if pad character can be used
    fn can_use_pad(&self) -> bool {
        match *self {
            Kind::Standard => true,
            Kind::IMAP => false,
            Kind::MIME => true,
            Kind::URL => true,
            Kind::FreenetURL => true,
        }
    }

    /// # Gets character at given index
    fn get_char(index: usize, last_chars: &LastChars) -> &char {
        match index {
            0...61 => &BASE62_DIGITS[index],
            62 => &last_chars.first,
            _ => &last_chars.last,
        }
    }

    /// # Checks to see if invalid characters are allowed
    fn allows_invalid_chars(&self) -> bool {
        match *self {
            Kind::Standard => false,
            Kind::IMAP => false,
            Kind::MIME => true,
            Kind::URL => false,
            Kind::FreenetURL => false,
        }
    }

    /// # _Estimates_ encoding capacity
    pub fn estimate_encoding_capacity(&self, bytes: impl AsRef<[u8]>) -> usize {
        let result = bytes.as_ref().len();
        if result == 0 {
            return 0;
        }

        let result = (result / 3).saturating_mul(4).saturating_add(match result % 3 {
            0 => 0,
            other => match self.must_use_pad() {
                true => 4,
                false => other + 1,
            },
        });
        match (self.max_line_len().as_ref(), self.line_separators().as_ref()) {
            (Some(max_line_len), Some(line_separators)) => result.saturating_add(
                (result / max_line_len).saturating_sub(if result % max_line_len == 0 { 1 } else { 0 }).saturating_mul(line_separators.len())
            ),
            _ => result,
        }
    }

    /// # _Estimates_ decoding capacity
    pub fn estimate_decoding_capacity(&self, bytes: impl AsRef<[u8]>) -> usize {
        let result = bytes.as_ref().len();
        if result == 0 {
            return 0;
        }

        let line_separators = match (self.max_line_len().as_ref(), self.line_separators().as_ref()) {
            (Some(max_line_len), Some(line_separators)) => {
                let line_len = max_line_len.saturating_add(line_separators.len());
                (result / line_len).saturating_mul(line_separators.len())
            },
            _ => 0,
        };

        let result = result.saturating_sub(line_separators);
        let result = (result / 4).saturating_mul(3).saturating_add(match result % 4 {
            0 | 1 => 0,
            2 => 1,
            _ => 2,
        });

        result
    }

}

#[test]
fn test_base62_digits() {
    for (i, b) in (b'A'..b'Z').enumerate() {
        assert_eq!(b as char, BASE62_DIGITS[i]);
    }
    for (i, b) in (b'a'..b'z').enumerate() {
        assert_eq!(b as char, BASE62_DIGITS[i + 26]);
    }
    for (i, b) in (b'0'..b'9').enumerate() {
        assert_eq!(b as char, BASE62_DIGITS[i + 52]);
    }
}

#[test]
fn test_kind_last_chars() {
    assert_eq!(Kind::Standard.last_chars(), &LastChars { first: '+', last: '/' });
    assert_eq!(Kind::IMAP.last_chars(), &LastChars { first: '+', last: ',' });
    assert_eq!(Kind::MIME.last_chars(), &LastChars { first: '+', last: '/' });
    assert_eq!(Kind::URL.last_chars(), &LastChars { first: '-', last: '_' });
    assert_eq!(Kind::FreenetURL.last_chars(), &LastChars { first: '~', last: '-' });
}

#[test]
fn test_kind_line_separators() {
    assert_eq!(Kind::Standard.line_separators(), None);
    assert_eq!(Kind::IMAP.line_separators(), None);
    assert_eq!(Kind::MIME.line_separators().unwrap(), &['\r', '\n']);
    assert_eq!(Kind::URL.line_separators(), None);
    assert_eq!(Kind::FreenetURL.line_separators(), None);
}

#[test]
fn test_kind_max_line_len() {
    assert_eq!(Kind::Standard.max_line_len(), None);
    assert_eq!(Kind::IMAP.max_line_len(), None);
    assert_eq!(Kind::MIME.max_line_len(), Some(76));
    assert_eq!(Kind::URL.max_line_len(), None);
    assert_eq!(Kind::FreenetURL.max_line_len(), None);
}

#[test]
fn test_kind_pad_char() {
    assert_eq!(Kind::Standard.must_use_pad(), true);
    assert_eq!(Kind::Standard.can_use_pad(), true);

    assert_eq!(Kind::IMAP.must_use_pad(), false);
    assert_eq!(Kind::IMAP.can_use_pad(), false);

    assert_eq!(Kind::MIME.must_use_pad(), true);
    assert_eq!(Kind::MIME.can_use_pad(), true);

    assert_eq!(Kind::URL.must_use_pad(), false);
    assert_eq!(Kind::URL.can_use_pad(), true);

    assert_eq!(Kind::FreenetURL.must_use_pad(), true);
    assert_eq!(Kind::FreenetURL.can_use_pad(), true);
}

#[test]
fn test_kind_invalid_chars() {
    assert_eq!(Kind::Standard.allows_invalid_chars(), false);
    assert_eq!(Kind::IMAP.allows_invalid_chars(), false);
    assert_eq!(Kind::MIME.allows_invalid_chars(), true);
    assert_eq!(Kind::URL.allows_invalid_chars(), false);
    assert_eq!(Kind::FreenetURL.allows_invalid_chars(), false);
}