macro_toolset/string_v2/base64.rs
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
//! Base64 string utilities.
use std::{marker::PhantomData, ops};
use super::{NumStr, StringExtT, StringT};
pub mod b64_padding {
//! Base64 padding
//!
//! The `base64` crate has ugly APIs and we here create some ZSTs
//! to represent the padding, convenient to use and performance improvement.
use super::{
Base64Str, Decode, DecodeToAny, DecodeToHex, Encode, NumStr, PhantomData, StringExtT,
StringT,
};
macro_rules! enum_padding {
($($name:ident) *) => {
$(
#[derive(Debug)]
#[allow(non_camel_case_types)]
#[doc = "Base64 Padding: "]
#[doc = stringify!($name) ]
pub struct $name;
impl $name {
#[inline]
/// Create a new [`Base64Str`], and finally encode it to a Base64 string.
pub fn encode<T: AsRef<[u8]>>(inner: T) -> Base64Str<T, $name, Encode> {
Base64Str {
inner,
padding: PhantomData,
command: PhantomData,
}
}
#[inline]
/// Create a new [`Base64Str`], and finally decode the inner Base64 string.
///
/// Notice: will do nothing if the decoded string is not valid UTF-8 encoded.
/// If that is acceptable, use [`decode_to_any`](Self::decode_to_any).
pub fn decode<T: AsRef<[u8]>>(inner: T) -> Base64Str<T, $name, Decode> {
Base64Str {
inner,
padding: PhantomData,
command: PhantomData,
}
}
#[allow(unsafe_code, reason = "Calling this means the decoded string can be invalid UTF-8")]
#[inline]
/// Create a new [`Base64Str`], and finally decode the inner Base64 string.
///
/// # Safety
///
/// Calling this means the decoded string can be invalid UTF-8.
pub unsafe fn decode_to_any<T: AsRef<[u8]>>(inner: T) -> Base64Str<T, $name, DecodeToAny> {
Base64Str {
inner,
padding: PhantomData,
command: PhantomData,
}
}
#[inline]
/// Create a new [`Base64Str`], and finally decode the inner Base64 string.
///
/// Notice: will do nothing if the inner string is not a valid Base64 string.
pub fn decode_to_hex<T: AsRef<[u8]>>(inner: T) -> Base64Str<T, $name, DecodeToHex> {
Base64Str {
inner,
padding: PhantomData,
command: PhantomData,
}
}
}
impl<T: AsRef<[u8]>> StringT for Base64Str<T, $name, Encode> {
#[inline]
fn encode_to_buf(self, string: &mut Vec<u8>) {
let inner = self.inner.as_ref();
let current_len = string.len();
let base64_len = inner.len() * 4 / 3 + 4;
let target_len = current_len + base64_len;
string.reserve_exact(base64_len);
#[allow(unsafe_code)]
// Safety: have reserved and allocate enough space
unsafe {
string.set_len(target_len);
}
let bytes_written = base64::Engine::encode_slice(
&base64::engine::general_purpose::$name,
self.inner,
&mut string[current_len..target_len],
)
.unwrap_or(0);
string.truncate(current_len + bytes_written);
}
#[inline]
fn encode_to_buf_with_separator(self, string: &mut Vec<u8>, separator: &str) {
self.encode_to_buf(string);
string.extend(separator.as_bytes());
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf(self, string: &mut bytes::BytesMut) {
let inner = self.inner.as_ref();
let current_len = string.len();
let base64_len = inner.len() * 4 / 3 + 4;
let target_len = current_len + base64_len;
string.reserve(base64_len);
#[allow(unsafe_code)]
// Safety: have reserved and allocate enough space
unsafe {
string.set_len(target_len);
}
let bytes_written = base64::Engine::encode_slice(
&base64::engine::general_purpose::$name,
self.inner,
&mut string[current_len..target_len],
)
.unwrap_or(0);
string.truncate(current_len + bytes_written);
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf_with_separator(self, string: &mut bytes::BytesMut, separator: &str) {
self.encode_to_bytes_buf(string);
string.extend(separator.as_bytes());
}
}
impl<T: AsRef<[u8]>> StringExtT for Base64Str<T, $name, Encode> {}
impl<T: AsRef<[u8]>> StringT for Base64Str<T, $name, Decode> {
#[inline]
fn encode_to_buf(self, string: &mut Vec<u8>) {
use base64::Engine;
let data = base64::engine::general_purpose::$name
.decode(self.inner.as_ref())
.unwrap_or_default();
if std::str::from_utf8(&data).is_ok() {
string.extend(data)
}
}
#[inline]
fn encode_to_buf_with_separator(self, string: &mut Vec<u8>, separator: &str) {
self.encode_to_buf(string);
string.extend(separator.as_bytes());
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf(self, string: &mut bytes::BytesMut) {
use base64::Engine;
let data = base64::engine::general_purpose::$name
.decode(self.inner.as_ref())
.unwrap_or_default();
if std::str::from_utf8(&data).is_ok() {
string.extend(data)
}
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf_with_separator(self, string: &mut bytes::BytesMut, separator: &str) {
self.encode_to_bytes_buf(string);
string.extend(separator.as_bytes());
}
}
impl<T: AsRef<[u8]>> StringExtT for Base64Str<T, $name, Decode> {}
impl<T: AsRef<[u8]>> StringT for Base64Str<T, $name, DecodeToAny> {
#[inline]
fn encode_to_buf(self, string: &mut Vec<u8>) {
use base64::Engine;
let _ = base64::engine::general_purpose::$name
.decode_vec(self.inner.as_ref(), string);
}
#[inline]
fn encode_to_buf_with_separator(self, string: &mut Vec<u8>, separator: &str) {
self.encode_to_buf(string);
string.extend(separator.as_bytes());
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf(self, string: &mut bytes::BytesMut) {
use base64::Engine;
if let Ok(data) = base64::engine::general_purpose::$name.decode(self.inner.as_ref()) {
string.extend(data);
}
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf_with_separator(self, string: &mut bytes::BytesMut, separator: &str) {
self.encode_to_bytes_buf(string);
string.extend(separator.as_bytes());
}
}
impl<T: AsRef<[u8]>> StringExtT for Base64Str<T, $name, DecodeToAny> {}
impl<T: AsRef<[u8]>> StringT for Base64Str<T, $name, DecodeToHex> {
#[inline]
fn encode_to_buf(self, string: &mut Vec<u8>) {
use base64::Engine;
base64::engine::general_purpose::$name
.decode(self.inner.as_ref())
.unwrap_or_default()
.into_iter()
.map(NumStr::hex_byte_default)
.encode_to_buf(string);
}
#[inline]
fn encode_to_buf_with_separator(self, string: &mut Vec<u8>, separator: &str) {
self.encode_to_buf(string);
string.extend(separator.as_bytes());
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf(self, string: &mut bytes::BytesMut) {
use base64::Engine;
base64::engine::general_purpose::$name
.decode(self.inner.as_ref())
.unwrap_or_default()
.into_iter()
.map(NumStr::hex_byte_default)
.encode_to_bytes_buf(string);
}
#[inline]
#[cfg(feature = "feat-string-ext-bytes")]
fn encode_to_bytes_buf_with_separator(self, string: &mut bytes::BytesMut, separator: &str) {
self.encode_to_bytes_buf(string);
string.extend(separator.as_bytes());
}
}
impl<T: AsRef<[u8]>> StringExtT for Base64Str<T, $name, DecodeToHex> {}
)*
};
}
enum_padding!(STANDARD STANDARD_NO_PAD URL_SAFE URL_SAFE_NO_PAD);
}
#[derive(Debug)]
/// Command: Encode, ZST marker struct
pub struct Encode;
#[derive(Debug)]
/// Command: Decode, ZST marker struct
///
/// Notice: Will do nothing if the decoded string is not valid UTF-8 encoded.
pub struct Decode;
#[derive(Debug)]
/// Command: Decode, ZST marker struct
///
/// This means the decoded string can be invalid UTF-8.
pub struct DecodeToAny;
#[derive(Debug)]
/// Command: Decode, ZST marker struct
///
/// This means the decoded byte will be hex encoded, lowercase.
pub struct DecodeToHex;
#[derive(Debug)]
#[repr(transparent)]
/// Base64 string, to encode or decode.
///
/// This struct can only be created by [`b64_padding::STANDARD`], etc.
///
/// Notice: will do nothing if the inner is not base64 encoded when decoding.
pub struct Base64Str<T: AsRef<[u8]>, P = b64_padding::STANDARD, C = Encode> {
inner: T,
padding: PhantomData<P>,
command: PhantomData<C>,
}
impl<T: AsRef<[u8]>, P, C> ops::Deref for Base64Str<T, P, C> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: AsRef<[u8]>, P, C> AsRef<[u8]> for Base64Str<T, P, C> {
fn as_ref(&self) -> &[u8] {
self.inner.as_ref()
}
}
#[allow(unsafe_code, reason = "test unsafe")]
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_base64() {
assert_eq!(
b64_padding::STANDARD::encode(b"hello world").to_string_ext(),
"aGVsbG8gd29ybGQ="
);
assert_eq!(
b64_padding::STANDARD::encode(b"hello world").to_string_ext(),
"aGVsbG8gd29ybGQ="
);
assert_eq!(
b64_padding::STANDARD::encode("hello world").to_string_ext(),
"aGVsbG8gd29ybGQ="
);
assert_eq!(
b64_padding::STANDARD::encode("hello world").to_string_ext(),
"aGVsbG8gd29ybGQ="
);
assert_eq!(
b64_padding::STANDARD::decode(b"aGVsbG8gd29ybGQ=").to_string_ext(),
"hello world"
);
assert_eq!(
unsafe { b64_padding::STANDARD::decode_to_any(b"aGVsbG8gd29ybGQ=") }.to_string_ext(),
"hello world"
);
assert_eq!(
b64_padding::STANDARD::decode_to_hex(
b64_padding::STANDARD::encode(vec![0x11, 0x45, 0x14, 0x19, 0x19, 0x81, 0x00])
.to_string_ext()
)
.to_string_ext(),
"11451419198100"
);
}
}