1use base64::{Engine, engine::general_purpose::STANDARD};2use jrsonnet_evaluator::{3 IBytes, IStr, Result, bail,4 function::builtin,5 runtime_error,6 typed::{Either, Either2},7};89#[builtin]10pub fn builtin_encode_utf8(str: IStr) -> IBytes {11 str.cast_bytes()12}1314#[builtin]15pub fn builtin_decode_utf8(arr: IBytes, #[default(true)] lossy: bool) -> Result<IStr> {16 match arr.clone().cast_str() {17 Some(s) => Ok(s),18 None if lossy => Ok(String::from_utf8_lossy(arr.as_slice()).into()),19 None => {20 bail!("bad utf8")21 }22 }23}2425#[builtin]26pub fn builtin_base64(input: Either![IStr, IBytes]) -> String {27 use Either2::*;28 match input {29 A(l) => STANDARD.encode(l.as_bytes()),30 B(a) => STANDARD.encode(a.as_slice()),31 }32}3334#[builtin]35pub fn builtin_base64_decode_bytes(str: IStr) -> Result<IBytes> {36 Ok(STANDARD37 .decode(str.as_bytes())38 .map_err(|e| runtime_error!("invalid base64: {e}"))?39 .as_slice()40 .into())41}4243#[builtin]44pub fn builtin_base64_decode(str: IStr, #[default(false)] lossy: bool) -> Result<String> {45 let bytes = STANDARD46 .decode(str.as_bytes())47 .map_err(|e| runtime_error!("invalid base64: {e}"))?;48 if lossy {49 Ok(String::from_utf8_lossy(&bytes).to_string())50 } else {51 String::from_utf8(bytes).map_err(|e| runtime_error!("bad utf8: {e}"))52 }53}