| 1 | //! Encoding and decoding of zbase32. |
| 2 | //! |
| 3 | //! This is an implementation of the human-oriented base-32 encoding called |
| 4 | //! [zbase32](https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt). |
| 5 | |
| 6 | #![cfg_attr(all(test, feature = "unstable"), feature(test))] |
| 7 | |
| 8 | /// Alphabet used by zbase32 |
| 9 | pub const ALPHABET: &[u8; 32] = b"ybndrfg8ejkmcpqxot1uwisza345h769"; |
| 10 | |
| 11 | #[rustfmt::skip] |
| 12 | const CONVERSION_TABLE: &[Option<u8>; 256] = &[ |
| 13 | /* 0 */ None, None, None, None, None, |
| 14 | /* 5 */ None, None, None, None, None, |
| 15 | /* 10 */ None, None, None, None, None, |
| 16 | /* 15 */ None, None, None, None, None, |
| 17 | /* 20 */ None, None, None, None, None, |
| 18 | /* 25 */ None, None, None, None, None, |
| 19 | /* 30 */ None, None, None, None, None, |
| 20 | /* 35 */ None, None, None, None, None, |
| 21 | /* 40 */ None, None, None, None, None, |
| 22 | /* 45 */ None, None, None, None, Some(0x12), |
| 23 | /* 50 */ None, Some(0x19), Some(0x1a), Some(0x1b), Some(0x1e), |
| 24 | /* 55 */ Some(0x1d), Some(0x07), Some(0x1f), None, None, |
| 25 | /* 60 */ None, None, None, None, None, |
| 26 | /* 65 */ None, None, None, None, None, |
| 27 | /* 70 */ None, None, None, None, None, |
| 28 | /* 75 */ None, None, None, None, None, |
| 29 | /* 80 */ None, None, None, None, None, |
| 30 | /* 85 */ None, None, None, None, None, |
| 31 | /* 90 */ None, None, None, None, None, |
| 32 | /* 95 */ None, None, Some(0x18), Some(0x01), Some(0x0c), |
| 33 | /* 100 */ Some(0x03), Some(0x08), Some(0x05), Some(0x06), Some(0x1c), |
| 34 | /* 105 */ Some(0x15), Some(0x09), Some(0x0a), None, Some(0x0b), |
| 35 | /* 110 */ Some(0x02), Some(0x10), Some(0x0d), Some(0x0e), Some(0x04), |
| 36 | /* 115 */ Some(0x16), Some(0x11), Some(0x13), None, Some(0x14), |
| 37 | /* 120 */ Some(0x0f), Some(0x00), Some(0x17), None, None, |
| 38 | /* 125 */ None, None, None, None, None, |
| 39 | /* 130 */ None, None, None, None, None, |
| 40 | /* 135 */ None, None, None, None, None, |
| 41 | /* 140 */ None, None, None, None, None, |
| 42 | /* 145 */ None, None, None, None, None, |
| 43 | /* 150 */ None, None, None, None, None, |
| 44 | /* 155 */ None, None, None, None, None, |
| 45 | /* 160 */ None, None, None, None, None, |
| 46 | /* 165 */ None, None, None, None, None, |
| 47 | /* 170 */ None, None, None, None, None, |
| 48 | /* 175 */ None, None, None, None, None, |
| 49 | /* 180 */ None, None, None, None, None, |
| 50 | /* 185 */ None, None, None, None, None, |
| 51 | /* 190 */ None, None, None, None, None, |
| 52 | /* 195 */ None, None, None, None, None, |
| 53 | /* 200 */ None, None, None, None, None, |
| 54 | /* 205 */ None, None, None, None, None, |
| 55 | /* 210 */ None, None, None, None, None, |
| 56 | /* 215 */ None, None, None, None, None, |
| 57 | /* 220 */ None, None, None, None, None, |
| 58 | /* 225 */ None, None, None, None, None, |
| 59 | /* 230 */ None, None, None, None, None, |
| 60 | /* 235 */ None, None, None, None, None, |
| 61 | /* 240 */ None, None, None, None, None, |
| 62 | /* 245 */ None, None, None, None, None, |
| 63 | /* 250 */ None, None, None, None, None, |
| 64 | /* 255 */ None |
| 65 | ]; |
| 66 | |
| 67 | #[inline] |
| 68 | fn value_of_digit(digit: u8) -> Result<u8, &'static str> { |
| 69 | match CONVERSION_TABLE[digit as usize] { |
| 70 | Some(v) => Ok(v), |
| 71 | None => Err("not a zbase32 digit"), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// Decode first N `bits` of given zbase32 encoded data |
| 76 | /// |
| 77 | /// # Panic |
| 78 | /// |
| 79 | /// Panics if `zbase32` decoded is shorter than N `bits`. |
| 80 | /// |
| 81 | /// # Examples |
| 82 | /// |
| 83 | /// ``` |
| 84 | /// use zbase32; |
| 85 | /// |
| 86 | /// assert_eq!(zbase32::decode(b"o", 1).unwrap(), &[0x80]); |
| 87 | /// ``` |
| 88 | pub fn decode(zbase32: &[u8], bits: u64) -> Result<Vec<u8>, &'static str> { |
| 89 | assert!(zbase32.len() as u64 * 5 >= bits, "zbase32 slice too short"); |
| 90 | #[allow(clippy::cast_possible_truncation)] |
| 91 | let capacity = if bits % 8 == 0 { |
| 92 | bits / 8 |
| 93 | } else { |
| 94 | bits / 8 + 1 |
| 95 | } as usize; |
| 96 | let mut result = Vec::with_capacity(capacity); |
| 97 | |
| 98 | let mut bits_remaining = bits; |
| 99 | let mut buffer_size: u8 = 0; |
| 100 | let mut buffer: u16 = !0; |
| 101 | for digit in zbase32 { |
| 102 | let value = value_of_digit(*digit)?; |
| 103 | buffer = (buffer << 5) | u16::from(value); |
| 104 | buffer_size += 5; |
| 105 | if bits_remaining < 8 && u64::from(buffer_size) >= bits_remaining { |
| 106 | break; |
| 107 | } |
| 108 | if buffer_size >= 8 { |
| 109 | #[allow(clippy::cast_possible_truncation)] |
| 110 | let byte = (buffer >> (buffer_size - 8)) as u8; |
| 111 | result.push(byte); |
| 112 | bits_remaining -= 8; |
| 113 | buffer_size -= 8; |
| 114 | } |
| 115 | } |
| 116 | if bits_remaining > 0 { |
| 117 | #[allow(clippy::cast_possible_truncation)] |
| 118 | let trim_right = buffer_size - bits_remaining as u8; |
| 119 | buffer >>= trim_right; |
| 120 | buffer_size -= trim_right; |
| 121 | #[allow(clippy::cast_possible_truncation)] |
| 122 | let byte = (buffer << (8_u8 - buffer_size)) as u8; |
| 123 | result.push(byte); |
| 124 | } |
| 125 | debug_assert_eq!(capacity, result.len()); |
| 126 | Ok(result) |
| 127 | } |
| 128 | |
| 129 | /// Decode given zbase32 encoded string |
| 130 | /// |
| 131 | /// Just like `decode` but doesn't allow decoding with bit precision. |
| 132 | /// |
| 133 | /// This decodes full bytes. For instance, if you have `b"yy"`, you'll get one |
| 134 | /// byte back. `b"yy"` can enode 10 bits (2 * 5) which is truncated at the next |
| 135 | /// lower byte boundary. |
| 136 | /// |
| 137 | /// # Examples |
| 138 | /// |
| 139 | /// ``` |
| 140 | /// use zbase32; |
| 141 | /// |
| 142 | /// assert_eq!(zbase32::decode_full_bytes(b"qb1ze3m1").unwrap(), b"peter"); |
| 143 | /// ``` |
| 144 | #[inline] |
| 145 | pub fn decode_full_bytes(zbase: &[u8]) -> Result<Vec<u8>, &'static str> { |
| 146 | let size = zbase.len() as u64 * 5; |
| 147 | decode(zbase, size / 8 * 8) |
| 148 | } |
| 149 | |
| 150 | /// Decode first N `bits` of given zbase32 encoded string |
| 151 | /// |
| 152 | /// # Panic |
| 153 | /// |
| 154 | /// Panics if `zbase32` decoded is shorter than N `bits`. |
| 155 | /// |
| 156 | /// # Examples |
| 157 | /// |
| 158 | /// ``` |
| 159 | /// use zbase32; |
| 160 | /// |
| 161 | /// assert_eq!(zbase32::decode_str("o", 1).unwrap(), &[0x80]); |
| 162 | /// ``` |
| 163 | #[inline] |
| 164 | pub fn decode_str(zbase32: &str, bits: u64) -> Result<Vec<u8>, &'static str> { |
| 165 | decode(zbase32.as_bytes(), bits) |
| 166 | } |
| 167 | |
| 168 | /// Decode given zbase32 encoded string |
| 169 | /// |
| 170 | /// Just like `decode_str` but doesn't allow decoding with bit precision. |
| 171 | /// |
| 172 | /// # Examples |
| 173 | /// |
| 174 | /// ``` |
| 175 | /// use zbase32; |
| 176 | /// |
| 177 | /// assert_eq!(zbase32::decode_full_bytes_str("qb1ze3m1").unwrap(), b"peter"); |
| 178 | /// ``` |
| 179 | #[inline] |
| 180 | pub fn decode_full_bytes_str(zbase32: &str) -> Result<Vec<u8>, &'static str> { |
| 181 | decode_full_bytes(zbase32.as_bytes()) |
| 182 | } |
| 183 | |
| 184 | /// Encode first N `bits` with zbase32. |
| 185 | /// |
| 186 | /// # Panics |
| 187 | /// |
| 188 | /// Panics if `data` is shorter than N `bits`. |
| 189 | /// |
| 190 | /// # Examples |
| 191 | /// |
| 192 | /// ``` |
| 193 | /// use zbase32; |
| 194 | /// |
| 195 | /// assert_eq!(zbase32::encode(b"testdata", 64), "qt1zg7drcf4gn"); |
| 196 | /// ``` |
| 197 | /// |
| 198 | pub fn encode(data: &[u8], bits: u64) -> String { |
| 199 | assert!(data.len() as u64 * 8 >= bits, "slice too short"); |
| 200 | #[allow(clippy::cast_possible_truncation)] |
| 201 | let capacity = if bits % 5 == 0 { |
| 202 | bits / 5 |
| 203 | } else { |
| 204 | bits / 5 + 1 |
| 205 | } as usize; |
| 206 | let mut result = Vec::with_capacity(capacity); |
| 207 | |
| 208 | let mut bits_remaining = bits; |
| 209 | let mut bit_offset: u8 = 16; |
| 210 | let mut remaining = data; |
| 211 | let mut buffer = !0; |
| 212 | |
| 213 | while bits_remaining > 0 { |
| 214 | if bit_offset >= 8 { |
| 215 | if let Some((first, others)) = remaining.split_first() { |
| 216 | buffer = buffer << 8 | u16::from(*first); |
| 217 | remaining = others; |
| 218 | bit_offset -= 8; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | let unused_bits = 5_u64.saturating_sub(bits_remaining); |
| 223 | #[allow(clippy::cast_possible_truncation)] |
| 224 | let index = (buffer >> (unused_bits as u8 + 16 - 5 - bit_offset) << unused_bits) & 0x1f; |
| 225 | result.push(ALPHABET[index as usize]); |
| 226 | |
| 227 | bit_offset += 5; |
| 228 | bits_remaining -= 5 - unused_bits; |
| 229 | } |
| 230 | |
| 231 | debug_assert_eq!(capacity, result.len()); |
| 232 | unsafe { String::from_utf8_unchecked(result) } |
| 233 | } |
| 234 | |
| 235 | /// Encode full bytes using zbase32. |
| 236 | /// |
| 237 | /// Just like `encode` but doesn't allow encoding with bit precision. |
| 238 | /// |
| 239 | /// # Examples |
| 240 | /// |
| 241 | /// ``` |
| 242 | /// use zbase32; |
| 243 | /// |
| 244 | /// let data = "Just an arbitrary sentence."; |
| 245 | /// assert_eq!(zbase32::encode_full_bytes(data.as_bytes()), |
| 246 | /// "jj4zg7bycfznyam1cjwzehubqjh1yh5fp34gk5udcwzy"); |
| 247 | /// ``` |
| 248 | #[inline] |
| 249 | pub fn encode_full_bytes(data: &[u8]) -> String { |
| 250 | encode(data, data.len() as u64 * 8) |
| 251 | } |
| 252 | |
| 253 | /// Check if `data` is valid zbase32 encoded bytes |
| 254 | /// |
| 255 | /// # Examples |
| 256 | /// |
| 257 | /// ``` |
| 258 | /// use zbase32; |
| 259 | /// |
| 260 | /// assert!(zbase32::validate(b"y1")); |
| 261 | /// assert!(!zbase32::validate(b"A")); |
| 262 | /// ``` |
| 263 | pub fn validate(data: &[u8]) -> bool { |
| 264 | data.iter().all(|i| value_of_digit(*i).is_ok()) |
| 265 | } |
| 266 | |
| 267 | /// Check if `data` is valid zbase32 encoded string |
| 268 | /// |
| 269 | /// # Examples |
| 270 | /// |
| 271 | /// ``` |
| 272 | /// use zbase32; |
| 273 | /// |
| 274 | /// assert!(zbase32::validate_str("y1")); |
| 275 | /// assert!(!zbase32::validate_str("A")); |
| 276 | /// ``` |
| 277 | #[inline(always)] |
| 278 | pub fn validate_str(data: &str) -> bool { |
| 279 | validate(data.as_bytes()) |
| 280 | } |
| 281 | |
| 282 | #[cfg(test)] |
| 283 | mod tests { |
| 284 | #[cfg(feature = "unstable")] |
| 285 | extern crate test; |
| 286 | extern crate rand; |
| 287 | |
| 288 | use super::*; |
| 289 | #[cfg(feature = "unstable")] |
| 290 | use tests::rand::seq::SliceRandom; |
| 291 | #[cfg(feature = "unstable")] |
| 292 | use tests::rand::Rng; |
| 293 | |
| 294 | #[rustfmt::skip] |
| 295 | const TEST_DATA: &[(u64, &str, &[u8])] = &[ |
| 296 | (0, "", &[]), |
| 297 | (1, "y", &[0x00]), |
| 298 | (1, "o", &[0x80]), |
| 299 | (2, "e", &[0x40]), |
| 300 | (2, "a", &[0xc0]), |
| 301 | (8, "yy", &[0x00]), |
| 302 | (10, "yy", &[0x00, 0x00]), |
| 303 | (10, "on", &[0x80, 0x80]), |
| 304 | (20, "tqre", &[0x8b, 0x88, 0x80]), |
| 305 | (24, "6n9hq", &[0xf0, 0xbf, 0xc7]), |
| 306 | (24, "4t7ye", &[0xd4, 0x7a, 0x04]), |
| 307 | (30, "6im5sd", &[0xf5, 0x57, 0xbb, 0x0c]), |
| 308 | (160, "ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6, |
| 309 | 0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6, |
| 310 | 0x75, 0xbe, 0x77, 0xdf]) |
| 311 | ]; |
| 312 | |
| 313 | const INVALID_TEST_DATA: &[&str] = &["ybndrfg8ejkmcpqxot1uwisza345H769", "bnâ„•e", "uv", "l"]; |
| 314 | |
| 315 | #[cfg(feature = "unstable")] |
| 316 | const ONE_MIB: usize = 1048576; |
| 317 | |
| 318 | #[test] |
| 319 | fn test_decode() { |
| 320 | for &(bits, zbase32, data) in TEST_DATA { |
| 321 | assert_eq!(decode(zbase32.as_bytes(), bits).unwrap(), data); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | #[rustfmt::skip] |
| 327 | fn test_decode_full_bytes() { |
| 328 | let test_data: &[(&str, &[u8])] = &[ |
| 329 | ("9", &[]), |
| 330 | ("y9", &[0x07]), |
| 331 | ("6n9hq", &[0xf0, 0xbf, 0xc7]), |
| 332 | ("4t7ye", &[0xd4, 0x7a, 0x04]), |
| 333 | ("ybndrfg8ejkmcpqxot1uwisza345h769", &[0x00, 0x44, 0x32, 0x14, 0xc7, 0x42, 0x54, 0xb6, |
| 334 | 0x35, 0xcf, 0x84, 0x65, 0x3a, 0x56, 0xd7, 0xc6, |
| 335 | 0x75, 0xbe, 0x77, 0xdf]) |
| 336 | ]; |
| 337 | |
| 338 | for &(zbase32, data) in test_data { |
| 339 | assert_eq!(decode_full_bytes_str(zbase32).unwrap(), data); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn test_decode_invalid_digits() { |
| 345 | for string in INVALID_TEST_DATA.iter() { |
| 346 | assert!(decode(string.as_bytes(), string.as_bytes().len() as u64 * 5).is_err()); |
| 347 | assert!(decode_full_bytes(string.as_bytes()).is_err()); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | #[test] |
| 352 | fn test_decode_superfluous_bits() { |
| 353 | assert_eq!(decode(b"999", 1).unwrap(), &[0x80]); |
| 354 | assert_eq!(decode(b"4t7yj", 24).unwrap(), &[0xd4, 0x7a, 0x04]); |
| 355 | assert_eq!(decode(b"4t7ye9", 25).unwrap(), &[0xd4, 0x7a, 0x04, 0x00]); |
| 356 | assert_eq!(decode(b"gyh3", 18).unwrap(), &[0x30, 0x39, 0x80]); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | #[should_panic(expected = "zbase32 slice too short")] |
| 361 | fn test_decode_short_slice() { |
| 362 | decode(b"oyoy", 4 * 5 + 1).unwrap(); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn test_encode() { |
| 367 | for &(bits, zbase32, data) in TEST_DATA { |
| 368 | assert_eq!(encode(data, bits), zbase32); |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn test_encode_superfluous_bits() { |
| 374 | assert_eq!(encode(&[0xff, 0xff], 1), "o"); |
| 375 | assert_eq!(encode(&[0xd4, 0x7a, 0x04, 0xff], 24), "4t7ye"); |
| 376 | } |
| 377 | |
| 378 | #[test] |
| 379 | #[should_panic(expected = "slice too short")] |
| 380 | fn test_encode_short_slice() { |
| 381 | encode(b"1234", 4 * 8 + 1); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn test_encode_full_bytes() { |
| 386 | for &(_, zbase32, data) in TEST_DATA.iter().filter(|&&(i, _, _)| i % 8 == 0) { |
| 387 | assert_eq!(encode_full_bytes(data), zbase32); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | #[test] |
| 392 | fn test_validate() { |
| 393 | for &(_, zbase32, _) in TEST_DATA { |
| 394 | assert!(validate(zbase32.as_bytes())); |
| 395 | assert!(validate_str(zbase32)); |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn test_validate_invalid() { |
| 401 | for string in INVALID_TEST_DATA.iter() { |
| 402 | assert!(!validate(string.as_bytes())); |
| 403 | assert!(!validate_str(string)); |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn test_valid_and_invalid_chars() { |
| 409 | for char in 0..=255 { |
| 410 | let bytes = &[char]; |
| 411 | if ALPHABET.contains(&char) { |
| 412 | assert_eq!(ALPHABET[value_of_digit(char).unwrap() as usize], char); |
| 413 | assert_eq!(encode(&decode(bytes, 5).unwrap(), 5).as_bytes(), bytes); |
| 414 | assert!(validate(bytes)); |
| 415 | } else { |
| 416 | assert!(value_of_digit(char).is_err()); |
| 417 | assert!(decode_full_bytes(bytes).is_err()); |
| 418 | assert!(!validate(bytes)); |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | #[cfg(feature = "unstable")] |
| 424 | #[bench] |
| 425 | fn decode_one_mib(b: &mut test::Bencher) { |
| 426 | let data = random_encoded_data(ONE_MIB); |
| 427 | b.iter(|| decode_full_bytes(&data).unwrap()) |
| 428 | } |
| 429 | |
| 430 | #[cfg(feature = "unstable")] |
| 431 | #[bench] |
| 432 | fn encode_one_mib(b: &mut test::Bencher) { |
| 433 | let data = random_data(ONE_MIB); |
| 434 | b.iter(|| encode_full_bytes(&data)) |
| 435 | } |
| 436 | |
| 437 | #[cfg(feature = "unstable")] |
| 438 | #[bench] |
| 439 | fn decode_five_bytes(b: &mut test::Bencher) { |
| 440 | let data = random_encoded_data(5); |
| 441 | b.iter(|| decode_full_bytes(&data).unwrap()) |
| 442 | } |
| 443 | |
| 444 | #[cfg(feature = "unstable")] |
| 445 | #[bench] |
| 446 | fn encode_five_bytes(b: &mut test::Bencher) { |
| 447 | let data = random_data(5); |
| 448 | b.iter(|| encode_full_bytes(&data)) |
| 449 | } |
| 450 | |
| 451 | #[cfg(feature = "unstable")] |
| 452 | #[bench] |
| 453 | fn validate_one_mib(b: &mut test::Bencher) { |
| 454 | let data = random_encoded_data(ONE_MIB); |
| 455 | b.iter(|| validate(&data)) |
| 456 | } |
| 457 | |
| 458 | #[cfg(feature = "unstable")] |
| 459 | fn random_data(bytes: usize) -> Vec<u8> { |
| 460 | let mut data = vec![0_u8; bytes]; |
| 461 | rand::thread_rng().fill(&mut data[..]); |
| 462 | data |
| 463 | } |
| 464 | |
| 465 | #[cfg(feature = "unstable")] |
| 466 | fn random_encoded_data(bytes: usize) -> Vec<u8> { |
| 467 | let mut gen = rand::thread_rng(); |
| 468 | (0..bytes * 8 / 5) |
| 469 | .map(|_| *ALPHABET.choose(&mut gen).unwrap()) |
| 470 | .collect() |
| 471 | } |
| 472 | } |