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.state().dependencies.is_some() {
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 if let Some(dependencies) = dest.state_mut().dependencies.as_mut() {
57 dependencies.push(Dependency::Url(dep))
58 }
59
60 return Ok(());
61 }
62
63 use cssparser::ToCss;
64 if dest.options().minify {
65 let mut buf = String::new();
66 Token::UnquotedUrl(CowRcStr::from(self.url.as_ref())).to_css(&mut buf)?;
67
68 if buf.len() > self.url.len() + 7 {
71 let mut single_quotes = 0;
72 let mut double_quotes = 0;
73 for b in self.url.bytes() {
74 match b {
75 b'\'' => single_quotes += 1,
76 b'"' => double_quotes += 1,
77 _ => {}
78 }
79 }
80
81 let mut buf2 = String::new();
82 if double_quotes > single_quotes {
83 serialize_single_quoted_string(&self.url, &mut buf2)?;
84 } else {
85 serialize_string(&self.url, &mut buf2)?;
86 }
87 if buf2.len() + 5 < buf.len() {
88 dest.write_str("url(")?;
89 dest.write_str(&buf2)?;
90 dest.write_char(')')?;
91 return Ok(());
92 }
93 }
94
95 dest.write_str(&buf)?;
96 } else {
97 dest.write_str("url(")?;
98 serialize_string(&self.url, dest)?;
99 dest.write_char(')')?;
100 }
101
102 Ok(())
103 }
104}
105
106fn serialize_single_quoted_string<W: Write>(value: &str, dest: &mut W) -> fmt::Result {
107 dest.write_char('\'')?;
108 let mut start = 0;
109 for (i, b) in value.bytes().enumerate() {
110 if matches!(b, b'\'' | b'"') {
111 CssStringWriter::new(dest).write_str(&value[start..i])?;
113 if b == b'\'' {
114 dest.write_char('\\')?;
115 }
116 dest.write_char(b as char)?;
117 start = i + 1;
118 }
119 }
120 CssStringWriter::new(dest).write_str(&value[start..])?;
121 dest.write_char('\'')
122}
123
124impl<'i> Url<'i> {
125 pub fn is_absolute(&self) -> bool {
127 let url = self.url.as_ref();
128
129 if url.starts_with('.') {
131 return false;
132 }
133
134 if url.starts_with('/') {
136 return true;
137 }
138
139 if url.starts_with('#') {
143 return true;
144 }
145
146 if !url.starts_with(|c| matches!(c, 'a'..='z' | 'A'..='Z')) {
149 return false;
150 }
151
152 for b in url.as_bytes() {
154 let c = *b as char;
155 match c {
156 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.' => {}
157 ':' => return true,
158 _ => break,
159 }
160 }
161
162 false
163 }
164}