Skip to content

Commit 72c302c

Browse files
committed
Serialize url as string if shorter
1 parent 096329e commit 72c302c

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,8 @@ mod tests {
10471047

10481048
minify_test(".foo { background: url('img-sprite.png') no-repeat bottom right }", ".foo{background:url(img-sprite.png) 100% 100% no-repeat}");
10491049
minify_test(".foo { background: transparent }", ".foo{background:#0000}");
1050+
1051+
minify_test(".foo { background: url(\"data:image/svg+xml,%3Csvg width='168' height='24' xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E\") }", ".foo{background:url(\"data:image/svg+xml,%3Csvg width='168' height='24' xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E\")}");
10501052
}
10511053

10521054
#[test]

src/values/image.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,26 @@ impl ToCss for Image {
8484
match self {
8585
None => dest.write_str("none"),
8686
Url(url) => {
87-
Token::UnquotedUrl(CowRcStr::from(url.as_ref())).to_css(dest)
87+
if dest.minify {
88+
let mut buf = String::new();
89+
Token::UnquotedUrl(CowRcStr::from(url.as_ref())).to_css(&mut buf)?;
90+
91+
// If the unquoted url is longer than it would be quoted (e.g. `url("...")`)
92+
// then serialize as a string and choose the shorter version.
93+
if buf.len() > url.len() + 7 {
94+
let mut buf2 = String::new();
95+
serialize_string(url, &mut buf2)?;
96+
if buf2.len() + 5 < buf.len() {
97+
dest.write_str("url(")?;
98+
dest.write_str(&buf2)?;
99+
return dest.write_char(')')
100+
}
101+
}
102+
103+
dest.write_str(&buf)
104+
} else {
105+
Token::UnquotedUrl(CowRcStr::from(url.as_ref())).to_css(dest)
106+
}
88107
}
89108
Gradient(grad) => grad.to_css(dest),
90109
ImageSet(image_set) => image_set.to_css(dest)

0 commit comments

Comments
 (0)