Skip to content

Commit

Permalink
improve css gradient parser
Browse files Browse the repository at this point in the history
  • Loading branch information
mazznoer committed Jul 22, 2024
1 parent aa7382e commit 3a6998a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/css_gradient.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{BlendMode, Color};

#[allow(clippy::question_mark)]
pub(crate) fn parse(s: &str, mode: BlendMode) -> Option<(Vec<Color>, Vec<f32>)> {
let mut stops = Vec::new();

Expand All @@ -13,7 +14,9 @@ pub(crate) fn parse(s: &str, mode: BlendMode) -> Option<(Vec<Color>, Vec<f32>)>
return None;
}

stops[0].0.as_ref()?;
if stops[0].0.is_none() {
return None;
}

for i in 0..stops.len() {
if i == 0 && stops[i].1.is_none() {
Expand All @@ -25,10 +28,13 @@ pub(crate) fn parse(s: &str, mode: BlendMode) -> Option<(Vec<Color>, Vec<f32>)>
if stops[i].1.is_none() {
stops[i].1 = Some(1.0);
}
continue;
break;
}

if stops[i].0.is_none() {
if stops[i + 1].0.is_none() {
return None;
}
let col1 = stops[i - 1].0.as_ref().unwrap();
let col2 = stops[i + 1].0.as_ref().unwrap();
let col = match mode {
Expand Down Expand Up @@ -66,6 +72,12 @@ pub(crate) fn parse(s: &str, mode: BlendMode) -> Option<(Vec<Color>, Vec<f32>)>
}
}

for (col, pos) in &stops {
if col.is_none() || pos.is_none() {
return None;
}
}

let colors = stops
.iter()
.map(|(c, _)| c.clone().unwrap())
Expand Down
13 changes: 13 additions & 0 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,19 @@ fn css_gradient() {
assert_eq!(g.at(pos).to_rgba8(), rgba8);
}
}

let invalid_css = [
"",
" ",
"0, red, lime",
"red, lime, 100%",
"deeppink, 0.4, 0.9, pink",
"0%, 100%",
];
for s in invalid_css {
let g = GradientBuilder::new().css(s).build::<LinearGradient>();
assert!(g.is_err());
}
}

#[test]
Expand Down

0 comments on commit 3a6998a

Please sign in to comment.