Debian Codegraph @

Xtermina/src/base64.rs

raw symbols SCIP
1 // CREDIT:
2 // A minimal base64 implementation to keep from pulling in a crate for just that. It's based on
3 // https://github.com/marshallpierce/rust-base64 but without all the customization options.
4 // The biggest portion comes from
5 // https://github.com/marshallpierce/rust-base64/blob/a675443d327e175f735a37f574de803d6a332591/src/engine/naive.rs#L42
6 // Thanks, rust-base64!
7
8 // CREDIT: this was yanked from the Helix codebase:
9 // <https://github.com/helix-editor/helix/blob/4130b162a7bbc7de739807abc05a0e8ba3712133/helix-view/src/base64.rs>
10 // Also see <https://github.com/helix-editor/helix/pull/3220>.
11
12 // The MIT License (MIT)
13
14 // Copyright (c) 2015 Alice Maz
15
16 // Permission is hereby granted, free of charge, to any person obtaining a copy
17 // of this software and associated documentation files (the "Software"), to deal
18 // in the Software without restriction, including without limitation the rights
19 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20 // copies of the Software, and to permit persons to whom the Software is
21 // furnished to do so, subject to the following conditions:
22
23 // The above copyright notice and this permission notice shall be included in
24 // all copies or substantial portions of the Software.
25
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 // THE SOFTWARE.
33
34 use core::ops::{BitAnd, BitOr, Shl, Shr};
35
36 const PAD_BYTE: u8 = b'=';
37 const ENCODE_TABLE: &[u8] =
38 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".as_bytes();
39 const LOW_SIX_BITS: u32 = 0x3F;
40
41 pub fn encode(input: &[u8]) -> String {
42 let rem = input.len() % 3;
43 let complete_chunks = input.len() / 3;
44 let remainder_chunk = usize::from(rem != 0);
45 let encoded_size = (complete_chunks + remainder_chunk) * 4;
46
47 let mut output = vec![0; encoded_size];
48
49 // complete chunks first
50 let complete_chunk_len = input.len() - rem;
51
52 let mut input_index = 0_usize;
53 let mut output_index = 0_usize;
54 while input_index < complete_chunk_len {
55 let chunk = &input[input_index..input_index + 3];
56
57 // populate low 24 bits from 3 bytes
58 let chunk_int: u32 =
59 (chunk[0] as u32).shl(16) | (chunk[1] as u32).shl(8) | (chunk[2] as u32);
60 // encode 4x 6-bit output bytes
61 output[output_index] = ENCODE_TABLE[chunk_int.shr(18) as usize];
62 output[output_index + 1] = ENCODE_TABLE[chunk_int.shr(12_u8).bitand(LOW_SIX_BITS) as usize];
63 output[output_index + 2] = ENCODE_TABLE[chunk_int.shr(6_u8).bitand(LOW_SIX_BITS) as usize];
64 output[output_index + 3] = ENCODE_TABLE[chunk_int.bitand(LOW_SIX_BITS) as usize];
65
66 input_index += 3;
67 output_index += 4;
68 }
69
70 // then leftovers
71 if rem == 2 {
72 let chunk = &input[input_index..input_index + 2];
73
74 // high six bits of chunk[0]
75 output[output_index] = ENCODE_TABLE[chunk[0].shr(2) as usize];
76 // bottom 2 bits of [0], high 4 bits of [1]
77 output[output_index + 1] = ENCODE_TABLE
78 [(chunk[0].shl(4_u8).bitor(chunk[1].shr(4_u8)) as u32).bitand(LOW_SIX_BITS) as usize];
79 // bottom 4 bits of [1], with the 2 bottom bits as zero
80 output[output_index + 2] =
81 ENCODE_TABLE[(chunk[1].shl(2_u8) as u32).bitand(LOW_SIX_BITS) as usize];
82 output[output_index + 3] = PAD_BYTE;
83 } else if rem == 1 {
84 let byte = input[input_index];
85 output[output_index] = ENCODE_TABLE[byte.shr(2) as usize];
86 output[output_index + 1] =
87 ENCODE_TABLE[(byte.shl(4_u8) as u32).bitand(LOW_SIX_BITS) as usize];
88 output[output_index + 2] = PAD_BYTE;
89 output[output_index + 3] = PAD_BYTE;
90 }
91 String::from_utf8(output).expect("Invalid UTF8")
92 }
93
94 #[cfg(test)]
95 mod tests {
96 fn compare_encode(expected: &str, target: &[u8]) {
97 assert_eq!(expected, super::encode(target));
98 }
99
100 #[test]
101 fn encode_rfc4648_0() {
102 compare_encode("", b"");
103 }
104
105 #[test]
106 fn encode_rfc4648_1() {
107 compare_encode("Zg==", b"f");
108 }
109
110 #[test]
111 fn encode_rfc4648_2() {
112 compare_encode("Zm8=", b"fo");
113 }
114
115 #[test]
116 fn encode_rfc4648_3() {
117 compare_encode("Zm9v", b"foo");
118 }
119
120 #[test]
121 fn encode_rfc4648_4() {
122 compare_encode("Zm9vYg==", b"foob");
123 }
124
125 #[test]
126 fn encode_rfc4648_5() {
127 compare_encode("Zm9vYmE=", b"fooba");
128 }
129
130 #[test]
131 fn encode_rfc4648_6() {
132 compare_encode("Zm9vYmFy", b"foobar");
133 }
134
135 #[test]
136 fn encode_all_ascii() {
137 let mut ascii = Vec::<u8>::with_capacity(128);
138
139 for i in 0..128 {
140 ascii.push(i);
141 }
142
143 compare_encode(
144 "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7P\
145 D0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn8\
146 =",
147 &ascii,
148 );
149 }
150
151 #[test]
152 fn encode_all_bytes() {
153 let mut bytes = Vec::<u8>::with_capacity(256);
154
155 for i in 0..255 {
156 bytes.push(i);
157 }
158 bytes.push(255); //bug with "overflowing" ranges?
159
160 compare_encode(
161 "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7P\
162 D0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn\
163 +AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6\
164 /wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==",
165 &bytes,
166 );
167 }
168 }