use super::funejson::Value; const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; /// Bytes as RFC 4648 base32: five bits per character, upper case, padded /// with = to a multiple of eight characters when `padding` is true. /// /// # Panics /// Panics if any value is outside 0-255. pub fn base32_encode(bytes: &[i64], padding: bool) -> String { let mut out = String::with_capacity(bytes.len() * 8 / 5 + 8); let mut buffer: u32 = 0; let mut bits = 0; for &b in bytes { if !(0..=255).contains(&b) { panic!("bytes must be a list of integers from 0 to 255"); } buffer = ((buffer << 8) | b as u32) & 0xfff; bits += 8; while bits >= 5 { out.push(ALPHABET[((buffer >> (bits - 5)) & 31) as usize] as char); bits -= 5; } } if bits > 0 { out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char); } if padding { while out.len() % 8 != 0 { out.push('='); } } out } pub fn fune_vector(args: &[Value]) -> Value { let bytes: Vec = match &args[0] { Value::Arr(items) => items .iter() .map(|item| match item { Value::Int(i) => *i, _ => panic!("bytes must be a list of integers from 0 to 255"), }) .collect(), _ => panic!("bytes must be a list of integers from 0 to 255"), }; let padding = match &args[1] { Value::Bool(b) => *b, _ => panic!("padding must be true or false"), }; Value::str(&base32_encode(&bytes, padding)) }