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
//! Wrappers for values that should be serialized or represented as base64
//!
//! ## Example
//!
//! ```
//! use aliri_core::base64::Base64;
//!
//! let data = Base64::from_raw("👋 hello, world! 👋".as_bytes());
//! let enc = data.to_string();
//! assert_eq!(enc, "8J+RiyBoZWxsbywgd29ybGQhIPCfkYs=");
//! ```
//!
//! ```
//! use aliri_core::base64::{Base64, Base64Url};
//!
//! let data = Base64Url::from_encoded("8J-RiyBoZWxsbywgd29ybGQhIPCfkYs").unwrap();
//! assert_eq!(data.as_slice(), "👋 hello, world! 👋".as_bytes());
//! let transcode = Base64::from_raw(data.into_inner());
//! let enc = transcode.to_string();
//! assert_eq!(enc, "8J+RiyBoZWxsbywgd29ybGQhIPCfkYs=");
//! ```

use std::{error::Error, fmt};

/// An error while decoding a value which is not properly formatted
/// base64 data
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvalidBase64Data {
    source: ::base64::DecodeError,
}

impl From<::base64::DecodeError> for InvalidBase64Data {
    fn from(err: ::base64::DecodeError) -> Self {
        Self { source: err }
    }
}

impl fmt::Display for InvalidBase64Data {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("invalid base64 data")
    }
}

impl Error for InvalidBase64Data {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.source)
    }
}

macro_rules! b64_builder {
    {
        $(#[$meta:meta])*
        $v:vis struct $ty:ident ($config:expr, $is_padded:expr);

        $(#[$meta_ref:meta])*
        $v_ref:vis struct $ty_ref:ident;
    } => {
        #[derive(Clone, Eq, PartialEq, Hash)]
        #[repr(transparent)]
        $(#[$meta])*
        ///
        /// Data is held in memory in its raw form. Costs of serialization
        /// are only incurred when serializing or displaying the value in
        /// its base64 representation.
        ///
        /// Data is held in memory in its raw form. Costs of converting to
        /// base64 form are only incurred when serializing or displaying the
        /// value. Cost of converting from base64 form are incurred on calling
        /// `from_encoded`.
        $v struct $ty(Vec<u8>);

        impl $ty {
            /// Creates a new buffer from an owned value
            ///
            /// To decode a base64-encoded buffer, use `from_encoded`.
            #[inline]
            pub fn from_raw<T: Into<Vec<u8>>>(raw: T) -> Self {
                Self(raw.into())
            }

            /// Constructs a new buffer from a base64-encoded slice
            pub fn from_encoded<T: AsRef<[u8]>>(enc: T) -> Result<Self, InvalidBase64Data> {
                let data = ::base64::decode_config(enc, $config)?;
                Ok(Self(data))
            }

            /// Unwraps the underlying buffer
            #[inline]
            pub fn into_inner(self) -> Vec<u8> {
                self.0
            }

            /// Calculates the expected length of the base64-encoding for a buffer of size `len`
            #[inline]
            pub fn calc_encoded_len(len: usize) -> usize {
                if $is_padded {
                    (len + 2) / 3 * 4
                } else {
                    let d = len / 3 * 4;
                    let m = len % 3;
                    if m > 0 {
                        d + m + 1
                    } else {
                        d
                    }
                }
            }
        }

        impl From<Vec<u8>> for $ty {
            #[inline]
            fn from(buf: Vec<u8>) -> Self {
                Self(buf)
            }
        }

        impl From<&'_ [u8]> for $ty {
            #[inline]
            fn from(slice: &[u8]) -> Self {
                Self::from_raw(slice)
            }
        }

        impl<'a> From<&'a [u8]> for &'a $ty_ref {
            #[inline]
            fn from(slice: &'a [u8]) -> Self {
                $ty_ref::from_slice(slice)
            }
        }

        impl From<&'_ $ty_ref> for $ty {
            #[inline]
            fn from(val: &$ty_ref) -> Self {
                Self::from(val.as_slice())
            }
        }

        impl From<$ty> for Vec<u8> {
            #[inline]
            fn from(val: $ty) -> Self {
                val.0
            }
        }

        impl ::std::borrow::Borrow<$ty_ref> for $ty {
            #[inline]
            fn borrow(&self) -> &$ty_ref {
                &self
            }
        }

        impl ::std::ops::Deref for $ty {
            type Target = $ty_ref;

            #[inline]
            fn deref(&self) -> &Self::Target {
                $ty_ref::from_slice(self.0.as_slice())
            }
        }

        impl ::std::ops::DerefMut for $ty {
            #[inline]
            fn deref_mut(&mut self) -> &mut $ty_ref {
                $ty_ref::from_mut_slice(self.0.as_mut_slice())
            }
        }

        impl AsRef<$ty_ref> for $ty {
            #[inline]
            fn as_ref(&self) -> &$ty_ref {
                &self
            }
        }

        impl ::std::fmt::Display for $ty {
            #[inline]
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                ::std::fmt::Display::fmt(&**self, f)
            }
        }

        impl ::std::fmt::Debug for $ty {
            #[inline]
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                ::std::fmt::Debug::fmt(&**self, f)
            }
        }

        impl ::serde::Serialize for $ty {
            #[inline]
            fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                self.as_ref().serialize(serializer)
            }
        }

        impl<'de> ::serde::Deserialize<'de> for $ty {
            fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let raw: &[u8] = ::serde::Deserialize::deserialize(deserializer)?;
                let data = base64::decode_config(raw, $config)
                    .map_err(serde::de::Error::custom)?;
                Ok(Self(data))
            }
        }

        #[derive(Hash, PartialEq, Eq)]
        #[repr(transparent)]
        $(#[$meta_ref])*
        ///
        /// Data is borrowed in its raw form. Costs of converting to base64
        /// form are only incurred when serializing or displaying the value.
        $v_ref struct $ty_ref([u8]);

        impl $ty_ref {
            #[allow(unsafe_code)]
            #[inline]
            /// Transparently reinterprets the slice as base64
            pub fn from_slice(raw: &[u8]) -> &Self {
                let ptr: *const [u8] = raw;

                // This type is a transparent wrapper around an `[u8]`, so this
                // transformation is safe to do.
                unsafe {
                    &*(ptr as *const Self)
                }
            }

            #[allow(unsafe_code)]
            #[inline]
            /// Transparently reinterprets the mutable slice as base64
            pub fn from_mut_slice(raw: &mut [u8]) -> &mut Self {
                let ptr: *mut [u8] = raw;

                // This type is a transparent wrapper around an `[u8]`, so this
                // transformation is safe to do.
                unsafe {
                    &mut *(ptr as *mut Self)
                }
            }

            /// Calculates the expected length of the base64-encoding of this buffer
            #[inline]
            pub fn encoded_len(&self) -> usize {
                $ty::calc_encoded_len(self.as_slice().len())
            }

            /// Provides access to the underlying slice
            #[inline]
            pub const fn as_slice(&self) -> &[u8] {
                &self.0
            }

            /// Provides mutable access to the underlying slice
            #[inline]
            pub fn as_mut_slice(&mut self) -> &mut [u8] {
                &mut self.0
            }
        }

        impl ToOwned for $ty_ref {
            type Owned = $ty;

            #[inline]
            fn to_owned(&self) -> Self::Owned {
                $ty(self.0.to_owned())
            }
        }

        impl PartialEq<$ty_ref> for $ty {
            #[inline]
            fn eq(&self, other: &$ty_ref) -> bool {
                self.0 == &other.0
            }
        }

        impl PartialEq<$ty> for $ty_ref {
            #[inline]
            fn eq(&self, other: &$ty) -> bool {
                &self.0 == other.0.as_slice()
            }
        }

        impl ::std::fmt::Display for $ty_ref {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                let encoded = ::base64::encode_config(&self.0, $config);
                f.write_str(&encoded)
            }
        }

        impl ::std::fmt::Debug for $ty_ref {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                let encoded = ::base64::encode_config(&self.0, $config);
                write!(f, "`{}`", encoded)
            }
        }

        impl ::serde::Serialize for $ty_ref {
            fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                let encoded = ::base64::encode_config(&self.0, $config);
                serializer.serialize_str(encoded.as_str())
            }
        }
    }
}

