swc_css_minifier/compressor/
unicode_range.rs

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
64
65
66
67
68
69
70
use swc_css_ast::*;

use super::Compressor;

impl Compressor {
    pub(super) fn compress_unicode_range(&self, unicode_range: &mut UnicodeRange) {
        unicode_range.start = unicode_range.start.to_ascii_lowercase();
        if let Some(end) = &mut unicode_range.end {
            *end = end.to_ascii_lowercase();
        }

        if unicode_range.end.is_none() {
            unicode_range.start = self.remove_leading_zeros(&unicode_range.start).into();

            return;
        }

        let start = &unicode_range.start;
        let end = unicode_range.end.as_ref().unwrap();
        let merged = self.merge_start_and_end(start, end);

        if let Some(merged) = &merged {
            unicode_range.start = self.remove_leading_zeros(merged).into();
            unicode_range.end = None;
        } else {
            unicode_range.start = self.remove_leading_zeros(start).into();
            unicode_range.end = Some(self.remove_leading_zeros(end).into());
        }
    }

    fn remove_leading_zeros(&self, value: &str) -> String {
        let mut result = String::with_capacity(value.len());
        let mut is_leading = true;

        for c in value.chars() {
            if c == '0' && is_leading {
                continue;
            }

            is_leading = false;

            result.push(c);
        }

        result
    }

    fn merge_start_and_end(&self, start: &str, end: &str) -> Option<String> {
        let mut minified = String::new();
        let mut question_counter = 0;

        for (idx, start_c) in start.chars().enumerate() {
            if let Some(end_c) = &end.chars().nth(idx) {
                if start_c == *end_c && question_counter == 0 {
                    minified.push(start_c);
                } else if start_c == '0' && *end_c == 'f' {
                    question_counter += 1;

                    minified.push('?')
                } else {
                    return None;
                }
            } else {
                return None;
            }
        }

        Some(minified)
    }
}