Functional Weave
Code in Rust

encoding.base32@1.0.0

impl/rust/base32_encode.rs

1,629 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

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<i64> = 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))
}