ct-codecs 1.1.4

Constant-time hex and base64 codecs from libsodium reimplemented in Rust
Documentation
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use crate::error::*;
use crate::{Decoder, Encoder};

struct Base64Impl;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Base64Variant {
    Original = 1,
    OriginalNoPadding = 3,
    UrlSafe = 5,
    UrlSafeNoPadding = 7,
}

enum VariantMask {
    NoPadding = 2,
    UrlSafe = 4,
}

impl Base64Impl {
    #[inline]
    fn _eq(x: u8, y: u8) -> u8 {
        !(((0u16.wrapping_sub((x as u16) ^ (y as u16))) >> 8) as u8)
    }

    #[inline]
    fn _gt(x: u8, y: u8) -> u8 {
        (((y as u16).wrapping_sub(x as u16)) >> 8) as u8
    }

    #[inline]
    fn _ge(x: u8, y: u8) -> u8 {
        !Self::_gt(y, x)
    }

    #[inline]
    fn _lt(x: u8, y: u8) -> u8 {
        Self::_gt(y, x)
    }

    #[inline]
    fn _le(x: u8, y: u8) -> u8 {
        Self::_ge(y, x)
    }

    #[inline]
    fn b64_byte_to_char(x: u8) -> u8 {
        (Self::_lt(x, 26) & (x.wrapping_add(b'A')))
            | (Self::_ge(x, 26) & Self::_lt(x, 52) & (x.wrapping_add(b'a'.wrapping_sub(26))))
            | (Self::_ge(x, 52) & Self::_lt(x, 62) & (x.wrapping_add(b'0'.wrapping_sub(52))))
            | (Self::_eq(x, 62) & b'+')
            | (Self::_eq(x, 63) & b'/')
    }

    #[inline]
    fn b64_char_to_byte(c: u8) -> u8 {
        let x = (Self::_ge(c, b'A') & Self::_le(c, b'Z') & (c.wrapping_sub(b'A')))
            | (Self::_ge(c, b'a') & Self::_le(c, b'z') & (c.wrapping_sub(b'a'.wrapping_sub(26))))
            | (Self::_ge(c, b'0') & Self::_le(c, b'9') & (c.wrapping_sub(b'0'.wrapping_sub(52))))
            | (Self::_eq(c, b'+') & 62)
            | (Self::_eq(c, b'/') & 63);
        x | (Self::_eq(x, 0) & (Self::_eq(c, b'A') ^ 0xff))
    }

    #[inline]
    fn b64_byte_to_urlsafe_char(x: u8) -> u8 {
        (Self::_lt(x, 26) & (x.wrapping_add(b'A')))
            | (Self::_ge(x, 26) & Self::_lt(x, 52) & (x.wrapping_add(b'a'.wrapping_sub(26))))
            | (Self::_ge(x, 52) & Self::_lt(x, 62) & (x.wrapping_add(b'0'.wrapping_sub(52))))
            | (Self::_eq(x, 62) & b'-')
            | (Self::_eq(x, 63) & b'_')
    }

    #[inline]
    fn b64_urlsafe_char_to_byte(c: u8) -> u8 {
        let x = (Self::_ge(c, b'A') & Self::_le(c, b'Z') & (c.wrapping_sub(b'A')))
            | (Self::_ge(c, b'a') & Self::_le(c, b'z') & (c.wrapping_sub(b'a'.wrapping_sub(26))))
            | (Self::_ge(c, b'0') & Self::_le(c, b'9') & (c.wrapping_sub(b'0'.wrapping_sub(52))))
            | (Self::_eq(c, b'-') & 62)
            | (Self::_eq(c, b'_') & 63);
        x | (Self::_eq(x, 0) & (Self::_eq(c, b'A') ^ 0xff))
    }

    #[inline]
    fn encoded_len(bin_len: usize, variant: Base64Variant) -> Result<usize, Error> {
        let nibbles = bin_len / 3;
        let rounded = nibbles * 3;
        let pad = bin_len - rounded;
        Ok(nibbles.checked_mul(4).ok_or(Error::Overflow)?
            + ((pad | (pad >> 1)) & 1)
                * (4 - (!((((variant as usize) & 2) >> 1).wrapping_sub(1)) & (3 - pad)))
            + 1)
    }

