aws_smithy_types/
base64.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! A thin wrapper over [`base64-simd`](https://docs.rs/base64-simd/)
7
8use base64_simd::STANDARD;
9use std::error::Error;
10
11/// Failure to decode a base64 value.
12#[derive(Debug)]
13pub struct DecodeError(base64_simd::Error);
14
15impl Error for DecodeError {
16    fn source(&self) -> Option<&(dyn Error + 'static)> {
17        Some(&self.0)
18    }
19}
20
21impl std::fmt::Display for DecodeError {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        write!(f, "failed to decode base64")
24    }
25}
26
27/// Decode `input` from base64 using the standard base64 alphabet
28///
29/// If input is not a valid base64 encoded string, this function will return `DecodeError`.
30pub fn decode(input: impl AsRef<str>) -> Result<Vec<u8>, DecodeError> {
31    STANDARD.decode_to_vec(input.as_ref()).map_err(DecodeError)
32}
33
34/// Encode `input` into base64 using the standard base64 alphabet
35pub fn encode(input: impl AsRef<[u8]>) -> String {
36    STANDARD.encode_to_string(input.as_ref())
37}
38
39/// Returns the base64 representation's length for the given `length` of data
40pub fn encoded_length(length: usize) -> usize {
41    STANDARD.encoded_length(length)
42}