Functional Weave
Code in Rust

collections.chunk@1.0.0

impl/rust.rs

1,096 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

/// Split `items` into consecutive batches of at most `size`, in order.
///
/// An empty list gives no batches rather than one empty batch, so a loop over
/// the result never sends an empty request.
///
/// # Panics
/// Panics if `size` is less than 1: it is always a bug upstream, and "no
/// limit" is the outage batching prevents.
pub fn chunk<T: Clone>(items: &[T], size: i64) -> Vec<Vec<T>> {
    if size < 1 {
        panic!("size must be at least 1, received {}", size);
    }
    items.chunks(size as usize).map(|batch| batch.to_vec()).collect()
}

pub fn fune_vector(args: &[Value]) -> Value {
    // Refuse what the typed signature cannot hold, with the wording TypeScript
    // and Python use, rather than let the conversion below quietly change it.
    if let Value::Float(f) = args[1] {
        if f.fract() != 0.0 {
            panic!("size must be a whole number, received {}", f);
        }
    }
    Value::Arr(
        chunk(args[0].as_arr(), args[1].as_i64())
            .into_iter()
            .map(Value::Arr)
            .collect(),
    )
}