rspack_lightningcss/values/
url.rs1use crate::dependencies::{Dependency, Location, UrlDependency};
4use crate::error::{ParserError, PrinterError};
5use crate::traits::{Parse, ToCss};
6use crate::values::string::CowArcStr;
7#[cfg(feature = "visitor")]
8use crate::visitor::Visit;
9use cssparser::*;
10use std::fmt::{self, Write};
11
12#[derive(Debug, Clone)]
14#[cfg_attr(feature = "visitor", derive(Visit))]
15#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
16#[cfg_attr(feature = "visitor", visit(visit_url, URLS))]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
19pub struct Url<'i> {
20 #[cfg_attr(feature = "serde", serde(borrow))]
22 pub url: CowArcStr<'i>,
23 pub loc: Location,
25}
26
27impl<'i> PartialEq for Url<'i> {
28 fn eq(&self, other: &Self) -> bool {
29 self.url == other.url
30 }
31}
32
33impl<'i> Parse<'i> for Url<'i> {
34 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
35 let loc = input.current_source_location();
36 let url = input.expect_url()?.into();
37 Ok(Url { url, loc: loc.into() })
38 }
39}
40
41impl<'i> ToCss for Url<'i> {
42 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
43 let dep = if dest.has_dependencies() {
44 Some(UrlDependency::new(self, dest.filename()))
45 } else {
46 None
47 };
48
49 if let Some(dep) = dep {
52 dest.write_str("url(")?;
53 serialize_string(&dep.placeholder, dest)?;
54 dest.write_char(')')?;
55
56 dest.add_dependency(Dependency::Url(dep));
57
58 return Ok(());
59 }
60
61 use cssparser::ToCss;
62 if dest.options().minify {
63 let mut buf = String::new();
64 Token::UnquotedUrl(CowRcStr::from(self.url.as_ref())).to_css(&mut buf)?;
65
66 if buf.len() > self.url.len() + 7 {
69 let mut single_quotes = 0;
70 let mut double_quotes = 0;
71 for b in self.url.bytes() {
72 match b {
73 b'\'' => single_quotes += 1,
74 b'"' => double_quotes += 1,
75 _ => {}
76 }
77 }
78
79 let mut buf2 = String::new();
80 if double_quotes > single_quotes {
81 serialize_single_quoted_string(&self.url, &mut buf2)?;
82 } else {
83 serialize_string(&self.url, &mut buf2)?;
84 }
85 if buf2.len() + 5 < buf.len() {
86 dest.write_str("url(")?;
87 dest.write_str(&buf2)?;
88 dest.write_char(')')?;
89 return Ok(());
90 }
91 }
92
93 dest.write_str(&buf)?;
94 } else {
95 dest.write_str("url(")?;
96 serialize_string(&self.url, dest)?;
97 dest.write_char(')')?;
98 }
99
100 Ok(())
101 }
102}
103
104fn serialize_single_quoted_string<W: Write>(value: &str, dest: &mut W) -> fmt::Result {
105 dest.write_char('\'')?;
106 let mut start = 0;
107 for (i, b) in value.bytes().enumerate() {
108 if matches!(b, b'\'' | b'"') {
109 CssStringWriter::new(dest).write_str(&value[start..i])?;
111 if b == b'\'' {
112 dest.write_char('\\')?;
113 }
114 dest.write_char(b as char)?;
115 start = i + 1;
116 }
117 }
118 CssStringWriter::new(dest).write_str(&value[start..])?;
119 dest.write_char('\'')
120}
121
122impl<'i> Url<'i> {
123 pub fn is_absolute(&self) -> bool {
125 let url = self.url.as_ref();
126
127 if url.starts_with('.') {
129 return false;
130 }
131
132 if url.starts_with('/') {
134 return true;
135 }
136
137 if url.starts_with('#') {
141 return true;
142 }
143
144 if !url.starts_with(|c| matches!(c, 'a'..='z' | 'A'..='Z')) {
147 return false;
148 }
149
150 for b in url.as_bytes() {
152 let c = *b as char;
153 match c {
154 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.' => {}
155 ':' => return true,
156 _ => break,
157 }
158 }
159
160 false
161 }
162}