forked from parcel-bundler/lightningcss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.rs
More file actions
63 lines (54 loc) · 1.7 KB
/
url.rs
File metadata and controls
63 lines (54 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use cssparser::*;
use crate::traits::{Parse, ToCss};
use crate::printer::Printer;
use crate::dependencies::{Dependency, UrlDependency};
use crate::error::{ParserError, PrinterError};
#[derive(Debug, Clone, PartialEq)]
pub struct Url {
pub url: String,
pub loc: SourceLocation
}
impl Parse for Url {
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
let loc = input.current_source_location();
let url = input.expect_url()?.as_ref().to_owned();
Ok(Url { url, loc })
}
}
impl ToCss for Url {
fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
let dep = if dest.dependencies.is_some() {
Some(UrlDependency::new(self, dest.filename))
} else {
None
};
let url = if let Some(dep) = &dep {
&dep.placeholder
} else {
&self.url
};
use cssparser::ToCss;
if dest.minify {
let mut buf = String::new();
Token::UnquotedUrl(CowRcStr::from(url.as_ref())).to_css(&mut buf)?;
// If the unquoted url is longer than it would be quoted (e.g. `url("...")`)
// then serialize as a string and choose the shorter version.
if buf.len() > url.len() + 7 {
let mut buf2 = String::new();
serialize_string(&url, &mut buf2)?;
if buf2.len() + 5 < buf.len() {
dest.write_str("url(")?;
dest.write_str(&buf2)?;
return dest.write_char(')')
}
}
dest.write_str(&buf)?;
} else {
Token::UnquotedUrl(CowRcStr::from(url.as_ref())).to_css(dest)?;
}
if let Some(dependencies) = &mut dest.dependencies {
dependencies.push(Dependency::Url(dep.unwrap()))
}
Ok(())
}
}