b64_builder! {
    /// Owned data to be encoded as standard base64
    ///
    /// Encoding alphabet: `A`–`Z`, `a`–`z`, `0`–`9`, `+`, `/`
    ///
    /// Padding character: `=`
    pub struct Base64(base64::STANDARD, true);

    /// Borrowed data to be encoded as standard base64
    ///
    /// Encoding alphabet: `A`–`Z`, `a`–`z`, `0`–`9`, `+`, `/`
    ///
    /// Padding character: `=`
    pub struct Base64Ref;
}

b64_builder! {
    /// Owned data to be encoded as URL-safe base64 (no padding)
    ///
    /// Encoding alphabet: `A`–`Z`, `a`–`z`, `0`–`9`, `-`, `_`
    pub struct Base64Url(base64::URL_SAFE_NO_PAD, false);

    /// Borrowed data to be encoded as URL-safe base64 (no padding)
    ///
    /// Encoding alphabet: `A`–`Z`, `a`–`z`, `0`–`9`, `-`, `_`
    pub struct Base64UrlRef;
}

#[cfg(doctest)]
#[doc(hidden)]
mod doctests {
    /// Verifies that `from_slice` does not extend lifetimes
    ///
    /// ```compile_fail
    /// use aliri_core::base64::Base64UrlRef;
    ///
    /// let b64 = {
    ///     let data = vec![0; 16];
    ///     Base64UrlRef::from_slice(data.as_slice())
    /// };
    ///
    /// println!("{}", b64);
    /// ```
    fn base64url_from_slice_does_not_extend_lifetimes() -> ! {
        loop {}
    }

    /// Verifies that `from_mut_slice` does not extend lifetimes
    ///
    /// ```compile_fail
    /// use aliri_core::base64::Base64UrlRef;
    ///
    /// let b64 = {
    ///     let mut data = vec![0; 16];
    ///     Base64UrlRef::from_mut_slice(data.as_mut_slice())
    /// };
    ///
    /// println!("{}", b64);
    /// ```
    fn base64url_from_mut_slice_does_not_extend_lifetimes() -> ! {
        loop {}
    }

    /// Verifies that `from_slice` does not extend lifetimes
    ///
    /// ```compile_fail
    /// use aliri_core::base64::Base64Ref;
    ///
    /// let b64 = {
    ///     let data = vec![0; 16];
    ///     Base64Ref::from_slice(data.as_slice())
    /// };
    ///
    /// println!("{}", b64);
    /// ```
    fn base64_from_slice_does_not_extend_lifetimes() -> ! {
        loop {}
    }

    /// Verifies that `from_mut_slice` does not extend lifetimes
    ///
    /// ```compile_fail
    /// use aliri_core::base64::Base64Ref;
    ///
    /// let b64 = {
    ///     let mut data = vec![0; 16];
    ///     Base64Ref::from_mut_slice(data.as_mut_slice())
    /// };
    ///
    /// println!("{}", b64);
    /// ```
    fn base64_from_mut_slice_does_not_extend_lifetimes() -> ! {
        loop {}
    }
}