From 0e567ad697d9a44885fb9f575b2b2fb491560a29 Mon Sep 17 00:00:00 2001 From: +merlan #flirora Date: Tue, 24 Jun 2025 17:16:50 -0400 Subject: [PATCH] Simplify gradient sampling logic --- .../typst-library/src/visualize/gradient.rs | 34 ++++++------------ ...2-coincident-gradient-stops-export-png.png | Bin 522 -> 520 bytes 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/crates/typst-library/src/visualize/gradient.rs b/crates/typst-library/src/visualize/gradient.rs index e19b410bc..20539197c 100644 --- a/crates/typst-library/src/visualize/gradient.rs +++ b/crates/typst-library/src/visualize/gradient.rs @@ -1284,34 +1284,20 @@ fn process_stops(stops: &[Spanned]) -> SourceResult Color { + assert!(!stops.is_empty(), "Cannot sample from gradient with no stops"); + let t = t.clamp(0.0, 1.0); - let mut low = 0; - let mut high = stops.len(); + let j = stops.partition_point(|(_, ratio)| ratio.get() < t); - while low < high { - let mid = (low + high) / 2; - if stops[mid].1.get() < t { - low = mid + 1; - } else { - high = mid; - } + if j == 0 { + return stops[0].0; + } + if j == stops.len() { + return stops.last().unwrap().0; } - if low == 0 { - low = 1; - } - if t == 1.0 { - while stops[low - 1].1 >= stops[low].1 { - low -= 1; - } - } else { - while stops[low - 1].1 >= stops[low].1 { - low += 1; - } - } - - let (col_0, pos_0) = stops[low - 1]; - let (col_1, pos_1) = stops[low]; + let (col_0, pos_0) = stops[j - 1]; + let (col_1, pos_1) = stops[j]; debug_assert!(pos_0 < pos_1); debug_assert!(pos_0.get() <= t); debug_assert!(t <= pos_1.get()); diff --git a/tests/ref/issue-6162-coincident-gradient-stops-export-png.png b/tests/ref/issue-6162-coincident-gradient-stops-export-png.png index d269342c7c6678e525f62b7d85b080e2fcfd812d..886ea195d7803623f0422d1c66e6edd2a1797c34 100644 GIT binary patch delta 494 zcmVSq{bql(A z2Dp6zwt)b(gnt0DhybyR0I!Y!u95((l>n-k0H~V)rk((#p#Y<#0HLP^i_; zFc=I5gTY`h7@QckcO|LTXYWrZ7z_r3!C){L3>0HLPn}i0I!Y! zv5Nq+hyb;O0k(k#xP1${c@VsH6uog5zik`AXdc33A;e!J#(!ES$5biFPAkesF3dnb z%0NuWKv%{;VZ=Xa!as4pKX|=9e!D(|xju@wK996Ml(IdUusxowJ)^5Vr>H%vraZ5t zJhP!Zx1Kz^oIAdmJHnSc#gseAkvq(eI?szb(ug|Mg*w=RIop3Z-h4UXcsb;CIp%RV z>1{adX*lj>IDheBH}hRL_EE-|M?f>}p9%R2| z0001TNklJQ3`N1P4+~`rreYo>_Q8}iDQQUO$oDFDSARE2TCVLo_xN8w z!C){L3zk