base64ct/
alphabet.rs
1#![allow(clippy::integer_arithmetic)]
5
6use core::{fmt::Debug, ops::RangeInclusive};
7
8pub mod bcrypt;
9pub mod crypt;
10pub mod shacrypt;
11pub mod standard;
12pub mod url;
13
14pub trait Alphabet: 'static + Copy + Debug + Eq + Send + Sized + Sync {
16 const BASE: u8;
18
19 const DECODER: &'static [DecodeStep];
21
22 const ENCODER: &'static [EncodeStep];
24
25 const PADDED: bool;
27
28 type Unpadded: Alphabet;
32
33 #[inline(always)]
35 fn decode_3bytes(src: &[u8], dst: &mut [u8]) -> i16 {
36 debug_assert_eq!(src.len(), 4);
37 debug_assert!(dst.len() >= 3, "dst too short: {}", dst.len());
38
39 let c0 = Self::decode_6bits(src[0]);
40 let c1 = Self::decode_6bits(src[1]);
41 let c2 = Self::decode_6bits(src[2]);
42 let c3 = Self::decode_6bits(src[3]);
43
44 dst[0] = ((c0 << 2) | (c1 >> 4)) as u8;
45 dst[1] = ((c1 << 4) | (c2 >> 2)) as u8;
46 dst[2] = ((c2 << 6) | c3) as u8;
47
48 ((c0 | c1 | c2 | c3) >> 8) & 1
49 }
50
51 fn decode_6bits(src: u8) -> i16 {
53 let mut ret: i16 = -1;
54
55 for step in Self::DECODER {
56 ret += match step {
57 DecodeStep::Range(range, offset) => {
58 let start = *range.start() as i16 - 1;
60 let end = *range.end() as i16 + 1;
61 (((start - src as i16) & (src as i16 - end)) >> 8) & (src as i16 + *offset)
62 }
63 DecodeStep::Eq(value, offset) => {
64 let start = *value as i16 - 1;
65 let end = *value as i16 + 1;
66 (((start - src as i16) & (src as i16 - end)) >> 8) & *offset
67 }
68 };
69 }
70
71 ret
72 }
73
74 #[inline(always)]
76 fn encode_3bytes(src: &[u8], dst: &mut [u8]) {
77 debug_assert_eq!(src.len(), 3);
78 debug_assert!(dst.len() >= 4, "dst too short: {}", dst.len());
79
80 let b0 = src[0] as i16;
81 let b1 = src[1] as i16;
82 let b2 = src[2] as i16;
83
84 dst[0] = Self::encode_6bits(b0 >> 2);
85 dst[1] = Self::encode_6bits(((b0 << 4) | (b1 >> 4)) & 63);
86 dst[2] = Self::encode_6bits(((b1 << 2) | (b2 >> 6)) & 63);
87 dst[3] = Self::encode_6bits(b2 & 63);
88 }
89
90 #[inline(always)]
92 fn encode_6bits(src: i16) -> u8 {
93 let mut diff = src + Self::BASE as i16;
94
95 for &step in Self::ENCODER {
96 diff += match step {
97 EncodeStep::Apply(threshold, offset) => ((threshold as i16 - diff) >> 8) & offset,
98 EncodeStep::Diff(threshold, offset) => ((threshold as i16 - src) >> 8) & offset,
99 };
100 }
101
102 diff as u8
103 }
104}
105
106#[derive(Debug)]
108pub enum DecodeStep {
109 Range(RangeInclusive<u8>, i16),
111
112 Eq(u8, i16),
114}
115
116#[derive(Copy, Clone, Debug)]
118pub enum EncodeStep {
119 Apply(u8, i16),
121
122 Diff(u8, i16),
124}