Functional Weave
Code in Rust

form.file-check@1.0.0

impl/rust/format_file_size.rs

1,462 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 UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];

/// A size for people: "512 bytes", "1.5MB". Units of 1024, one decimal place
/// rounded half up only when the size is not a whole number of the unit; a
/// size that rounds up to 1024 of a unit is one of the next.
///
/// # Panics
/// Panics on a negative size.
pub fn format_file_size(bytes: i64) -> String {
    if bytes < 0 {
        panic!("size must be 0 or more, got {}", bytes);
    }
    if bytes == 1 {
        return "1 byte".to_string();
    }
    if bytes < 1024 {
        return format!("{} bytes", bytes);
    }
    let b = bytes as i128;
    let mut power: u32 = 1;
    while (power as usize) < UNITS.len() && b >= 1024i128.pow(power + 1) {
        power += 1;
    }
    let mut unit = 1024i128.pow(power);
    let mut tenths = (b * 10 + unit / 2) / unit;
    if tenths >= 10240 && (power as usize) < UNITS.len() {
        power += 1;
        unit = 1024i128.pow(power);
        tenths = (b * 10 + unit / 2) / unit;
    }
    let (whole, fraction) = (tenths / 10, tenths % 10);
    if fraction == 0 {
        format!("{}{}", whole, UNITS[power as usize - 1])
    } else {
        format!("{}.{}{}", whole, fraction, UNITS[power as usize - 1])
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    if let Value::Float(f) = args[0] {
        panic!("size must be a whole number of bytes, got {}", f);
    }
    Value::str(&format_file_size(args[0].as_i64()))
}