    pub fn encode<'t>(
        b64: &'t mut [u8],
        bin: &[u8],
        variant: Base64Variant,
    ) -> Result<&'t [u8], Error> {
        let bin_len = bin.len();
        let b64_maxlen = b64.len();
        let mut acc_len = 0usize;
        let mut b64_pos = 0usize;
        let mut acc = 0u16;

        let nibbles = bin_len / 3;
        let remainder = bin_len - 3 * nibbles;
        let mut b64_len = nibbles * 4;
        if remainder != 0 {
            if (variant as u16 & VariantMask::NoPadding as u16) == 0 {
                b64_len += 4;
            } else {
                b64_len += 2 + (remainder >> 1);
            }
        }
        if b64_maxlen < b64_len {
            return Err(Error::Overflow);
        }
        if (variant as u16 & VariantMask::UrlSafe as u16) != 0 {
            for &v in bin {
                acc = (acc << 8) + v as u16;
                acc_len += 8;
                while acc_len >= 6 {
                    acc_len -= 6;
                    b64[b64_pos] = Self::b64_byte_to_urlsafe_char(((acc >> acc_len) & 0x3f) as u8);
                    b64_pos += 1;
                }
            }
            if acc_len > 0 {
                b64[b64_pos] =
                    Self::b64_byte_to_urlsafe_char(((acc << (6 - acc_len)) & 0x3f) as u8);
                b64_pos += 1;
            }
        } else {
            for &v in bin {
                acc = (acc << 8) + v as u16;
                acc_len += 8;
                while acc_len >= 6 {
                    acc_len -= 6;
                    b64[b64_pos] = Self::b64_byte_to_char(((acc >> acc_len) & 0x3f) as u8);
                    b64_pos += 1;
                }
            }
            if acc_len > 0 {
                b64[b64_pos] = Self::b64_byte_to_char(((acc << (6 - acc_len)) & 0x3f) as u8);
                b64_pos += 1;
            }
        }
        while b64_pos < b64_len {
            b64[b64_pos] = b'=';
            b64_pos += 1
        }
        Ok(&b64[..b64_pos])
    }

    fn skip_padding<'t>(
        b64: &'t [u8],
        mut padding_len: usize,
        ignore: Option<&[u8]>,
    ) -> Result<&'t [u8], Error> {
        let b64_len = b64.len();
        let mut b64_pos = 0usize;
        while padding_len > 0 {
            if b64_pos >= b64_len {
                return Err(Error::InvalidInput);
            }
            let c = b64[b64_pos];
            if c == b'=' {
                padding_len -= 1
            } else {
                match ignore {
                    Some(ignore) if ignore.contains(&c) => {}
                    _ => return Err(Error::InvalidInput),
                }
            }
            b64_pos += 1
        }
        Ok(&b64[b64_pos..])
    }

    pub fn decode<'t>(
        bin: &'t mut [u8],
        b64: &[u8],
        ignore: Option<&[u8]>,
        variant: Base64Variant,
    ) -> Result<&'t [u8], Error> {
        let bin_maxlen = bin.len();
        let is_urlsafe = (variant as u16 & VariantMask::UrlSafe as u16) != 0;
        let mut acc = 0u16;
        let mut acc_len = 0usize;
        let mut bin_pos = 0usize;
        let mut premature_end = None;
        for (b64_pos, &c) in b64.iter().enumerate() {
            let d = if is_urlsafe {
                Self::b64_urlsafe_char_to_byte(c)
            } else {
                Self::b64_char_to_byte(c)
            };
            if d == 0xff {
                match ignore {
                    Some(ignore) if ignore.contains(&c) => continue,
                    _ => {
                        premature_end = Some(b64_pos);
                        break;
                    }
                }
            }
            acc = (acc << 6) + d as u16;
            acc_len += 6;
            if acc_len >= 8 {
                acc_len -= 8;
                if bin_pos >= bin_maxlen {
                    return Err(Error::Overflow);
                }
                bin[bin_pos] = (acc >> acc_len) as u8;
                bin_pos += 1;
            }
        }
        if acc_len > 4 || (acc & ((1u16 << acc_len).wrapping_sub(1))) != 0 {
            return Err(Error::InvalidInput);
        }
        let padding_len = acc_len / 2;
        if let Some(premature_end) = premature_end {
            let remaining = if variant as u16 & VariantMask::NoPadding as u16 == 0 {
                Self::skip_padding(&b64[premature_end..], padding_len, ignore)?
            } else {
                &b64[premature_end..]
            };
            match ignore {
                None => {
                    if !remaining.is_empty() {
                        return Err(Error::InvalidInput);
                    }
                }
                Some(ignore) => {
                    for &c in remaining {
                        if !ignore.contains(&c) {
                            return Err(Error::InvalidInput);
                        }
                    }
                }
            }
        } else if variant as u16 & VariantMask::NoPadding as u16 == 0 && padding_len != 0 {
            return Err(Error::InvalidInput);
        }
        Ok(&bin[..bin_pos])
    }
}

