use super::funejson::Value; /// Padding that each count of data characters past a multiple of 8 needs; /// -1 marks the counts no byte string produces. const PAD: [i64; 8] = [0, -1, 6, -1, 4, 3, -1, 1]; fn quintet(c: char) -> i64 { match c { 'A'..='Z' => c as i64 - 65, 'a'..='z' => c as i64 - 97, '2'..='7' => c as i64 - 24, _ => -1, } } /// RFC 4648 base32 back to bytes. Either case; = padding optional but exact /// when present; no spaces or other characters; zero bits after the last /// byte. /// /// # Panics /// Panics on a character outside the alphabet, padding that is wrong or not /// at the end, an impossible length, or non-zero trailing bits. pub fn base32_decode(text: &str) -> Vec { let mut values: Vec = Vec::with_capacity(text.len()); let mut padding = 0i64; for c in text.chars() { if c == '=' { padding += 1; continue; } let v = quintet(c); if v < 0 || padding > 0 { panic!("base32 text may only contain A-Z and 2-7, with = padding at the end"); } values.push(v as u32); } let rest = values.len() % 8; if PAD[rest] < 0 { panic!("base32 text has a length that no byte count produces"); } if padding > 0 && padding != PAD[rest] { panic!("base32 text has the wrong amount of = padding"); } let mut out = Vec::with_capacity(values.len() * 5 / 8); let mut buffer: u32 = 0; let mut bits = 0; for v in values { buffer = ((buffer << 5) | v) & 0x1fff; bits += 5; if bits >= 8 { out.push(((buffer >> (bits - 8)) & 255) as i64); bits -= 8; } } if buffer & ((1u32 << bits) - 1) != 0 { panic!("base32 text has non-zero bits after its last byte"); } out } pub fn fune_vector(args: &[Value]) -> Value { let text = match &args[0] { Value::Str(s) => s.as_str(), _ => panic!("base32 text must be a string"), }; Value::Arr(base32_decode(text).into_iter().map(Value::Int).collect()) }