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
358
359
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![allow(clippy::cast_possible_truncation)]
#![warn(clippy::cargo)]
#![warn(missing_docs, intra_doc_link_resolution_failure)]
#![warn(missing_debug_implementations)]
#![warn(rust_2018_idioms)]

//! The Bubble Babble binary data encoding.
//!
//! This is a native Rust implementation of a Bubble Babble encoder and decoder.
//!
//! # Usage
//!
//! You can encode binary data by calling [`encode`]:
//!
//! ```
//! let enc = boba::encode("Pineapple");
//! assert_eq!(enc, "xigak-nyryk-humil-bosek-sonax");
//! ```
//!
//! Decoding binary data is done by calling [`decode`]:
//!
//! ```
//! # fn main() -> Result<(), boba::DecodeError> {
//! let dec = boba::decode("xexax")?;
//! assert_eq!(dec, vec![]);
//! # Ok(())
//! # }
//! ```
//!
//! Decode is fallible and can return [`DecodeError`]. For example, all Bubble
//! Babble-encoded data has an ASCII alphabet, so attempting to decode an emoji
//! will fail.
//!
//! ```
//! # use boba::DecodeError;
//! let dec = boba::decode("x🦀x");
//! // The `DecodeError` contains the offset of the first invalid byte.
//! assert_eq!(Err(DecodeError::InvalidByte(1)), dec);
//! ```
//!
//! ## Safety
//!
//! This crate operates on byte slices, but [`encode`] returns a [`String`].
//! This crate contains a single line of unsafe code to turn the encode buffer
//! into a `String`. This is known to be safe since the buffer is populated from
//! a fixed, ASCII-only alpahabet.

#![doc(html_root_url = "https://docs.rs/boba/3.0.0")]

#[cfg(doctest)]
doc_comment::doctest!("../README.md");

use bstr::ByteSlice;
use std::error;
use std::fmt;

const VOWELS: [u8; 6] = *b"aeiouy";
const CONSONANTS: [u8; 16] = *b"bcdfghklmnprstvz";

const HEADER: u8 = b'x';
const TRAILER: u8 = b'x';

/// Decoding errors from [`boba::decode`](decode).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DecodeError {
    /// Checksum mismatch when decoding input.
    ChecksumMismatch,
    /// Corrupted input caused a decoding failure.
    Corrupted,
    /// Input contained a byte not in the encoding alphabet at this position.
    InvalidByte(usize),
    /// Input was missing a leading `x` header.
    MalformedHeader,
    /// Input was missing a final `x` trailer.
    MalformedTrailer,
}

impl error::Error for DecodeError {}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ChecksumMismatch => write!(f, "Checksum mismatch"),
            Self::Corrupted => write!(f, "Corrupted input"),
            Self::InvalidByte(pos) => write!(
                f,
                "Encountered byte outside of encoding alphabet at position {}",
                pos
            ),
            Self::MalformedHeader => write!(f, "Missing required 'x' header"),
            Self::MalformedTrailer => write!(f, "Missing required 'x' trailer"),
        }
    }
}

/// Encode a byte slice with the Bubble Babble encoding to a [`String`].
///
/// # Examples
///
/// ```
/// assert_eq!(boba::encode([]), "xexax");
/// assert_eq!(boba::encode("1234567890"), "xesef-disof-gytuf-katof-movif-baxux");
/// assert_eq!(boba::encode("Pineapple"), "xigak-nyryk-humil-bosek-sonax");
/// ```
#[must_use]
pub fn encode<T: AsRef<[u8]>>(data: T) -> String {
    let data = data.as_ref();
    let mut encoded = Vec::with_capacity(6 * (data.len() / 2) + 3 + 2);
    encoded.push(HEADER);
    let mut checksum = 1_u8;
    let mut chunks = data.chunks_exact(2);
    while let Some([left, right]) = chunks.next() {
        odd_partial(*left, checksum, &mut encoded);
        let d = (*right >> 4) & 15;
        let e = *right & 15;
        // Panic safety:
        //
        // - `d` is constructed with a mask of `0b1111`.
        // - `CONSONANTS` is a fixed size array with 17 elements.
        // - Maximum value of `d` is 16.
        encoded.push(CONSONANTS[d as usize]);
        encoded.push(b'-');
        // Panic safety:
        //
        // - `e` is constructed with a mask of `0b1111`.
        // - `CONSONANTS` is a fixed size array with 17 elements.
        // - Maximum value of `e` is 15.
        encoded.push(CONSONANTS[e as usize]);
        checksum =
            ((u16::from(checksum * 5) + u16::from(*left) * 7 + u16::from(*right)) % 36) as u8;
    }
    if let [byte] = chunks.remainder() {
        odd_partial(*byte, checksum, &mut encoded);
    } else {
        even_partial(checksum, &mut encoded);
    }
    encoded.push(TRAILER);
    // Safety:
    //
    // - `encoded` is pushed to by indexing into the `VOWELS` and `CONSONANTS`
    //   arrays.
    // - `VOWELS` only contains bytes that are valid ASCII.
    // - `CONSONANTS` only contains bytes that are valid ASCII.
    unsafe { String::from_utf8_unchecked(encoded) }
}