/// Standard Base64 encoder and decoder with padding.
///
/// This implementation follows the standard Base64 encoding as defined in RFC 4648,
/// and includes padding characters ('=') when needed.
///
/// # Standard Base64 Alphabet
///
/// The standard Base64 alphabet uses characters:
/// - 'A' to 'Z' (26 characters)
/// - 'a' to 'z' (26 characters)
/// - '0' to '9' (10 characters)
/// - '+' and '/' (2 characters)
/// - '=' (padding character)
///
/// # Examples
///
/// ```
/// use ct_codecs::{Base64, Encoder, Decoder};
///
/// let data = b"Hello, world!";
/// # let result = 
/// let encoded = Base64::encode_to_string(data)?;
/// assert_eq!(encoded, "SGVsbG8sIHdvcmxkIQ==");
///
/// let decoded = Base64::decode_to_vec(&encoded, None)?;
/// assert_eq!(decoded, data);
/// # Ok::<(), ct_codecs::Error>(())
/// ```
pub struct Base64;

/// Standard Base64 encoder and decoder without padding.
///
/// This implementation follows the standard Base64 encoding as defined in RFC 4648,
/// but omits padding characters ('=').
///
/// # Examples
///
/// ```
/// use ct_codecs::{Base64NoPadding, Encoder, Decoder};
///
/// let data = b"Hello, world!";
/// # let result = 
/// let encoded = Base64NoPadding::encode_to_string(data)?;
/// assert_eq!(encoded, "SGVsbG8sIHdvcmxkIQ");
///
/// let decoded = Base64NoPadding::decode_to_vec(&encoded, None)?;
/// assert_eq!(decoded, data);
/// # Ok::<(), ct_codecs::Error>(())
/// ```
pub struct Base64NoPadding;

/// URL-safe Base64 encoder and decoder with padding.
///
/// This implementation follows the URL-safe Base64 encoding variant as defined in RFC 4648.
/// It replaces the '+' and '/' characters with '-' and '_' to make the output URL and
/// filename safe. Padding characters ('=') are included when needed.
///
/// # URL-safe Base64 Alphabet
///
/// The URL-safe Base64 alphabet uses characters:
/// - 'A' to 'Z' (26 characters)
/// - 'a' to 'z' (26 characters)
/// - '0' to '9' (10 characters)
/// - '-' and '_' (2 characters)
/// - '=' (padding character)
///
/// # Examples
///
/// ```
/// use ct_codecs::{Base64UrlSafe, Encoder, Decoder};
///
/// let data = b"Hello, world!";
/// # let result = 
/// let encoded = Base64UrlSafe::encode_to_string(data)?;
/// assert_eq!(encoded, "SGVsbG8sIHdvcmxkIQ==");
///
/// // If the input contains characters that would be escaped in URLs
/// let binary_data = &[251, 239, 190, 222];
/// let encoded = Base64UrlSafe::encode_to_string(binary_data)?;
/// assert_eq!(encoded, "---e3g==");
/// # Ok::<(), ct_codecs::Error>(())
/// ```
pub struct Base64UrlSafe;

/// URL-safe Base64 encoder and decoder without padding.
///
/// This implementation follows the URL-safe Base64 encoding variant as defined in RFC 4648,
/// but omits padding characters ('='). This is particularly useful for URLs, where the
/// padding character may need to be percent-encoded.
///
/// # Examples
///
/// ```
/// use ct_codecs::{Base64UrlSafeNoPadding, Encoder, Decoder};
///
/// let data = b"Hello, world!";
/// # let result = 
/// let encoded = Base64UrlSafeNoPadding::encode_to_string(data)?;
/// assert_eq!(encoded, "SGVsbG8sIHdvcmxkIQ");
///
/// // With binary data containing characters that would be escaped in URLs
/// let binary_data = &[251, 239, 190, 222];
/// let encoded = Base64UrlSafeNoPadding::encode_to_string(binary_data)?;
/// assert_eq!(encoded, "---e3g");
/// # Ok::<(), ct_codecs::Error>(())
/// ```
pub struct Base64UrlSafeNoPadding;

impl Encoder for Base64 {
    #[inline]
    fn encoded_len(bin_len: usize) -> Result<usize, Error> {
        Base64Impl::encoded_len(bin_len, Base64Variant::Original)
    }

    #[inline]
    fn encode<IN: AsRef<[u8]>>(b64: &mut [u8], bin: IN) -> Result<&[u8], Error> {
        Base64Impl::encode(b64, bin.as_ref(), Base64Variant::Original)
    }
}

impl Decoder for Base64 {
    #[inline]
    fn decode<'t, IN: AsRef<[u8]>>(
        bin: &'t mut [u8],
        b64: IN,
        ignore: Option<&[u8]>,
    ) -> Result<&'t [u8], Error> {
        Base64Impl::decode(bin, b64.as_ref(), ignore, Base64Variant::Original)
    }
}

