cssparser/from_bytes.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5/// Abstraction for avoiding a dependency from cssparser to an encoding library
6pub trait EncodingSupport {
7 /// One character encoding
8 type Encoding;
9
10 /// https://encoding.spec.whatwg.org/#concept-encoding-get
11 fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding>;
12
13 /// Return the UTF-8 encoding
14 fn utf8() -> Self::Encoding;
15
16 /// Whether the given encoding is UTF-16BE or UTF-16LE
17 fn is_utf16_be_or_le(encoding: &Self::Encoding) -> bool;
18}
19
20/// Determine the character encoding of a CSS stylesheet.
21///
22/// This is based on the presence of a BOM (Byte Order Mark), an `@charset` rule, and
23/// encoding meta-information.
24///
25/// * `css_bytes`: A byte string.
26/// * `protocol_encoding`: The encoding label, if any, defined by HTTP or equivalent protocol.
27/// (e.g. via the `charset` parameter of the `Content-Type` header.)
28/// * `environment_encoding`: An optional `Encoding` object for the [environment encoding]
29/// (https://drafts.csswg.org/css-syntax/#environment-encoding), if any.
30///
31/// Returns the encoding to use.
32pub fn stylesheet_encoding<E>(
33 css: &[u8],
34 protocol_encoding_label: Option<&[u8]>,
35 environment_encoding: Option<E::Encoding>,
36) -> E::Encoding
37where
38 E: EncodingSupport,
39{
40 // https://drafts.csswg.org/css-syntax/#the-input-byte-stream
41 if let Some(label) = protocol_encoding_label {
42 if let Some(protocol_encoding) = E::from_label(label) {
43 return protocol_encoding;
44 };
45 };
46
47 let prefix = b"@charset \"";
48 if css.starts_with(prefix) {
49 let rest = &css[prefix.len()..];
50 if let Some(label_length) = rest.iter().position(|&b| b == b'"') {
51 if rest[label_length..].starts_with(b"\";") {
52 let label = &rest[..label_length];
53 if let Some(charset_encoding) = E::from_label(label) {
54 if E::is_utf16_be_or_le(&charset_encoding) {
55 return E::utf8();
56 } else {
57 return charset_encoding;
58 }
59 }
60 }
61 }
62 }
63 environment_encoding.unwrap_or_else(E::utf8)
64}