/// Decode Bubble Babble-encoded byte slice to a `Vec<u8>`.
///
/// # Examples
///
/// ```
/// assert_eq!(boba::decode("xexax"), Ok(vec![]));
/// assert_eq!(boba::decode("xesef-disof-gytuf-katof-movif-baxux"), Ok(b"1234567890".to_vec()));
/// assert_eq!(boba::decode("xigak-nyryk-humil-bosek-sonax"), Ok(b"Pineapple".to_vec()));
/// ```
///
/// # Errors
///
/// Decoding is fallible and might return [`DecodeError`]:
///
/// - If the input is not an ASCII string, an error is returned.
/// - If the input contains an ASCII character outside of the Bubble Babble
///   encoding alphabet, an error is returned.
/// - If the input does not start with a leading 'x', an error is returned.
/// - If the input does not end with a trailing 'x', an error is returned.
/// - If the decoded result does not checksum properly, an error is returned.
///
/// ```
/// # use boba::DecodeError;
/// assert_eq!(boba::decode("x💎🦀x"), Err(DecodeError::InvalidByte(1)));
/// assert_eq!(boba::decode("x789x"), Err(DecodeError::InvalidByte(1)));
/// assert_eq!(boba::decode("yx"), Err(DecodeError::MalformedHeader));
/// assert_eq!(boba::decode("xy"), Err(DecodeError::MalformedTrailer));
/// assert_eq!(boba::decode(""), Err(DecodeError::Corrupted));
/// assert_eq!(boba::decode("z"), Err(DecodeError::Corrupted));
/// assert_eq!(boba::decode("xx"), Err(DecodeError::Corrupted));
/// ```
pub fn decode<T: AsRef<[u8]>>(encoded: T) -> Result<Vec<u8>, DecodeError> {
    let encoded = encoded.as_ref();
    if encoded == b"xexax" {
        return Ok(Vec::new());
    }
    let enc = match encoded {
        [b'x', enc @ .., b'x'] => enc,
        [b'x', ..] => return Err(DecodeError::MalformedTrailer),
        [.., b'x'] => return Err(DecodeError::MalformedHeader),
        _ => return Err(DecodeError::Corrupted),
    };
    if let Some(pos) = enc.find_non_ascii_byte() {
        return Err(DecodeError::InvalidByte(pos + 1));
    }
    let len = encoded.len();
    let mut decoded = Vec::with_capacity(if len == 5 { 1 } else { 2 * ((len + 1) / 6) });
    let mut checksum = 1_u8;
    let mut chunks = enc.chunks_exact(6);
    let mut pos = 1;
    while let Some([left, mid, right, up, _, down]) = chunks.next() {
        let byte1 = decode_3_tuple(
            VOWELS
                .find_byte(*left)
                .ok_or_else(|| DecodeError::InvalidByte(pos))? as u8,
            CONSONANTS
                .find_byte(*mid)
                .ok_or_else(|| DecodeError::InvalidByte(pos + 1))? as u8,
            VOWELS
                .find_byte(*right)
                .ok_or_else(|| DecodeError::InvalidByte(pos + 2))? as u8,
            checksum,
        )?;
        let byte2 = decode_2_tuple(
            CONSONANTS
                .find_byte(*up)
                .ok_or_else(|| DecodeError::InvalidByte(pos + 3))? as u8,
            CONSONANTS
                .find_byte(*down)
                .ok_or_else(|| DecodeError::InvalidByte(pos + 5))? as u8,
        );
        pos += 6;
        checksum =
            ((u16::from(checksum * 5) + (u16::from(byte1) * 7) + u16::from(byte2)) % 36) as u8;
        decoded.push(byte1);
        decoded.push(byte2);
    }
    if let [left, mid, right] = chunks.remainder() {
        let a = VOWELS
            .find_byte(*left)
            .ok_or_else(|| DecodeError::InvalidByte(pos))? as u8;
        let c = VOWELS
            .find_byte(*right)
            .ok_or_else(|| DecodeError::InvalidByte(pos + 2))? as u8;

        if *mid == b'x' {
            if a != checksum % 6 || c != checksum / 6 {
                return Err(DecodeError::ChecksumMismatch);
            }
        } else {
            let b = CONSONANTS
                .find_byte(*mid)
                .ok_or_else(|| DecodeError::InvalidByte(pos + 1))? as u8;
            decoded.push(decode_3_tuple(a, b, c, checksum)?);
        }
        Ok(decoded)
    } else {
        Err(DecodeError::Corrupted)
    }
}

