Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add exact argument to array.zip #4030

Merged
merged 6 commits into from
May 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 31 additions & 6 deletions crates/typst/src/foundations/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use comemo::Tracked;
use ecow::{eco_format, EcoString, EcoVec};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use typst_syntax::Spanned;
T0mstone marked this conversation as resolved.
Show resolved Hide resolved

use crate::diag::{bail, At, SourceResult, StrResult};
use crate::engine::Engine;
Expand Down Expand Up @@ -485,11 +486,17 @@ impl Array {
/// The real arguments (the other arguments are just for the docs, this
/// function is a bit involved, so we parse the arguments manually).
args: &mut Args,
#[external]
T0mstone marked this conversation as resolved.
Show resolved Hide resolved
#[named]
#[default(false)]
exact: bool,
/// The arrays to zip with.
#[external]
#[variadic]
others: Vec<Array>,
) -> SourceResult<Array> {
let exact: bool = args.named("exact")?.unwrap_or_default();

let remaining = args.remaining();

// Fast path for one array.
Expand All @@ -499,7 +506,16 @@ impl Array {

// Fast path for just two arrays.
if remaining == 1 {
let other = args.expect::<Array>("others")?;
let Spanned { v: other, span: other_span } =
args.expect::<Spanned<Array>>("others")?;
if exact && self.len() != other.len() {
bail!(
other_span,
"Second argument has different length ({}) from first argument ({})",
T0mstone marked this conversation as resolved.
Show resolved Hide resolved
other.len(),
self.len()
);
}
return Ok(self
.into_iter()
.zip(other)
Expand All @@ -509,11 +525,20 @@ impl Array {

// If there is more than one array, we use the manual method.
let mut out = Self::with_capacity(self.len());
let mut iterators = args
.all::<Array>()?
.into_iter()
.map(|i| i.into_iter())
.collect::<Vec<_>>();
let arrays = args.all::<Spanned<Array>>()?;
if let Some(Spanned { v, span }) =
arrays.iter().find(|sp| sp.v.len() != self.len())
{
bail!(
*span,
"Argument has different length ({}) from first argument ({})",
T0mstone marked this conversation as resolved.
Show resolved Hide resolved
v.len(),
self.len()
);
}

let mut iterators =
arrays.into_iter().map(|i| i.v.into_iter()).collect::<Vec<_>>();

for this in self {
let mut row = Self::with_capacity(1 + iterators.len());
Expand Down