impl Encoder for Base64NoPadding {
    #[inline]
    fn encoded_len(bin_len: usize) -> Result<usize, Error> {
        Base64Impl::encoded_len(bin_len, Base64Variant::OriginalNoPadding)
    }

    #[inline]
    fn encode<IN: AsRef<[u8]>>(b64: &mut [u8], bin: IN) -> Result<&[u8], Error> {
        Base64Impl::encode(b64, bin.as_ref(), Base64Variant::OriginalNoPadding)
    }
}

impl Decoder for Base64NoPadding {
    #[inline]
    fn decode<'t, IN: AsRef<[u8]>>(
        bin: &'t mut [u8],
        b64: IN,
        ignore: Option<&[u8]>,
    ) -> Result<&'t [u8], Error> {
        Base64Impl::decode(bin, b64.as_ref(), ignore, Base64Variant::OriginalNoPadding)
    }
}

impl Encoder for Base64UrlSafe {
    #[inline]
    fn encoded_len(bin_len: usize) -> Result<usize, Error> {
        Base64Impl::encoded_len(bin_len, Base64Variant::UrlSafe)
    }

    #[inline]
    fn encode<IN: AsRef<[u8]>>(b64: &mut [u8], bin: IN) -> Result<&[u8], Error> {
        Base64Impl::encode(b64, bin.as_ref(), Base64Variant::UrlSafe)
    }
}

impl Decoder for Base64UrlSafe {
    #[inline]
    fn decode<'t, IN: AsRef<[u8]>>(
        bin: &'t mut [u8],
        b64: IN,
        ignore: Option<&[u8]>,
    ) -> Result<&'t [u8], Error> {
        Base64Impl::decode(bin, b64.as_ref(), ignore, Base64Variant::UrlSafe)
    }
}

impl Encoder for Base64UrlSafeNoPadding {
    #[inline]
    fn encoded_len(bin_len: usize) -> Result<usize, Error> {
        Base64Impl::encoded_len(bin_len, Base64Variant::UrlSafeNoPadding)
    }

    #[inline]
    fn encode<IN: AsRef<[u8]>>(b64: &mut [u8], bin: IN) -> Result<&[u8], Error> {
        Base64Impl::encode(b64, bin.as_ref(), Base64Variant::UrlSafeNoPadding)
    }
}

impl Decoder for Base64UrlSafeNoPadding {
    #[inline]
    fn decode<'t, IN: AsRef<[u8]>>(
        bin: &'t mut [u8],
        b64: IN,
        ignore: Option<&[u8]>,
    ) -> Result<&'t [u8], Error> {
        Base64Impl::decode(bin, b64.as_ref(), ignore, Base64Variant::UrlSafeNoPadding)
    }
}

#[cfg(feature = "std")]
#[test]
fn test_base64() {
    let bin = [1u8, 5, 11, 15, 19, 131, 122];
    let expected = "AQULDxODeg==";
    let b64 = Base64::encode_to_string(bin).unwrap();
    assert_eq!(b64, expected);
    let bin2 = Base64::decode_to_vec(&b64, None).unwrap();
    assert_eq!(bin, &bin2[..]);
}

#[cfg(feature = "std")]
#[test]
fn test_base64_mising_padding() {
    let missing_padding = "AA";
    assert!(Base64::decode_to_vec(missing_padding, None).is_err());
    assert!(Base64NoPadding::decode_to_vec(missing_padding, None).is_ok());
    let missing_padding = "AAA";
    assert!(Base64::decode_to_vec(missing_padding, None).is_err());
    assert!(Base64NoPadding::decode_to_vec(missing_padding, None).is_ok());
}

#[test]
fn test_base64_no_std() {
    let bin = [1u8, 5, 11, 15, 19, 131, 122];
    let expected = [65, 81, 85, 76, 68, 120, 79, 68, 101, 103, 61, 61];
    let mut b64 = [0u8; 12];
    let b64 = Base64::encode(&mut b64, bin).unwrap();
    assert_eq!(b64, expected);
    let mut bin2 = [0u8; 7];
    let bin2 = Base64::decode(&mut bin2, b64, None).unwrap();
    assert_eq!(bin, bin2);
}

#[test]
fn test_base64_invalid_padding() {
    let valid_padding = "AA==";
    assert_eq!(Base64::decode_to_vec(valid_padding, None), Ok(vec![0u8; 1]));
    let invalid_padding = "AA=";
    assert_eq!(
        Base64::decode_to_vec(invalid_padding, None),
        Err(Error::InvalidInput)
    );
}