#[inline]
fn odd_partial(raw_byte: u8, checksum: u8, buf: &mut Vec<u8>) {
    let a = (((raw_byte >> 6) & 3) + checksum) % 6;
    let b = (raw_byte >> 2) & 15;
    let c = ((raw_byte & 3) + checksum / 6) % 6;
    // Panic safety:
    //
    // - `a` is constructed with mod 6.
    // - `VOWELS` is a fixed size array with 6 elements.
    // - Maximum value of `a` is 5.
    buf.push(VOWELS[a as usize]);
    // Panic safety:
    //
    // - `b` is constructed with a mask of `0b1111`.
    // - `CONSONANTS` is a fixed size array with 17 elements.
    // - Maximum value of `e` is 15.
    buf.push(CONSONANTS[b as usize]);
    // Panic safety:
    //
    // - `c` is constructed with mod 6.
    // - `VOWELS` is a fixed size array with 6 elements.
    // - Maximum value of `c` is 5.
    buf.push(VOWELS[c as usize]);
}

#[inline]
fn even_partial(checksum: u8, buf: &mut Vec<u8>) {
    let a = checksum % 6;
    // let b = 16;
    let c = checksum / 6;
    // Panic safety:
    //
    // - `a` is constructed with mod 6.
    // - `VOWELS` is a fixed size array with 6 elements.
    // - Maximum value of `a` is 5.
    buf.push(VOWELS[a as usize]);
    buf.push(b'x');
    // Panic safety:
    //
    // - `c` is constructed with divide by 6.
    // - Maximum value of `checksum` is 36 -- see `encode` loop.
    // - `VOWELS` is a fixed size array with 6 elements.
    // - Maximum value of `c` is 5.
    buf.push(VOWELS[c as usize]);
}

#[inline]
fn decode_3_tuple(byte1: u8, byte2: u8, byte3: u8, checksum: u8) -> Result<u8, DecodeError> {
    // Will not overflow since:
    // - byte1 is guaranteed to be ASCII or < 128.
    // Will not underflow since:
    // - 6 - (checksum % 6) > 0
    let high = (byte1 + 6 - (checksum % 6)) % 6;
    let mid = byte2;
    // Will not overflow since:
    // - byte3 is guaranteed to be ASCII or < 128.
    // Will not underflow since:
    // - 6 - ((checksum / 6) % 6) > 0
    let low = (byte3 + 6 - ((checksum / 6) % 6)) % 6;
    if high >= 4 || low >= 4 {
        Err(DecodeError::Corrupted)
    } else {
        Ok((high << 6) | (mid << 2) | low)
    }
}

#[inline]
fn decode_2_tuple(byte1: u8, byte2: u8) -> u8 {
    (byte1 << 4) | byte2
}

#[cfg(test)]
#[allow(clippy::non_ascii_literal)]
mod tests {
    use crate::DecodeError;

    #[test]
    fn encode() {
        assert_eq!(crate::encode([]), "xexax");
        assert_eq!(
            crate::encode("1234567890"),
            "xesef-disof-gytuf-katof-movif-baxux"
        );
        assert_eq!(crate::encode("Pineapple"), "xigak-nyryk-humil-bosek-sonax");
    }

    #[test]
    fn decode() {
        assert_eq!(crate::decode("xexax"), Ok(vec![]));
        assert_eq!(
            crate::decode("xesef-disof-gytuf-katof-movif-baxux"),
            Ok(b"1234567890".to_vec())
        );
        assert_eq!(
            crate::decode("xigak-nyryk-humil-bosek-sonax"),
            Ok(b"Pineapple".to_vec())
        );
    }

    #[test]
    fn decode_error() {
        assert_eq!(crate::decode(""), Err(DecodeError::Corrupted));
        assert_eq!(crate::decode("z"), Err(DecodeError::Corrupted));
        assert_eq!(crate::decode("xy"), Err(DecodeError::MalformedTrailer));
        assert_eq!(crate::decode("yx"), Err(DecodeError::MalformedHeader));
        assert_eq!(crate::decode("xx"), Err(DecodeError::Corrupted));
        assert_eq!(crate::decode("x💎🦀x"), Err(DecodeError::InvalidByte(1)));
        assert_eq!(crate::decode("x789x"), Err(DecodeError::InvalidByte(1)));
    }
}