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    pub fn new() -> Self {
331        Self {
332            count: 0,
333            cache: Vec::new(),
334            value_units: HashMap::default(),
335            epoch: next_epoch(),
336            hashes: vec![0; 256],
337            sources: vec![0; 256],
338            starts: vec![0; 256],
339            ends: vec![0; 256],
340            slots: vec![0; 512],
341            texts: Vec::new(),
342            derived_values: Vec::new(),
343            flags: Vec::new(),
344            lowers: Vec::new(),
345            builder: StringBuilder::new(),
346            pool: Vec::with_capacity(1024),
347        }
348    }
349
350    /// set the code units of a source: the strings of the source are ranges of it. the buffer is shared, not copied
351    pub fn set_text(&mut self, source: usize, codes: CodeUnits) {
352        if self.texts.len() <= source {
353            self.texts.resize(source + 1, None);
354        }
355        self.texts[source] = Some(codes);
356    }
357
358    /// kept for parity with typescript: the code units are the text, there is nothing to release
359    pub fn release_codes(&mut self, _source: usize) {}
360
361    /// code units of a source
362    pub fn text(&self, source: usize) -> Option<&CodeUnits> {
363        self.texts.get(source).and_then(|t| t.as_ref())
364    }
365
366    #[inline]
367    fn find<F: Fn(&Self, u32) -> bool>(&self, hash: i32, eq: F) -> Result<u32, usize> {
368        let mask = self.slots.len() - 1;
369        let mut slot = (hash as usize) & mask;
370        loop {
371            let entry = self.slots[slot];
372            if entry == 0 {
373                return Err(slot);
374            }
375            let id = (entry - 1) as u32;
376            if self.hashes[id as usize] == hash && eq(self, id) {
377                return Ok(id);
378            }
379            slot = (slot + 1) & mask;
380        }
381    }
382
383    /// intern a string
384    pub fn intern(&mut self, str: &str) -> u32 {
385        let hash = hash_string(str);
386        match self.find(hash, |t, id| t.equals_string(id, str)) {
387            Ok(id) => id,
388            Err(slot) => {
389                let len = if str.is_ascii() { str.len() } else { str.encode_utf16().count() };
390                let id = self.add(hash, slot, StringSource::Value, 0, len as i32);
391                if !str.is_ascii() {
392                    self.value_units.insert(id, str.encode_utf16().collect::<Vec<u16>>().into());
393                }
394                self.set_cache(id, Rc::from(str));
395                id
396            }
397        }
398    }
399
400    /// intern a shared string, without copying it
401    /// intern a shared string: a shared `Rc<str>` is kept as is, a range of a source is copied
402    pub fn intern_shared(&mut self, str: &SharedStr) -> u32 {
403        match &str.0 {
404            SharedRepr::Shared(rc) => self.intern_rc(rc),
405            SharedRepr::Static(_) | SharedRepr::Ascii { .. } => self.intern(str),
406        }
407    }
408
409    pub fn intern_rc(&mut self, str: &Rc<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, str.clone());
420                id
421            }
422        }
423    }
424
425    /// intern utf-16 code units (copied to the pool when they are not interned yet)
426    pub fn intern_units(&mut self, codes: &[u16]) -> u32 {
427        let hash = hash_range(codes, 0, codes.len());
428        match self.find(hash, |t, id| t.equals_units(id, codes)) {
429            Ok(id) => id,
430            Err(slot) => {
431                let offset = self.pool.len() as i32;
432                self.pool.extend_from_slice(codes);
433                self.add(hash, slot, StringSource::Pool, offset, offset + codes.len() as i32)
434            }
435        }
436    }
437
438    /// intern a range of the code units of a source (`source >= 0`, the range is kept) or of the canonical text
439    /// (`StringSource::Canonical`, `codes` is the canonical text). use [`StringTable::intern_units`] for the pool
440    pub fn intern_range(&mut self, codes: &CodeUnits, start: usize, end: usize, source: i32) -> u32 {
441        let hash = codes.hash_range(start, end);
442        match self.find(hash, |t, id| t.equals_code_range(id, codes, start, end)) {
443            Ok(id) => id,
444            Err(slot) => {
445                if source == StringSource::Pool {
446                    let offset = self.pool.len() as i32;
447                    for i in start..end {
448                        self.pool.push(codes.at(i) as u16);
449                    }
450                    self.add(hash, slot, StringSource::Pool, offset, offset + (end - start) as i32)
451                } else {
452                    self.add(hash, slot, source, start as i32, end as i32)
453                }
454            }
455        }
456    }
457
458    /// intern a range of the canonical text
459    pub fn intern_canonical(&mut self, start: u32, end: u32) -> u32 {
460        let (hash, found) = with_canonical_text(|text| {
461            let bytes = &text.as_bytes()[start as usize..end as usize];
462            let hash = hash_range(bytes, 0, bytes.len());
463            (hash, self.find(hash, |t, id| t.equals_bytes(id, bytes)))
464        });
465        match found {
466            Ok(id) => id,
467            Err(slot) => self.add(hash, slot, StringSource::Canonical, start as i32, end as i32),
468        }
469    }
470
471    /// id of a string, -1 when the string is not interned
472    pub fn lookup(&self, str: &str) -> i32 {
473        match self.find(hash_string(str), |t, id| t.equals_string(id, str)) {
474            Ok(id) => id as i32,
475            Err(_) => -1,
476        }
477    }
478
479    fn set_cache(&mut self, id: u32, value: impl Into<SharedStr>) {
480        let value = value.into();
481        let id = id as usize;
482        if self.cache.len() <= id {
483            self.cache.resize(id + 1, None);
484        }
485        self.cache[id] = Some(value);
486    }
487
488    /// the string of an id. the string is created the first time it is read
489    pub fn get(&mut self, id: u32) -> SharedStr {
490        if let Some(Some(str)) = self.cache.get(id as usize) {
491            return str.clone();
492        }
493        if id >= self.count {
494            return SharedStr::default();
495        }
496        let i = id as usize;
497        let (start, end) = (self.starts[i] as usize, self.ends[i] as usize);
498        // an ascii range of a source shares the source buffer: no copy
499        let str: SharedStr = match (self.sources[i], self.texts.get(self.sources[i].max(0) as usize)) {
500            (source, Some(Some(CodeUnits::Bytes(bytes)))) if source >= 0 => SharedStr::ascii(bytes, start, end),
501            _ => SharedStr::from(self.peek(id)),
502        };
503        self.set_cache(id, str.clone());
504        str
505    }
506
507    /// the string of an id, without caching it
508    pub fn peek(&self, id: u32) -> String {
509        if let Some(Some(str)) = self.cache.get(id as usize) {
510            return str.to_string();
511        }
512        if id >= self.count {
513            return String::new();
514        }
515        let i = id as usize;
516        let (start, end) = (self.starts[i] as usize, self.ends[i] as usize);
517        match self.sources[i] {
518            StringSource::Pool => String::from_utf16_lossy(&self.pool[start..end]),
519            StringSource::Canonical => with_canonical_text(|t| t[start..end].to_owned()),
520            source => self.texts[source as usize].as_ref().map_or(String::new(), |c| c.slice(start, end).into_owned()),
521        }
522    }
523
524    /// run a function with the string of an id, without creating it when it is an ascii range of a source
525    pub fn with_str<R>(&self, id: u32, f: impl FnOnce(&str) -> R) -> R {
526        if let Some(Some(str)) = self.cache.get(id as usize) {
527            return f(str);
528        }
529        if id < self.count {
530            let i = id as usize;
531            let source = self.sources[i];
532            if source >= 0 {
533                if let Some(CodeUnits::Bytes(bytes)) = self.texts.get(source as usize).and_then(|t| t.as_ref()) {
534                    // ascii: valid utf-8
535                    return f(unsafe { std::str::from_utf8_unchecked(&bytes[self.starts[i] as usize..self.ends[i] as usize]) });
536                }
537            } else if source == StringSource::Canonical {
538                let (s, e) = (self.starts[i] as usize, self.ends[i] as usize);
539                return with_canonical_text(|t| f(&t[s..e]));
540            }
541            // utf-16 code units (a source that is not ascii, the pool): decoded into a reused buffer, no string is
542            // created
543            let (s, e) = (self.starts[i] as usize, self.ends[i] as usize);
544            if source == StringSource::Pool {
545                return with_decoded(&self.pool[s..e], f);
546            }
547            if source >= 0 {
548                if let Some(CodeUnits::Utf16(units)) = self.texts.get(source as usize).and_then(|t| t.as_ref()) {
549                    return with_decoded(&units[s..e], f);
550                }
551            }
552        }
553        f(&self.peek(id))
554    }
555
556    /// length of a string, in utf-16 code units
557    #[inline]
558    pub fn length(&self, id: u32) -> usize {
559        if id >= self.count {
560            return 0;
561        }
562        (self.ends[id as usize] - self.starts[id as usize]) as usize
563    }
564
565    /// utf-16 code unit of a string
566    pub fn code_at(&self, id: u32, index: usize) -> u32 {
567        let i = id as usize;
568        let source = self.sources[i];
569        let offset = self.starts[i] as usize + index;
570        if source >= 0 {
571            return self.texts[source as usize].as_ref().map_or(u32::MAX, |c| c.at(offset));
572        }
573        match source {
574            StringSource::Pool => self.pool.get(offset).map_or(u32::MAX, |&c| c as u32),
575            StringSource::Canonical => canonical_code_at(offset as u32),
576            _ => {
577                if let Some(units) = self.value_units.get(&id) {
578                    units.get(index).map_or(u32::MAX, |&c| c as u32)
579                } else {
580                    self.cache[i].as_ref().and_then(|s| s.as_bytes().get(index)).map_or(u32::MAX, |&b| b as u32)
581                }
582            }
583        }
584    }
585
586    /// the code units of a string, borrowed from where they are stored (the source text, the pool, the canonical text,
587    /// the value): no copy
588    pub fn with_units<R>(&self, id: u32, f: impl FnOnce(Units<'_>) -> R) -> R {
589        if id >= self.count {
590            return f(Units::Bytes(&[]));
591        }
592        let i = id as usize;
593        let (start, end) = (self.starts[i] as usize, self.ends[i] as usize);
594        match self.sources[i] {
595            StringSource::Pool => f(Units::Utf16(&self.pool[start..end])),
596            StringSource::Canonical => with_canonical_text(|t| f(Units::Bytes(&t.as_bytes()[start..end]))),
597            StringSource::Value => match self.value_units.get(&id) {
598                Some(units) => f(Units::Utf16(units)),
599                None => f(Units::Bytes(self.cache.get(i).and_then(|c| c.as_ref()).map_or(&[][..], |s| s.as_bytes()))),
600            },
601            source => match self.texts.get(source as usize).and_then(|t| t.as_ref()) {
602                Some(CodeUnits::Bytes(b)) => f(Units::Bytes(&b[start..end])),
603                Some(CodeUnits::Utf16(u)) => f(Units::Utf16(&u[start..end])),
604                None => f(Units::Bytes(&[])),
605            },
606        }
607    }
608
609    /// append the code units of a string to a buffer. the string is not created
610    pub fn copy_into(&self, id: u32, target: &mut Vec<u16>) -> usize {
611        let length = self.length(id);
612        target.reserve(length);
613        let i = id as usize;
614        let start = self.starts[i] as usize;
615        match self.sources[i] {
616            StringSource::Pool => target.extend_from_slice(&self.pool[start..start + length]),
617            StringSource::Canonical => with_canonical_text(|t| target.extend(t.as_bytes()[start..start + length].iter().map(|&b| b as u16))),
618            StringSource::Value => {
619                if let Some(units) = self.value_units.get(&id) {
620                    target.extend_from_slice(units);
621                } else if let Some(Some(s)) = self.cache.get(i) {
622                    target.extend(s.bytes().map(|b| b as u16));
623                }
624            }
625            source => match self.texts[source as usize].as_ref() {
626                Some(CodeUnits::Bytes(b)) => target.extend(b[start..start + length].iter().map(|&b| b as u16)),
627                Some(CodeUnits::Utf16(u)) => target.extend_from_slice(&u[start..start + length]),
628                None => {}
629            },
630        }
631        length
632    }
633
634    /// a boolean property of a string, computed once per id from the string
635    pub fn flag(&mut self, id: u32, flag: StringFlag, compute: impl FnOnce(&str) -> bool) -> bool {
636        if let Some(value) = self.cached_flag(id, flag) {
637            return value;
638        }
639        let value = self.with_str(id, compute);
640        self.set_flag(id, flag, value);
641        value
642    }
643
644    /// the string of an id when it has been created (`cache[id]`)
645    pub fn cached(&self, id: u32) -> Option<SharedStr> {
646        self.cache.get(id as usize).cloned().flatten()
647    }
648
649    /// cached value of a flag, if it is computed
650    pub fn cached_flag(&self, id: u32, flag: StringFlag) -> Option<bool> {
651        let value = (self.flags.get(id as usize).copied().unwrap_or(0) >> (flag as u8 * 2)) & 3;
652        if value == 0 {
653            None
654        } else {
655            Some(value == 3)
656        }
657    }
658
659    /// store the value of a flag
660    pub fn set_flag(&mut self, id: u32, flag: StringFlag, value: bool) {
661        if id as usize >= self.flags.len() {
662            let size = (self.count.max(id + 1) * 2) as usize;
663            self.flags.resize(size, 0);
664        }
665        self.flags[id as usize] |= (if value { 3 } else { 1 }) << (flag as u8 * 2);
666    }
667
668    /// a value derived from a string, if it is computed
669    pub fn derived<T: Clone + 'static>(&self, id: u32, slot: StringDerived) -> Option<T> {
670        self.derived_values
671            .get(slot as usize)
672            .and_then(|m| m.as_ref())
673            .and_then(|m| m.get(&id))
674            .and_then(|v| v.downcast_ref::<T>())
675            .cloned()
676    }
677
678    /// store a value derived from a string
679    pub fn set_derived<T: 'static>(&mut self, id: u32, slot: StringDerived, value: T) {
680        let slot = slot as usize;
681        if self.derived_values.len() <= slot {
682            self.derived_values.resize_with(slot + 1, || None);
683        }
684        self.derived_values[slot].get_or_insert_with(HashMap::default).insert(id, Box::new(value));
685    }
686
687    /// append the bytes of a string to a buffer when it is ascii. returns the number of bytes, -1 when the string is
688    /// not ascii (nothing is appended)
689    pub fn copy_ascii(&self, id: u32, target: &mut Vec<u8>) -> isize {
690        self.with_units(id, |units| match units {
691            // a byte slice is ascii (the non ascii texts are stored as utf-16 code units)
692            Units::Bytes(bytes) => {
693                target.extend_from_slice(bytes);
694                bytes.len() as isize
695            }
696            Units::Utf16(units) => {
697                if units.iter().any(|&u| u > 0x7f) {
698                    return -1;
699                }
700                target.extend(units.iter().map(|&u| u as u8));
701                units.len() as isize
702            }
703        })
704    }
705
706    /// index of the first occurrence of a code unit, -1 when it is not found
707    pub fn index_of_code(&self, id: u32, code: u32) -> isize {
708        self.with_units(id, |units| match units {
709            Units::Bytes(bytes) => {
710                if code > 0x7f {
711                    return -1;
712                }
713                bytes.iter().position(|&b| b as u32 == code).map_or(-1, |i| i as isize)
714            }
715            Units::Utf16(units) => units.iter().position(|&u| u as u32 == code).map_or(-1, |i| i as isize),
716        })
717    }
718
719    /// true if the string of an id equals a string. the string is not created
720    pub fn equals(&self, id: u32, str: &str) -> bool {
721        if id >= self.count {
722            return false;
723        }
724        self.equals_string(id, str)
725    }
726
727    /// id of the lowercase string: the id itself when the string has no uppercase letter
728    pub fn lower(&mut self, id: u32) -> u32 {
729        if let Some(&l) = self.lowers.get(id as usize) {
730            if l != 0 {
731                return (l - 1) as u32;
732            }
733        }
734        let length = self.length(id);
735        let mut result = id;
736        for i in 0..length {
737            let code = self.code_at(id, i);
738            if code > 0x7f {
739                let str = self.get(id);
740                let lower = str.to_lowercase();
741                result = if *lower == *str { id } else { self.intern(&lower) };
742                break;
743            }
744            if (0x41..=0x5a).contains(&code) {
745                let mut builder = std::mem::take(&mut self.builder);
746                builder.reset().append_id(self, id);
747                for c in builder.codes[i..].iter_mut() {
748                    if (0x41..=0x5a).contains(c) {
749                        *c += 32;
750                    }
751                }
752                result = builder.intern(self);
753                self.builder = builder;
754                break;
755            }
756        }
757        if id as usize >= self.lowers.len() {
758            self.lowers.resize((self.count.max(id + 1) * 2) as usize, 0);
759        }
760        self.lowers[id as usize] = result as i32 + 1;
761        result
762    }
763
764    /// true if the string of an id starts with a string
765    pub fn starts_with(&self, id: u32, str: &str) -> bool {
766        if id >= self.count || self.length(id) < str.len() {
767            return false;
768        }
769        self.with_units(id, |units| match units {
770            Units::Bytes(bytes) => bytes.starts_with(str.as_bytes()),
771            Units::Utf16(units) => str.encode_utf16().zip(units.iter()).all(|(c, &u)| c == u) && units.len() >= str.encode_utf16().count(),
772        })
773    }
774
775    /// true if the string of an id equals a string, ignoring the case of the ascii letters
776    pub fn equals_ignore_case(&self, id: u32, str: &str) -> bool {
777        if id >= self.count {
778            return false;
779        }
780        let lower = |c: u32| if (65..=90).contains(&c) { c + 32 } else { c };
781        self.with_units(id, |units| match units {
782            Units::Bytes(bytes) => bytes.eq_ignore_ascii_case(str.as_bytes()),
783            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)),
784        })
785    }
786
787    /// drop the strings that are not used and renumber the others. returns the new id of each string
788    pub fn compact(&mut self, used: &[u8]) -> Vec<u32> {
789        let previous_count = self.count as usize;
790        let mut mapping = vec![0u32; previous_count];
791        let mut count = 0u32;
792        for id in 0..previous_count {
793            if used.get(id).copied().unwrap_or(0) != 0 {
794                mapping[id] = count;
795                count += 1;
796            }
797        }
798        let hashes = std::mem::take(&mut self.hashes);
799        let sources = std::mem::take(&mut self.sources);
800        let starts = std::mem::take(&mut self.starts);
801        let ends = std::mem::take(&mut self.ends);
802        let cache = std::mem::take(&mut self.cache);
803        let mut value_units = std::mem::take(&mut self.value_units);
804        let previous_pool = std::mem::take(&mut self.pool);
805        let mut pool = Vec::with_capacity(previous_pool.len().max(1024));
806        self.reset(count);
807        for id in 0..previous_count {
808            if used.get(id).copied().unwrap_or(0) == 0 {
809                continue;
810            }
811            let target = mapping[id] as usize;
812            let (mut start, mut end) = (starts[id], ends[id]);
813            if sources[id] == StringSource::Pool {
814                let offset = pool.len() as i32;
815                pool.extend_from_slice(&previous_pool[start as usize..end as usize]);
816                end = offset + end - start;
817                start = offset;
818            }
819            self.hashes[target] = hashes[id];
820            self.sources[target] = sources[id];
821            self.starts[target] = start;
822            self.ends[target] = end;
823            if let Some(Some(c)) = cache.get(id) {
824                self.set_cache(target as u32, c.clone());
825            }
826            if let Some(units) = value_units.remove(&(id as u32)) {
827                self.value_units.insert(target as u32, units);
828            }
829        }
830        self.pool = pool;
831        self.rehash();
832        mapping
833    }
834
835    /// copy of the table
836    pub fn export(&self) -> StringTableData {
837        let count = self.count as usize;
838        StringTableData {
839            count: self.count,
840            hashes: self.hashes[..count].to_vec(),
841            sources: self.sources[..count].to_vec(),
842            starts: self.starts[..count].to_vec(),
843            ends: self.ends[..count].to_vec(),
844            texts: self.texts.clone(),
845            pool: self.pool.clone(),
846            values: (0..count)
847                .map(|id| if self.sources[id] == StringSource::Value { self.cache.get(id).cloned().flatten().map(Rc::from) } else { None })
848                .collect(),
849        }
850    }
851
852    /// initialize the table from an exported copy
853    pub fn import(&mut self, data: &StringTableData) {
854        let count = data.count as usize;
855        self.reset(data.count);
856        self.hashes[..count].copy_from_slice(&data.hashes[..count]);
857        self.sources[..count].copy_from_slice(&data.sources[..count]);
858        self.starts[..count].copy_from_slice(&data.starts[..count]);
859        self.ends[..count].copy_from_slice(&data.ends[..count]);
860        self.texts = data.texts.clone();
861        self.pool = data.pool.clone();
862        for id in 0..count {
863            if data.sources[id] == StringSource::Value {
864                if let Some(Some(v)) = data.values.get(id) {
865                    if !v.is_ascii() {
866                        self.value_units.insert(id as u32, v.encode_utf16().collect::<Vec<u16>>().into());
867                    }
868                    self.set_cache(id as u32, v.clone());
869                }
870            }
871        }
872        self.rehash();
873    }
874
875    fn add(&mut self, hash: i32, slot: usize, source: i32, start: i32, end: i32) -> u32 {
876        let id = self.count as usize;
877        self.count += 1;
878        if id == self.hashes.len() {
879            self.grow(id * 2);
880        }
881        self.hashes[id] = hash;
882        self.sources[id] = source;
883        self.starts[id] = start;
884        self.ends[id] = end;
885        self.slots[slot] = id as i32 + 1;
886        if self.count as usize * 2 > self.slots.len() {
887            self.rehash();
888        }
889        id as u32
890    }
891
892    fn equals_units(&self, id: u32, codes: &[u16]) -> bool {
893        self.length(id) == codes.len() && codes.iter().enumerate().all(|(i, &c)| self.code_at(id, i) == c as u32)
894    }
895
896    fn equals_bytes(&self, id: u32, codes: &[u8]) -> bool {
897        self.length(id) == codes.len() && codes.iter().enumerate().all(|(i, &c)| self.code_at(id, i) == c as u32)
898    }
899
900    fn equals_code_range(&self, id: u32, codes: &CodeUnits, start: usize, end: usize) -> bool {
901        let length = end - start;
902        if self.length(id) != length {
903            return false;
904        }
905        let i = id as usize;
906        // same buffer, same range
907        let source = self.sources[i];
908        if source >= 0 && self.starts[i] as usize == start {
909            if let Some(text) = self.texts[source as usize].as_ref() {
910                let same = match (text, codes) {
911                    (CodeUnits::Bytes(a), CodeUnits::Bytes(b)) => Rc::ptr_eq(a, b),
912                    (CodeUnits::Utf16(a), CodeUnits::Utf16(b)) => Rc::ptr_eq(a, b),
913                    _ => false,
914                };
915                if same {
916                    return true;
917                }
918            }
919        }
920        // the units of the string are borrowed once and compared as slices (a memcmp when the widths match)
921        self.with_units(id, |units| match (units, codes) {
922            (Units::Bytes(a), CodeUnits::Bytes(b)) => a == &b[start..end],
923            (Units::Utf16(a), CodeUnits::Utf16(b)) => a == &b[start..end],
924            (Units::Bytes(a), CodeUnits::Utf16(b)) => a.iter().zip(&b[start..end]).all(|(&x, &y)| x as u16 == y),
925            (Units::Utf16(a), CodeUnits::Bytes(b)) => a.iter().zip(&b[start..end]).all(|(&x, &y)| x == y as u16),
926        })
927    }
928
929    fn equals_string(&self, id: u32, str: &str) -> bool {
930        let i = id as usize;
931        if let Some(Some(cached)) = self.cache.get(i) {
932            return **cached == *str;
933        }
934        if self.sources[i] == StringSource::Value {
935            return false;
936        }
937        self.with_units(id, |units| match units {
938            Units::Bytes(bytes) => bytes == str.as_bytes(),
939            Units::Utf16(units) => units.len() == str.encode_utf16().count() && str.encode_utf16().zip(units.iter()).all(|(c, &u)| c == u),
940        })
941    }
942
943    fn grow(&mut self, size: usize) {
944        self.hashes.resize(size, 0);
945        self.sources.resize(size, 0);
946        self.starts.resize(size, 0);
947        self.ends.resize(size, 0);
948    }
949
950    /// drop the strings, allocate the columns for `count` strings. the ids change
951    fn reset(&mut self, count: u32) {
952        let size = (count as usize).max(256);
953        self.count = count;
954        self.cache = Vec::new();
955        self.value_units = HashMap::default();
956        self.epoch = next_epoch();
957        self.lowers = Vec::new();
958        self.flags = Vec::new();
959        self.derived_values = Vec::new();
960        self.hashes = vec![0; size];
961        self.sources = vec![0; size];
962        self.starts = vec![0; size];
963        self.ends = vec![0; size];
964    }
965
966    fn rehash(&mut self) {
967        let mut size = 512;
968        while size < self.count as usize * 4 {
969            size *= 2;
970        }
971        let mut slots = vec![0i32; size];
972        let mask = size - 1;
973        for id in 0..self.count as usize {
974            let mut slot = (self.hashes[id] as usize) & mask;
975            while slots[slot] != 0 {
976                slot = (slot + 1) & mask;
977            }
978            slots[slot] = id as i32 + 1;
979        }
980        self.slots = slots;
981    }
982}