Skip to main content

rust_css_parser/ast/
strings.rs

1//! Port of `src/ast/strings.ts`.
2//!
3//! String table of an arena. An interned string is a range of a text:
4//!
5//! - a range of the code units of a source file: the values of the tokens read by the tokenizer. the table stores
6//!   the source index and the start and end offsets, no string is created. the code units buffer is shared with the
7//!   tokenizer (reference counted): it is not copied
8//! - a range of the canonical text: the spelling of the known units and function names
9//! - a range of the pool: the code units of the strings that are not a range of a source
10//! - a string: the strings interned by [`StringTable::intern`]
11//!
12//! Strings are created when they are read ([`StringTable::get`]), once per id, as shared `Rc<str>`.
13
14use crate::parser::utils::canonical::{canonical_code_at, with_canonical_text};
15use crate::parser::utils::codes::{hash_range, hash_string, CodeUnits};
16use std::any::Any;
17use crate::utils::fx::HashMap;
18use std::cell::RefCell;
19use std::rc::Rc;
20
21/// where the code units of an interned string are stored. a value that is not negative is the index of a source
22#[allow(non_snake_case)]
23pub mod StringSource {
24    /// the code units are copied to the pool
25    pub const Pool: i32 = -1;
26    /// range of the canonical text
27    pub const Canonical: i32 = -2;
28    /// a string
29    pub const Value: i32 = -3;
30}
31
32/// boolean properties of the strings computed once per string id. 4 flags at most
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[repr(u8)]
35pub enum StringFlag {
36    /// a named color, a system color or `currentcolor` / `transparent`, ignoring the case
37    Color = 0,
38    /// a rule selector that is not modified by the minifier
39    SimpleSelector = 1,
40    /// a rule selector that contains a vendor prefixed pseudo class
41    VendorPrefix = 2,
42}
43
44/// values derived from the strings computed once per string id
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46#[repr(u8)]
47pub enum StringDerived {
48    FunctionSyntax = 0,
49    SelectorFunctionSyntax = 1,
50    TransformKind = 2,
51    /// true if the rules are allowed in the block of an at-rule (by name, without `@`), see `parse_selector()`
52    AtRuleAcceptsRules = 3,
53}
54
55/// copy of a string table, see [`StringTable::export`]
56#[derive(Clone, Debug, Default)]
57pub struct StringTableData {
58    pub count: u32,
59    pub hashes: Vec<i32>,
60    pub sources: Vec<i32>,
61    pub starts: Vec<i32>,
62    pub ends: Vec<i32>,
63    /// code units of each source, by source index
64    pub texts: Vec<Option<CodeUnits>>,
65    pub pool: Vec<u16>,
66    /// the strings of the `StringSource::Value` entries, by id
67    pub values: Vec<Option<Rc<str>>>,
68}
69
70/// the code units of a string, borrowed (see [`StringTable::with_units`]): ascii bytes or utf-16 code units
71#[derive(Clone, Copy, Debug)]
72pub enum Units<'a> {
73    Bytes(&'a [u8]),
74    Utf16(&'a [u16]),
75}
76
77/// builds a string from code units, strings and interned strings, then interns it: no string is created
78#[derive(Default)]
79pub struct StringBuilder {
80    pub codes: Vec<u16>,
81}
82
83impl StringBuilder {
84    pub fn new() -> Self {
85        Self { codes: Vec::with_capacity(256) }
86    }
87
88    /// drop the code units
89    pub fn reset(&mut self) -> &mut Self {
90        self.codes.clear();
91        self
92    }
93
94    pub fn len(&self) -> usize {
95        self.codes.len()
96    }
97
98    pub fn is_empty(&self) -> bool {
99        self.codes.is_empty()
100    }
101
102    /// append the code units of an interned string
103    pub fn append_id(&mut self, table: &StringTable, id: u32) -> &mut Self {
104        table.copy_into(id, &mut self.codes);
105        self
106    }
107
108    /// append a string
109    pub fn append_string(&mut self, str: &str) -> &mut Self {
110        self.codes.extend(str.encode_utf16());
111        self
112    }
113
114    /// append a code unit
115    pub fn append_code(&mut self, code: u16) -> &mut Self {
116        self.codes.push(code);
117        self
118    }
119
120    /// intern the string
121    pub fn intern(&self, table: &mut StringTable) -> u32 {
122        table.intern_units(&self.codes)
123    }
124}
125
126thread_local! {
127    /// the buffers of [`with_decoded`]: a stack, a decoded string may be read while another one is decoded
128    static DECODED: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
129}
130
131/// run a function with utf-16 code units decoded into a reused buffer (`String::from_utf16_lossy()` without allocating)
132fn with_decoded<R>(units: &[u16], f: impl FnOnce(&str) -> R) -> R {
133    let mut buffer = DECODED.with(|d| d.borrow_mut().pop()).unwrap_or_default();
134    buffer.clear();
135    buffer.extend(char::decode_utf16(units.iter().copied()).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)));
136    let result = f(&buffer);
137    if buffer.capacity() <= 1 << 16 {
138        DECODED.with(|d| d.borrow_mut().push(buffer));
139    }
140    result
141}
142
143/// a string shared without a copy: a shared string, or a range of the bytes of an ascii source (the source buffer is
144/// shared). it derefs to `&str`, a clone increments a reference count
145#[derive(Clone)]
146pub struct SharedStr(SharedRepr);
147
148#[derive(Clone)]
149enum SharedRepr {
150    Shared(Rc<str>),
151    /// a static string (the configuration): no copy, no reference count
152    Static(&'static str),
153    /// a range of an ascii buffer: valid utf-8 at any boundary
154    Ascii { buffer: Rc<[u8]>, start: u32, end: u32 },
155}
156
157impl SharedStr {
158    /// a range of an ascii buffer, without a copy
159    pub fn ascii(buffer: &Rc<[u8]>, start: usize, end: usize) -> Self {
160        debug_assert!(buffer[start..end].is_ascii());
161        SharedStr(SharedRepr::Ascii { buffer: buffer.clone(), start: start as u32, end: end as u32 })
162    }
163
164    pub fn as_str(&self) -> &str {
165        self
166    }
167
168    /// a static string, without a copy
169    pub fn from_static(s: &'static str) -> Self {
170        SharedStr(SharedRepr::Static(s))
171    }
172}
173
174impl std::ops::Deref for SharedStr {
175    type Target = str;
176
177    #[inline]
178    fn deref(&self) -> &str {
179        match &self.0 {
180            SharedRepr::Shared(s) => s,
181            SharedRepr::Static(s) => s,
182            // SAFETY: the buffer is ascii (see `SharedStr::ascii()`)
183            SharedRepr::Ascii { buffer, start, end } => unsafe { std::str::from_utf8_unchecked(&buffer[*start as usize..*end as usize]) },
184        }
185    }
186}
187
188impl AsRef<str> for SharedStr {
189    fn as_ref(&self) -> &str {
190        self
191    }
192}
193
194impl std::borrow::Borrow<str> for SharedStr {
195    fn borrow(&self) -> &str {
196        self
197    }
198}
199
200impl Default for SharedStr {
201    fn default() -> Self {
202        SharedStr(SharedRepr::Shared(Rc::from("")))
203    }
204}
205
206impl From<Rc<str>> for SharedStr {
207    fn from(s: Rc<str>) -> Self {
208        SharedStr(SharedRepr::Shared(s))
209    }
210}
211
212impl From<&str> for SharedStr {
213    fn from(s: &str) -> Self {
214        SharedStr(SharedRepr::Shared(Rc::from(s)))
215    }
216}
217
218impl From<String> for SharedStr {
219    fn from(s: String) -> Self {
220        SharedStr(SharedRepr::Shared(Rc::from(s)))
221    }
222}
223
224impl From<SharedStr> for Rc<str> {
225    /// a shared string is returned as is, a range is copied
226    fn from(s: SharedStr) -> Self {
227        match s.0 {
228            SharedRepr::Shared(s) => s,
229            SharedRepr::Static(_) | SharedRepr::Ascii { .. } => Rc::from(&*s),
230        }
231    }
232}
233
234impl std::fmt::Display for SharedStr {
235    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        f.write_str(self)
237    }
238}
239
240impl std::fmt::Debug for SharedStr {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        std::fmt::Debug::fmt(&**self, f)
243    }
244}
245
246impl PartialEq for SharedStr {
247    fn eq(&self, other: &Self) -> bool {
248        **self == **other
249    }
250}
251
252impl Eq for SharedStr {}
253
254impl PartialEq<str> for SharedStr {
255    fn eq(&self, other: &str) -> bool {
256        &**self == other
257    }
258}
259
260impl PartialEq<&str> for SharedStr {
261    fn eq(&self, other: &&str) -> bool {
262        &**self == *other
263    }
264}
265
266impl std::hash::Hash for SharedStr {
267    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
268        (**self).hash(state)
269    }
270}
271
272impl PartialOrd for SharedStr {
273    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
274        Some(self.cmp(other))
275    }
276}
277
278impl Ord for SharedStr {
279    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
280        (**self).cmp(&**other)
281    }
282}
283
284/// interned strings of an arena
285pub struct StringTable {
286    /// number of strings
287    pub count: u32,
288    /// strings by id: the strings that have been read and the `StringSource::Value` strings
289    cache: Vec<Option<SharedStr>>,
290    /// utf-16 code units of the non ascii `StringSource::Value` strings
291    value_units: HashMap<u32, Rc<[u16]>>,
292    /// identity of the ids: changed when the ids change (see [`StringTable::compact`])
293    pub epoch: u64,
294    hashes: Vec<i32>,
295    sources: Vec<i32>,
296    starts: Vec<i32>,
297    ends: Vec<i32>,
298    /// hash table: string id + 1 by slot, 0 when the slot is empty (open addressing, linear probing)
299    slots: Vec<i32>,
300    /// code units of the sources, by source index
301    texts: Vec<Option<CodeUnits>>,
302    derived_values: Vec<Option<HashMap<u32, Box<dyn Any>>>>,
303    flags: Vec<u8>,
304    /// id of the lowercase string + 1, by id
305    lowers: Vec<i32>,
306    builder: StringBuilder,
307    /// code units of the strings that are not a range of a source
308    pool: Vec<u16>,
309}
310
311thread_local! {
312    static EPOCH: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
313}
314
315fn next_epoch() -> u64 {
316    EPOCH.with(|e| {
317        let v = e.get();
318        e.set(v + 1);
319        v
320    })
321}
322
323impl Default for StringTable {
324    fn default() -> Self {
325        Self::new()
326    }
327}
328
329impl StringTable {
330    /// approximate number of bytes held by the table: the capacity of its vectors and the code units of the sources.
331    /// reported to the javascript engine by the N-API addon, see [`crate::bindings::take_external_memory`]
332    pub fn memory_size(&self) -> usize {
333        use std::mem::size_of;
334
335        let ints = self.hashes.capacity() + self.sources.capacity() + self.starts.capacity() + self.ends.capacity() + self.slots.capacity() + self.lowers.capacity();
336        let texts: usize = self
337            .texts
338            .iter()
339            .flatten()
340            .map(|t| match t {
341                CodeUnits::Bytes(b) => b.len(),
342                CodeUnits::Utf16(u) => u.len() * 2,
343            })
344            .sum();
345
346        ints * size_of::<i32>()
347            + self.cache.capacity() * size_of::<Option<SharedStr>>()
348            + self.texts.capacity() * size_of::<Option<CodeUnits>>()
349            + self.derived_values.capacity() * size_of::<Option<HashMap<u32, Box<dyn Any>>>>()
350            + self.flags.capacity()
351            + self.pool.capacity() * size_of::<u16>()
352            + texts
353    }
354
355    pub fn new() -> Self {
356        Self {
357            count: 0,
358            cache: Vec::new(),
359            value_units: HashMap::default(),
360            epoch: next_epoch(),
361            hashes: vec![0; 256],
362            sources: vec![0; 256],
363            starts: vec![0; 256],
364            ends: vec![0; 256],
365            slots: vec![0; 512],
366            texts: Vec::new(),
367            derived_values: Vec::new(),
368            flags: Vec::new(),
369            lowers: Vec::new(),
370            builder: StringBuilder::new(),
371            pool: Vec::with_capacity(1024),
372        }
373    }
374
375    /// set the code units of a source: the strings of the source are ranges of it. the buffer is shared, not copied
376    pub fn set_text(&mut self, source: usize, codes: CodeUnits) {
377        if self.texts.len() <= source {
378            self.texts.resize(source + 1, None);
379        }
380        self.texts[source] = Some(codes);
381    }
382
383    /// kept for parity with typescript: the code units are the text, there is nothing to release
384    pub fn release_codes(&mut self, _source: usize) {}
385
386    /// code units of a source
387    pub fn text(&self, source: usize) -> Option<&CodeUnits> {
388        self.texts.get(source).and_then(|t| t.as_ref())
389    }
390
391    #[inline]
392    fn find<F: Fn(&Self, u32) -> bool>(&self, hash: i32, eq: F) -> Result<u32, usize> {
393        let mask = self.slots.len() - 1;
394        let mut slot = (hash as usize) & mask;
395        loop {
396            let entry = self.slots[slot];
397            if entry == 0 {
398                return Err(slot);
399            }
400            let id = (entry - 1) as u32;
401            if self.hashes[id as usize] == hash && eq(self, id) {
402                return Ok(id);
403            }
404            slot = (slot + 1) & mask;
405        }
406    }
407
408    /// intern a string
409    pub fn intern(&mut self, str: &str) -> u32 {
410        let hash = hash_string(str);
411        match self.find(hash, |t, id| t.equals_string(id, str)) {
412            Ok(id) => id,
413            Err(slot) => {
414                let len = if str.is_ascii() { str.len() } else { str.encode_utf16().count() };
415                let id = self.add(hash, slot, StringSource::Value, 0, len as i32);
416                if !str.is_ascii() {
417                    self.value_units.insert(id, str.encode_utf16().collect::<Vec<u16>>().into());
418                }
419                self.set_cache(id, Rc::from(str));
420                id
421            }
422        }
423    }
424
425    /// intern a shared string, without copying it
426    /// intern a shared string: a shared `Rc<str>` is kept as is, a range of a source is copied
427    pub fn intern_shared(&mut self, str: &SharedStr) -> u32 {
428        match &str.0 {
429            SharedRepr::Shared(rc) => self.intern_rc(rc),
430            SharedRepr::Static(_) | SharedRepr::Ascii { .. } => self.intern(str),
431        }
432    }
433
434    pub fn intern_rc(&mut self, str: &Rc<str>) -> u32 {
435        let hash = hash_string(str);
436        match self.find(hash, |t, id| t.equals_string(id, str)) {
437            Ok(id) => id,
438            Err(slot) => {
439                let len = if str.is_ascii() { str.len() } else { str.encode_utf16().count() };
440                let id = self.add(hash, slot, StringSource::Value, 0, len as i32);
441                if !str.is_ascii() {
442                    self.value_units.insert(id, str.encode_utf16().collect::<Vec<u16>>().into());
443                }
444                self.set_cache(id, str.clone());
445                id
446            }
447        }
448    }
449
450    /// intern utf-16 code units (copied to the pool when they are not interned yet)
451    pub fn intern_units(&mut self, codes: &[u16]) -> u32 {
452        let hash = hash_range(codes, 0, codes.len());
453        match self.find(hash, |t, id| t.equals_units(id, codes)) {
454            Ok(id) => id,
455            Err(slot) => {
456                let offset = self.pool.len() as i32;
457                self.pool.extend_from_slice(codes);
458                self.add(hash, slot, StringSource::Pool, offset, offset + codes.len() as i32)
459            }
460        }
461    }
462
463    /// intern a range of the code units of a source (`source >= 0`, the range is kept) or of the canonical text
464    /// (`StringSource::Canonical`, `codes` is the canonical text). use [`StringTable::intern_units`] for the pool
465    pub fn intern_range(&mut self, codes: &CodeUnits, start: usize, end: usize, source: i32) -> u32 {
466        let hash = codes.hash_range(start, end);
467        match self.find(hash, |t, id| t.equals_code_range(id, codes, start, end)) {
468            Ok(id) => id,
469            Err(slot) => {
470                if source == StringSource::Pool {
471                    let offset = self.pool.len() as i32;
472                    for i in start..end {
473                        self.pool.push(codes.at(i) as u16);
474                    }
475                    self.add(hash, slot, StringSource::Pool, offset, offset + (end - start) as i32)
476                } else {
477                    self.add(hash, slot, source, start as i32, end as i32)
478                }
479            }
480        }
481    }
482
483    /// intern a range of the canonical text
484    pub fn intern_canonical(&mut self, start: u32, end: u32) -> u32 {
485        let (hash, found) = with_canonical_text(|text| {
486            let bytes = &text.as_bytes()[start as usize..end as usize];
487            let hash = hash_range(bytes, 0, bytes.len());
488            (hash, self.find(hash, |t, id| t.equals_bytes(id, bytes)))
489        });
490        match found {
491            Ok(id) => id,
492            Err(slot) => self.add(hash, slot, StringSource::Canonical, start as i32, end as i32),
493        }
494    }
495
496    /// id of a string, -1 when the string is not interned
497    pub fn lookup(&self, str: &str) -> i32 {
498        match self.find(hash_string(str), |t, id| t.equals_string(id, str)) {
499            Ok(id) => id as i32,
500            Err(_) => -1,
501        }
502    }
503
504    fn set_cache(&mut self, id: u32, value: impl Into<SharedStr>) {
505        let value = value.into();
506        let id = id as usize;
507        if self.cache.len() <= id {
508            self.cache.resize(id + 1, None);
509        }
510        self.cache[id] = Some(value);
511    }
512
513    /// the string of an id. the string is created the first time it is read
514    pub fn get(&mut self, id: u32) -> SharedStr {
515        if let Some(Some(str)) = self.cache.get(id as usize) {
516            return str.clone();
517        }
518        if id >= self.count {
519            return SharedStr::default();
520        }
521        let i = id as usize;
522        let (start, end) = (self.starts[i] as usize, self.ends[i] as usize);
523        // an ascii range of a source shares the source buffer: no copy
524        let str: SharedStr = match (self.sources[i], self.texts.get(self.sources[i].max(0) as usize)) {
525            (source, Some(Some(CodeUnits::Bytes(bytes)))) if source >= 0 => SharedStr::ascii(bytes, start, end),
526            _ => SharedStr::from(self.peek(id)),
527        };
528        self.set_cache(id, str.clone());
529        str
530    }
531
532    /// the string of an id, without caching it
533    pub fn peek(&self, id: u32) -> String {
534        if let Some(Some(str)) = self.cache.get(id as usize) {
535            return str.to_string();
536        }
537        if id >= self.count {
538            return String::new();
539        }
540        let i = id as usize;
541        let (start, end) = (self.starts[i] as usize, self.ends[i] as usize);
542        match self.sources[i] {
543            StringSource::Pool => String::from_utf16_lossy(&self.pool[start..end]),
544            StringSource::Canonical => with_canonical_text(|t| t[start..end].to_owned()),
545            source => self.texts[source as usize].as_ref().map_or(String::new(), |c| c.slice(start, end).into_owned()),
546        }
547    }
548
549    /// run a function with the string of an id, without creating it when it is an ascii range of a source
550    pub fn with_str<R>(&self, id: u32, f: impl FnOnce(&str) -> R) -> R {
551        if let Some(Some(str)) = self.cache.get(id as usize) {
552            return f(str);
553        }
554        if id < self.count {
555            let i = id as usize;
556            let source = self.sources[i];
557            if source >= 0 {
558                if let Some(CodeUnits::Bytes(bytes)) = self.texts.get(source as usize).and_then(|t| t.as_ref()) {
559                    // ascii: valid utf-8
560                    return f(unsafe { std::str::from_utf8_unchecked(&bytes[self.starts[i] as usize..self.ends[i] as usize]) });
561                }
562            } else if source == StringSource::Canonical {
563                let (s, e) = (self.starts[i] as usize, self.ends[i] as usize);
564                return with_canonical_text(|t| f(&t[s..e]));
565            }
566            // utf-16 code units (a source that is not ascii, the pool): decoded into a reused buffer, no string is
567            // created
568            let (s, e) = (self.starts[i] as usize, self.ends[i] as usize);
569            if source == StringSource::Pool {
570                return with_decoded(&self.pool[s..e], f);
571            }
572            if source >= 0 {
573                if let Some(CodeUnits::Utf16(units)) = self.texts.get(source as usize).and_then(|t| t.as_ref()) {
574                    return with_decoded(&units[s..e], f);
575                }
576            }
577        }
578        f(&self.peek(id))
579    }
580
581    /// length of a string, in utf-16 code units
582    #[inline]
583    pub fn length(&self, id: u32) -> usize {
584        if id >= self.count {
585            return 0;
586        }
587        (self.ends[id as usize] - self.starts[id as usize]) as usize
588    }
589
590    /// utf-16 code unit of a string
591    pub fn code_at(&self, id: u32, index: usize) -> u32 {
592        let i = id as usize;
593        let source = self.sources[i];
594        let offset = self.starts[i] as usize + index;
595        if source >= 0 {
596            return self.texts[source as usize].as_ref().map_or(u32::MAX, |c| c.at(offset));
597        }
598        match source {
599            StringSource::Pool => self.pool.get(offset).map_or(u32::MAX, |&c| c as u32),
600            StringSource::Canonical => canonical_code_at(offset as u32),
601            _ => {
602                if let Some(units) = self.value_units.get(&id) {
603                    units.get(index).map_or(u32::MAX, |&c| c as u32)
604                } else {
605                    self.cache[i].as_ref().and_then(|s| s.as_bytes().get(index)).map_or(u32::MAX, |&b| b as u32)
606                }
607            }
608        }
609    }
610
611    /// the code units of a string, borrowed from where they are stored (the source text, the pool, the canonical text,
612    /// the value): no copy
613    pub fn with_units<R>(&self, id: u32, f: impl FnOnce(Units<'_>) -> R) -> R {
614        if id >= self.count {
615            return f(Units::Bytes(&[]));
616        }
617        let i = id as usize;
618        let (start, end) = (self.starts[i] as usize, self.ends[i] as usize);
619        match self.sources[i] {
620            StringSource::Pool => f(Units::Utf16(&self.pool[start..end])),
621            StringSource::Canonical => with_canonical_text(|t| f(Units::Bytes(&t.as_bytes()[start..end]))),
622            StringSource::Value => match self.value_units.get(&id) {
623                Some(units) => f(Units::Utf16(units)),
624                None => f(Units::Bytes(self.cache.get(i).and_then(|c| c.as_ref()).map_or(&[][..], |s| s.as_bytes()))),
625            },
626            source => match self.texts.get(source as usize).and_then(|t| t.as_ref()) {
627                Some(CodeUnits::Bytes(b)) => f(Units::Bytes(&b[start..end])),
628                Some(CodeUnits::Utf16(u)) => f(Units::Utf16(&u[start..end])),
629                None => f(Units::Bytes(&[])),
630            },
631        }
632    }
633
634    /// append the code units of a string to a buffer. the string is not created
635    pub fn copy_into(&self, id: u32, target: &mut Vec<u16>) -> usize {
636        let length = self.length(id);
637        target.reserve(length);
638        let i = id as usize;
639        let start = self.starts[i] as usize;
640        match self.sources[i] {
641            StringSource::Pool => target.extend_from_slice(&self.pool[start..start + length]),
642            StringSource::Canonical => with_canonical_text(|t| target.extend(t.as_bytes()[start..start + length].iter().map(|&b| b as u16))),
643            StringSource::Value => {
644                if let Some(units) = self.value_units.get(&id) {
645                    target.extend_from_slice(units);
646                } else if let Some(Some(s)) = self.cache.get(i) {
647                    target.extend(s.bytes().map(|b| b as u16));
648                }
649            }
650            source => match self.texts[source as usize].as_ref() {
651                Some(CodeUnits::Bytes(b)) => target.extend(b[start..start + length].iter().map(|&b| b as u16)),
652                Some(CodeUnits::Utf16(u)) => target.extend_from_slice(&u[start..start + length]),
653                None => {}
654            },
655        }
656        length
657    }
658
659    /// a boolean property of a string, computed once per id from the string
660    pub fn flag(&mut self, id: u32, flag: StringFlag, compute: impl FnOnce(&str) -> bool) -> bool {
661        if let Some(value) = self.cached_flag(id, flag) {
662            return value;
663        }
664        let value = self.with_str(id, compute);
665        self.set_flag(id, flag, value);
666        value
667    }
668
669    /// the string of an id when it has been created (`cache[id]`)
670    pub fn cached(&self, id: u32) -> Option<SharedStr> {
671        self.cache.get(id as usize).cloned().flatten()
672    }
673
674    /// cached value of a flag, if it is computed
675    pub fn cached_flag(&self, id: u32, flag: StringFlag) -> Option<bool> {
676        let value = (self.flags.get(id as usize).copied().unwrap_or(0) >> (flag as u8 * 2)) & 3;
677        if value == 0 {
678            None
679        } else {
680            Some(value == 3)
681        }
682    }
683
684    /// store the value of a flag
685    pub fn set_flag(&mut self, id: u32, flag: StringFlag, value: bool) {
686        if id as usize >= self.flags.len() {
687            let size = (self.count.max(id + 1) * 2) as usize;
688            self.flags.resize(size, 0);
689        }
690        self.flags[id as usize] |= (if value { 3 } else { 1 }) << (flag as u8 * 2);
691    }
692
693    /// a value derived from a string, if it is computed
694    pub fn derived<T: Clone + 'static>(&self, id: u32, slot: StringDerived) -> Option<T> {
695        self.derived_values
696            .get(slot as usize)
697            .and_then(|m| m.as_ref())
698            .and_then(|m| m.get(&id))
699            .and_then(|v| v.downcast_ref::<T>())
700            .cloned()
701    }
702
703    /// store a value derived from a string
704    pub fn set_derived<T: 'static>(&mut self, id: u32, slot: StringDerived, value: T) {
705        let slot = slot as usize;
706        if self.derived_values.len() <= slot {
707            self.derived_values.resize_with(slot + 1, || None);
708        }
709        self.derived_values[slot].get_or_insert_with(HashMap::default).insert(id, Box::new(value));
710    }
711
712    /// append the bytes of a string to a buffer when it is ascii. returns the number of bytes, -1 when the string is
713    /// not ascii (nothing is appended)
714    pub fn copy_ascii(&self, id: u32, target: &mut Vec<u8>) -> isize {
715        self.with_units(id, |units| match units {
716            // a byte slice is ascii (the non ascii texts are stored as utf-16 code units)
717            Units::Bytes(bytes) => {
718                target.extend_from_slice(bytes);
719                bytes.len() as isize
720            }
721            Units::Utf16(units) => {
722                if units.iter().any(|&u| u > 0x7f) {
723                    return -1;
724                }
725                target.extend(units.iter().map(|&u| u as u8));
726                units.len() as isize
727            }
728        })
729    }
730
731    /// index of the first occurrence of a code unit, -1 when it is not found
732    pub fn index_of_code(&self, id: u32, code: u32) -> isize {
733        self.with_units(id, |units| match units {
734            Units::Bytes(bytes) => {
735                if code > 0x7f {
736                    return -1;
737                }
738                bytes.iter().position(|&b| b as u32 == code).map_or(-1, |i| i as isize)
739            }
740            Units::Utf16(units) => units.iter().position(|&u| u as u32 == code).map_or(-1, |i| i as isize),
741        })
742    }
743
744    /// true if the string of an id equals a string. the string is not created
745    pub fn equals(&self, id: u32, str: &str) -> bool {
746        if id >= self.count {
747            return false;
748        }
749        self.equals_string(id, str)
750    }
751
752    /// id of the lowercase string: the id itself when the string has no uppercase letter
753    pub fn lower(&mut self, id: u32) -> u32 {
754        if let Some(&l) = self.lowers.get(id as usize) {
755            if l != 0 {
756                return (l - 1) as u32;
757            }
758        }
759        let length = self.length(id);
760        let mut result = id;
761        for i in 0..length {
762            let code = self.code_at(id, i);
763            if code > 0x7f {
764                let str = self.get(id);
765                let lower = str.to_lowercase();
766                result = if *lower == *str { id } else { self.intern(&lower) };
767                break;
768            }
769            if (0x41..=0x5a).contains(&code) {
770                let mut builder = std::mem::take(&mut self.builder);
771                builder.reset().append_id(self, id);
772                for c in builder.codes[i..].iter_mut() {
773                    if (0x41..=0x5a).contains(c) {
774                        *c += 32;
775                    }
776                }
777                result = builder.intern(self);
778                self.builder = builder;
779                break;
780            }
781        }
782        if id as usize >= self.lowers.len() {
783            self.lowers.resize((self.count.max(id + 1) * 2) as usize, 0);
784        }
785        self.lowers[id as usize] = result as i32 + 1;
786        result
787    }
788
789    /// true if the string of an id starts with a string
790    pub fn starts_with(&self, id: u32, str: &str) -> bool {
791        if id >= self.count || self.length(id) < str.len() {
792            return false;
793        }
794        self.with_units(id, |units| match units {
795            Units::Bytes(bytes) => bytes.starts_with(str.as_bytes()),
796            Units::Utf16(units) => str.encode_utf16().zip(units.iter()).all(|(c, &u)| c == u) && units.len() >= str.encode_utf16().count(),
797        })
798    }
799
800    /// true if the string of an id equals a string, ignoring the case of the ascii letters
801    pub fn equals_ignore_case(&self, id: u32, str: &str) -> bool {
802        if id >= self.count {
803            return false;
804        }
805        let lower = |c: u32| if (65..=90).contains(&c) { c + 32 } else { c };
806        self.with_units(id, |units| match units {
807            Units::Bytes(bytes) => bytes.eq_ignore_ascii_case(str.as_bytes()),
808            Units::Utf16(units) => units.len() == str.encode_utf16().count() && str.encode_utf16().zip(units.iter()).all(|(c, &u)| lower(c as u32) == lower(u as u32)),
809        })
810    }
811
812    /// drop the strings that are not used and renumber the others. returns the new id of each string
813    pub fn compact(&mut self, used: &[u8]) -> Vec<u32> {
814        let previous_count = self.count as usize;
815        let mut mapping = vec![0u32; previous_count];
816        let mut count = 0u32;
817        for id in 0..previous_count {
818            if used.get(id).copied().unwrap_or(0) != 0 {
819                mapping[id] = count;
820                count += 1;
821            }
822        }
823        let hashes = std::mem::take(&mut self.hashes);
824        let sources = std::mem::take(&mut self.sources);
825        let starts = std::mem::take(&mut self.starts);
826        let ends = std::mem::take(&mut self.ends);
827        let cache = std::mem::take(&mut self.cache);
828        let mut value_units = std::mem::take(&mut self.value_units);
829        let previous_pool = std::mem::take(&mut self.pool);
830        let mut pool = Vec::with_capacity(previous_pool.len().max(1024));
831        self.reset(count);
832        for id in 0..previous_count {
833            if used.get(id).copied().unwrap_or(0) == 0 {
834                continue;
835            }
836            let target = mapping[id] as usize;
837            let (mut start, mut end) = (starts[id], ends[id]);
838            if sources[id] == StringSource::Pool {
839                let offset = pool.len() as i32;
840                pool.extend_from_slice(&previous_pool[start as usize..end as usize]);
841                end = offset + end - start;
842                start = offset;
843            }
844            self.hashes[target] = hashes[id];
845            self.sources[target] = sources[id];
846            self.starts[target] = start;
847            self.ends[target] = end;
848            if let Some(Some(c)) = cache.get(id) {
849                self.set_cache(target as u32, c.clone());
850            }
851            if let Some(units) = value_units.remove(&(id as u32)) {
852                self.value_units.insert(target as u32, units);
853            }
854        }
855        self.pool = pool;
856        self.rehash();
857        mapping
858    }
859
860    /// copy of the table
861    pub fn export(&self) -> StringTableData {
862        let count = self.count as usize;
863        StringTableData {
864            count: self.count,
865            hashes: self.hashes[..count].to_vec(),
866            sources: self.sources[..count].to_vec(),
867            starts: self.starts[..count].to_vec(),
868            ends: self.ends[..count].to_vec(),
869            texts: self.texts.clone(),
870            pool: self.pool.clone(),
871            values: (0..count)
872                .map(|id| if self.sources[id] == StringSource::Value { self.cache.get(id).cloned().flatten().map(Rc::from) } else { None })
873                .collect(),
874        }
875    }
876
877    /// initialize the table from an exported copy
878    pub fn import(&mut self, data: &StringTableData) {
879        let count = data.count as usize;
880        self.reset(data.count);
881        self.hashes[..count].copy_from_slice(&data.hashes[..count]);
882        self.sources[..count].copy_from_slice(&data.sources[..count]);
883        self.starts[..count].copy_from_slice(&data.starts[..count]);
884        self.ends[..count].copy_from_slice(&data.ends[..count]);
885        self.texts = data.texts.clone();
886        self.pool = data.pool.clone();
887        for id in 0..count {
888            if data.sources[id] == StringSource::Value {
889                if let Some(Some(v)) = data.values.get(id) {
890                    if !v.is_ascii() {
891                        self.value_units.insert(id as u32, v.encode_utf16().collect::<Vec<u16>>().into());
892                    }
893                    self.set_cache(id as u32, v.clone());
894                }
895            }
896        }
897        self.rehash();
898    }
899
900    fn add(&mut self, hash: i32, slot: usize, source: i32, start: i32, end: i32) -> u32 {
901        let id = self.count as usize;
902        self.count += 1;
903        if id == self.hashes.len() {
904            self.grow(id * 2);
905        }
906        self.hashes[id] = hash;
907        self.sources[id] = source;
908        self.starts[id] = start;
909        self.ends[id] = end;
910        self.slots[slot] = id as i32 + 1;
911        if self.count as usize * 2 > self.slots.len() {
912            self.rehash();
913        }
914        id as u32
915    }
916
917    fn equals_units(&self, id: u32, codes: &[u16]) -> bool {
918        self.length(id) == codes.len() && codes.iter().enumerate().all(|(i, &c)| self.code_at(id, i) == c as u32)
919    }
920
921    fn equals_bytes(&self, id: u32, codes: &[u8]) -> bool {
922        self.length(id) == codes.len() && codes.iter().enumerate().all(|(i, &c)| self.code_at(id, i) == c as u32)
923    }
924
925    fn equals_code_range(&self, id: u32, codes: &CodeUnits, start: usize, end: usize) -> bool {
926        let length = end - start;
927        if self.length(id) != length {
928            return false;
929        }
930        let i = id as usize;
931        // same buffer, same range
932        let source = self.sources[i];
933        if source >= 0 && self.starts[i] as usize == start {
934            if let Some(text) = self.texts[source as usize].as_ref() {
935                let same = match (text, codes) {
936                    (CodeUnits::Bytes(a), CodeUnits::Bytes(b)) => Rc::ptr_eq(a, b),
937                    (CodeUnits::Utf16(a), CodeUnits::Utf16(b)) => Rc::ptr_eq(a, b),
938                    _ => false,
939                };
940                if same {
941                    return true;
942                }
943            }
944        }
945        // the units of the string are borrowed once and compared as slices (a memcmp when the widths match)
946        self.with_units(id, |units| match (units, codes) {
947            (Units::Bytes(a), CodeUnits::Bytes(b)) => a == &b[start..end],
948            (Units::Utf16(a), CodeUnits::Utf16(b)) => a == &b[start..end],
949            (Units::Bytes(a), CodeUnits::Utf16(b)) => a.iter().zip(&b[start..end]).all(|(&x, &y)| x as u16 == y),
950            (Units::Utf16(a), CodeUnits::Bytes(b)) => a.iter().zip(&b[start..end]).all(|(&x, &y)| x == y as u16),
951        })
952    }
953
954    fn equals_string(&self, id: u32, str: &str) -> bool {
955        let i = id as usize;
956        if let Some(Some(cached)) = self.cache.get(i) {
957            return **cached == *str;
958        }
959        if self.sources[i] == StringSource::Value {
960            return false;
961        }
962        self.with_units(id, |units| match units {
963            Units::Bytes(bytes) => bytes == str.as_bytes(),
964            Units::Utf16(units) => units.len() == str.encode_utf16().count() && str.encode_utf16().zip(units.iter()).all(|(c, &u)| c == u),
965        })
966    }
967
968    fn grow(&mut self, size: usize) {
969        self.hashes.resize(size, 0);
970        self.sources.resize(size, 0);
971        self.starts.resize(size, 0);
972        self.ends.resize(size, 0);
973    }
974
975    /// drop the strings, allocate the columns for `count` strings. the ids change
976    fn reset(&mut self, count: u32) {
977        let size = (count as usize).max(256);
978        self.count = count;
979        self.cache = Vec::new();
980        self.value_units = HashMap::default();
981        self.epoch = next_epoch();
982        self.lowers = Vec::new();
983        self.flags = Vec::new();
984        self.derived_values = Vec::new();
985        self.hashes = vec![0; size];
986        self.sources = vec![0; size];
987        self.starts = vec![0; size];
988        self.ends = vec![0; size];
989    }
990
991    fn rehash(&mut self) {
992        let mut size = 512;
993        while size < self.count as usize * 4 {
994            size *= 2;
995        }
996        let mut slots = vec![0i32; size];
997        let mask = size - 1;
998        for id in 0..self.count as usize {
999            let mut slot = (self.hashes[id] as usize) & mask;
1000            while slots[slot] != 0 {
1001                slot = (slot + 1) & mask;
1002            }
1003            slots[slot] = id as i32 + 1;
1004        }
1005        self.slots = slots;
1006    }
1007}