Skip to main content

leanfran_runtime/
string.rs

1//! `String`: UTF-8 bytes with a `'\0'` terminator, `m_size` bytes including it, `m_length`
2//! code points. `String.Pos` is a byte offset.
3
4use crate::array::lean_alloc_sarray;
5use crate::nat::lean_usize_to_nat;
6use crate::object::*;
7use core::mem::{offset_of, size_of};
8use core::ptr;
9
10const STRING_DATA: usize = offset_of!(StringObject, m_data);
11
12#[inline]
13unsafe fn so(o: Obj) -> *mut StringObject {
14    o as *mut StringObject
15}
16
17/* Allocation and access */
18
19#[inline]
20pub unsafe fn lean_alloc_string(size: usize, capacity: usize, len: usize) -> Obj {
21    let o = lean_alloc_object(size_of::<StringObject>() + capacity);
22    lean_set_st_header(o, LEAN_STRING as u32, 0);
23    (*so(o)).m_size = size;
24    (*so(o)).m_capacity = capacity;
25    (*so(o)).m_length = len;
26    o
27}
28
29#[inline]
30pub unsafe fn lean_string_cstr(o: Obj) -> *const u8 {
31    debug_check_live(o, "string read");
32    (o as *const u8).add(STRING_DATA)
33}
34
35#[inline]
36unsafe fn w_string_cstr(o: Obj) -> *mut u8 {
37    (o as *mut u8).add(STRING_DATA)
38}
39
40/// Byte size including the terminator.
41#[inline]
42pub unsafe fn lean_string_size(o: Obj) -> usize {
43    (*so(o)).m_size
44}
45
46/// Number of code points.
47#[inline]
48pub unsafe fn lean_string_len(o: Obj) -> usize {
49    (*so(o)).m_length
50}
51
52#[inline]
53pub unsafe fn lean_string_capacity(o: Obj) -> usize {
54    (*so(o)).m_capacity
55}
56
57#[inline]
58pub unsafe fn lean_string_byte_size(o: Obj) -> usize {
59    size_of::<StringObject>() + lean_string_capacity(o)
60}
61
62/// The bytes of a string without the terminator.
63#[inline]
64pub unsafe fn lean_string_bytes<'a>(o: Obj) -> &'a [u8] {
65    core::slice::from_raw_parts(lean_string_cstr(o), lean_string_size(o) - 1)
66}
67
68/// The contents of a string (borrowed; the string must stay alive while the result is used).
69#[inline]
70pub unsafe fn lean_string_to_str<'a>(o: Obj) -> &'a str {
71    core::str::from_utf8_unchecked(lean_string_bytes(o))
72}
73
74#[inline]
75pub fn lean_char_default_value() -> u32 {
76    'A' as u32
77}
78
79/// A string from `sz` bytes of valid UTF-8 with `len` code points.
80pub unsafe fn lean_mk_string_unchecked(s: &str, sz: usize, len: usize) -> Obj {
81    mk_string_bytes_unchecked(&s.as_bytes()[..sz], len)
82}
83
84unsafe fn mk_string_bytes_unchecked(b: &[u8], len: usize) -> Obj {
85    let rsz = b.len() + 1;
86    let r = lean_alloc_string(rsz, rsz, len);
87    ptr::copy_nonoverlapping(b.as_ptr(), w_string_cstr(r), b.len());
88    *w_string_cstr(r).add(b.len()) = 0;
89    r
90}
91
92/// A string from valid UTF-8 bytes.
93pub unsafe fn lean_mk_string_from_bytes_unchecked(b: &[u8]) -> Obj {
94    mk_string_bytes_unchecked(b, utf8_strlen(b))
95}
96
97/// A string from bytes; invalid sequences become U+FFFD.
98pub unsafe fn lean_mk_string_from_bytes(b: &[u8]) -> Obj {
99    match core::str::from_utf8(b) {
100        Ok(s) => mk_string_bytes_unchecked(b, s.chars().count()),
101        Err(_) => lean_mk_string(&String::from_utf8_lossy(b)),
102    }
103}
104
105pub unsafe fn lean_mk_string(s: &str) -> Obj {
106    mk_string_bytes_unchecked(s.as_bytes(), s.chars().count())
107}
108
109pub unsafe fn lean_mk_ascii_string_unchecked(s: &str) -> Obj {
110    mk_string_bytes_unchecked(s.as_bytes(), s.len())
111}
112
113/* UTF-8 helpers */
114
115pub(crate) fn utf8_strlen(b: &[u8]) -> usize {
116    b.iter().filter(|&&c| (c & 0xc0) != 0x80).count()
117}
118
119#[inline]
120fn is_utf8_first_byte(c: u8) -> bool {
121    (c & 0x80) == 0 || (c & 0xe0) == 0xc0 || (c & 0xf0) == 0xe0 || (c & 0xf8) == 0xf0
122}
123
124/// UTF-8 encoding of a code point (`push_unicode_scalar`).
125pub(crate) fn encode_utf8(c: u32, out: &mut Vec<u8>) {
126    if c < 0x80 {
127        out.push(c as u8);
128    } else if c < 0x800 {
129        out.push((0xc0 | (c >> 6)) as u8);
130        out.push((0x80 | (c & 0x3f)) as u8);
131    } else if c < 0x10000 {
132        out.push((0xe0 | (c >> 12)) as u8);
133        out.push((0x80 | ((c >> 6) & 0x3f)) as u8);
134        out.push((0x80 | (c & 0x3f)) as u8);
135    } else {
136        out.push((0xf0 | (c >> 18)) as u8);
137        out.push((0x80 | ((c >> 12) & 0x3f)) as u8);
138        out.push((0x80 | ((c >> 6) & 0x3f)) as u8);
139        out.push((0x80 | (c & 0x3f)) as u8);
140    }
141}
142
143/// Decodes the code point at byte `i` of `s` (`lean_string_utf8_get_core`).
144fn utf8_get_core(s: &[u8], i: usize) -> Option<u32> {
145    let size = s.len();
146    let c = s[i] as u32;
147    if c & 0x80 == 0 {
148        return Some(c);
149    }
150    if (c & 0xe0) == 0xc0 && i + 1 < size {
151        let r = ((c & 0x1f) << 6) | (s[i + 1] as u32 & 0x3f);
152        if r >= 0x80 {
153            return Some(r);
154        }
155    }
156    if (c & 0xf0) == 0xe0 && i + 2 < size {
157        let r = ((c & 0x0f) << 12) | ((s[i + 1] as u32 & 0x3f) << 6) | (s[i + 2] as u32 & 0x3f);
158        if r >= 0x800 && !(0xD800..=0xDFFF).contains(&r) {
159            return Some(r);
160        }
161    }
162    if (c & 0xf8) == 0xf0 && i + 3 < size {
163        let r = ((c & 0x07) << 18)
164            | ((s[i + 1] as u32 & 0x3f) << 12)
165            | ((s[i + 2] as u32 & 0x3f) << 6)
166            | (s[i + 3] as u32 & 0x3f);
167        if (0x10000..=0x10FFFF).contains(&r) {
168            return Some(r);
169        }
170    }
171    None
172}
173
174/// Decodes all code points of valid UTF-8.
175fn utf8_decode(s: &[u8]) -> Vec<u32> {
176    let mut out = Vec::new();
177    let mut i = 0;
178    while i < s.len() {
179        out.push(utf8_get_core(s, i).unwrap_or(lean_char_default_value()));
180        i += utf8_char_size(s[i]);
181    }
182    out
183}
184
185#[inline]
186fn utf8_char_size(c: u8) -> usize {
187    if c & 0x80 == 0 {
188        1
189    } else if (c & 0xe0) == 0xc0 {
190        2
191    } else if (c & 0xf0) == 0xe0 {
192        3
193    } else if (c & 0xf8) == 0xf0 {
194        4
195    } else {
196        1
197    }
198}
199
200/// Validates UTF-8 as Lean does (no surrogates, at most U+10FFFF); returns the code point count.
201pub(crate) fn validate_utf8(s: &[u8]) -> Option<usize> {
202    core::str::from_utf8(s).ok().map(|t| t.chars().count())
203}
204
205/* Copies */
206
207pub unsafe fn lean_copy_string(s: Obj, cap: usize) -> Obj {
208    let sz = lean_string_size(s);
209    let r = lean_alloc_string(sz, cap, lean_string_len(s));
210    if (*s).m_other & LEAN_LINEAR_MARK_MASK != 0 {
211        (*r).m_other |= LEAN_LINEAR_MARK_MASK;
212    }
213    ptr::copy_nonoverlapping(lean_string_cstr(s), w_string_cstr(r), sz);
214    lean_dec_ref(s);
215    r
216}
217
218pub unsafe fn lean_copy_string_nonlinear(s: Obj, cap: usize) -> Obj {
219    lean_copy_string(s, cap)
220}
221
222#[inline]
223pub unsafe fn lean_string_ensure_exclusive(s: Obj) -> Obj {
224    if lean_is_exclusive(s) {
225        s
226    } else {
227        lean_copy_string(s, lean_string_capacity(s))
228    }
229}
230
231unsafe fn string_ensure_capacity(o: Obj, extra: usize) -> Obj {
232    let sz = lean_string_size(o);
233    let cap = lean_string_capacity(o);
234    if sz + extra > cap {
235        let r = lean_alloc_string(sz, cap + sz + extra, lean_string_len(o));
236        (*r).m_other = (*o).m_other;
237        ptr::copy_nonoverlapping(lean_string_cstr(o), w_string_cstr(r), sz);
238        lean_dealloc(o, lean_string_byte_size(o));
239        r
240    } else {
241        o
242    }
243}
244
245/// Appends `bytes` (with `len` code points) to the owned string `s`.
246unsafe fn string_append_bytes(s: Obj, bytes: &[u8], len: usize) -> Obj {
247    let sz = lean_string_size(s);
248    let new_sz = sz + bytes.len();
249    let r = if !lean_is_exclusive(s) {
250        lean_copy_string(s, new_sz * 2)
251    } else {
252        string_ensure_capacity(s, bytes.len())
253    };
254    ptr::copy_nonoverlapping(bytes.as_ptr(), w_string_cstr(r).add(sz - 1), bytes.len());
255    (*so(r)).m_size = new_sz;
256    (*so(r)).m_length += len;
257    *w_string_cstr(r).add(new_sz - 1) = 0;
258    r
259}
260
261/* Operations */
262
263pub unsafe fn lean_string_push(s: Obj, c: u32) -> Obj {
264    let mut buf = Vec::with_capacity(4);
265    encode_utf8(c, &mut buf);
266    string_append_bytes(s, &buf, 1)
267}
268
269/// Consumes `s1`, borrows `s2`.
270pub unsafe fn lean_string_append(s1: Obj, s2: Obj) -> Obj {
271    let len2 = lean_string_len(s2);
272    if s1 == s2 {
273        let b = lean_string_bytes(s2).to_vec();
274        return string_append_bytes(s1, &b, len2);
275    }
276    string_append_bytes(s1, lean_string_bytes(s2), len2)
277}
278
279#[inline]
280pub unsafe fn lean_string_length(s: Obj) -> Obj {
281    lean_box(lean_string_len(s))
282}
283
284#[inline]
285pub unsafe fn lean_string_utf8_byte_size(s: Obj) -> Obj {
286    lean_box(lean_string_size(s) - 1)
287}
288
289/// `String.ofList` (consumes the list).
290pub unsafe fn lean_string_mk(cs: Obj) -> Obj {
291    let mut bytes = Vec::new();
292    let mut len = 0;
293    let mut o = cs;
294    while !lean_is_scalar(o) {
295        encode_utf8(lean_unbox_uint32(lean_ctor_get(o, 0)), &mut bytes);
296        o = lean_ctor_get(o, 1);
297        len += 1;
298    }
299    lean_dec(cs);
300    mk_string_bytes_unchecked(&bytes, len)
301}
302
303/// The list of characters of a string (consumes it).
304pub unsafe fn lean_string_data(s: Obj) -> Obj {
305    let cs = utf8_decode(lean_string_bytes(s));
306    lean_dec_ref(s);
307    let mut r = lean_box(0);
308    for c in cs.into_iter().rev() {
309        let n = lean_alloc_ctor(1, 2, 0);
310        lean_ctor_set(n, 0, lean_box_uint32(c));
311        lean_ctor_set(n, 1, r);
312        r = n;
313    }
314    r
315}
316
317pub unsafe fn lean_string_utf8_get(s: Obj, i0: Obj) -> u32 {
318    if !lean_is_scalar(i0) {
319        return lean_char_default_value();
320    }
321    let i = lean_unbox(i0);
322    let b = lean_string_bytes(s);
323    if i >= b.len() {
324        return lean_char_default_value();
325    }
326    utf8_get_core(b, i).unwrap_or(lean_char_default_value())
327}
328
329#[inline]
330pub unsafe fn lean_string_utf8_get_fast(s: Obj, i: Obj) -> u32 {
331    let b = lean_string_bytes(s);
332    let idx = lean_unbox(i);
333    let c = *lean_string_cstr(s).add(idx);
334    if c & 0x80 == 0 {
335        return c as u32;
336    }
337    utf8_get_core(b, idx).unwrap_or(lean_char_default_value())
338}
339
340pub unsafe fn lean_string_utf8_get_opt(s: Obj, i0: Obj) -> Obj {
341    if !lean_is_scalar(i0) {
342        return lean_box(0);
343    }
344    let i = lean_unbox(i0);
345    let b = lean_string_bytes(s);
346    if i >= b.len() {
347        return lean_box(0);
348    }
349    match utf8_get_core(b, i) {
350        Some(c) => {
351            let r = lean_alloc_ctor(1, 1, 0);
352            lean_ctor_set(r, 0, lean_box_uint32(c));
353            r
354        }
355        None => lean_box(0),
356    }
357}
358
359pub unsafe fn lean_string_utf8_get_bang(s: Obj, i0: Obj) -> u32 {
360    let b = lean_string_bytes(s);
361    let ok = if lean_is_scalar(i0) && lean_unbox(i0) < b.len() {
362        utf8_get_core(b, lean_unbox(i0))
363    } else {
364        None
365    };
366    match ok {
367        Some(c) => c,
368        None => {
369            crate::panic::lean_panic_fn(
370                lean_box(0),
371                lean_mk_ascii_string_unchecked("Error: invalid `String.Pos` at `String.get!`"),
372            );
373            lean_char_default_value()
374        }
375    }
376}
377
378pub unsafe fn lean_string_utf8_next(s: Obj, i0: Obj) -> Obj {
379    if !lean_is_scalar(i0) {
380        return crate::nat::lean_nat_add(i0, lean_box(1));
381    }
382    let i = lean_unbox(i0);
383    let b = lean_string_bytes(s);
384    if i >= b.len() {
385        return lean_usize_to_nat(i + 1);
386    }
387    lean_box(i + utf8_char_size(b[i]))
388}
389
390#[inline]
391pub unsafe fn lean_string_utf8_next_fast(s: Obj, i: Obj) -> Obj {
392    let idx = lean_unbox(i);
393    let c = *lean_string_cstr(s).add(idx);
394    lean_box(idx + utf8_char_size(c))
395}
396
397pub unsafe fn lean_string_utf8_prev(s: Obj, i0: Obj) -> Obj {
398    if !lean_is_scalar(i0) {
399        return crate::nat::lean_nat_sub(i0, lean_box(1));
400    }
401    let mut i = lean_unbox(i0);
402    let b = lean_string_bytes(s);
403    if i == 0 {
404        return lean_box(0);
405    }
406    if i > b.len() {
407        return lean_box(i - 1);
408    }
409    i -= 1;
410    while !is_utf8_first_byte(b[i]) {
411        i -= 1;
412    }
413    lean_box(i)
414}
415
416pub unsafe fn lean_string_is_valid_pos(s: Obj, i0: Obj) -> u8 {
417    if !lean_is_scalar(i0) {
418        return 0;
419    }
420    let i = lean_unbox(i0);
421    let b = lean_string_bytes(s);
422    if i > b.len() {
423        return 0;
424    }
425    if i == b.len() {
426        return 1;
427    }
428    is_utf8_first_byte(b[i]) as u8
429}
430
431#[inline]
432pub unsafe fn lean_string_utf8_at_end(s: Obj, i: Obj) -> u8 {
433    (!lean_is_scalar(i) || lean_unbox(i) >= lean_string_size(s) - 1) as u8
434}
435
436pub unsafe fn lean_string_utf8_extract(s: Obj, b0: Obj, e0: Obj) -> Obj {
437    let b = if lean_is_scalar(b0) {
438        lean_unbox(b0)
439    } else {
440        usize::MAX
441    };
442    let mut e = if lean_is_scalar(e0) {
443        lean_unbox(e0)
444    } else {
445        usize::MAX
446    };
447    let bytes = lean_string_bytes(s);
448    let sz = bytes.len();
449    if b >= e || b >= sz {
450        return lean_mk_string_unchecked("", 0, 0);
451    }
452    if !is_utf8_first_byte(bytes[b]) {
453        return lean_mk_string_unchecked("", 0, 0);
454    }
455    if e > sz {
456        e = sz;
457    }
458    if e < sz && !is_utf8_first_byte(bytes[e]) {
459        e = sz;
460    }
461    lean_mk_string_from_bytes_unchecked(&bytes[b..e])
462}
463
464pub unsafe fn lean_string_utf8_extract_fast(s: Obj, b0: Obj, e0: Obj) -> Obj {
465    let b = lean_unbox(b0);
466    let e = lean_unbox(e0);
467    if b >= e {
468        return lean_mk_string_unchecked("", 0, 0);
469    }
470    lean_mk_string_from_bytes_unchecked(&lean_string_bytes(s)[b..e])
471}
472
473/// Consumes `s`, borrows `i0`.
474pub unsafe fn lean_string_utf8_set(s: Obj, i0: Obj, c: u32) -> Obj {
475    if !lean_is_scalar(i0) {
476        return s;
477    }
478    let i = lean_unbox(i0);
479    let sz = lean_string_size(s) - 1;
480    if i >= sz {
481        return s;
482    }
483    let old = *lean_string_cstr(s).add(i);
484    if old < 128 && c < 128 {
485        let r = lean_string_ensure_exclusive(s);
486        *w_string_cstr(r).add(i) = c as u8;
487        return r;
488    }
489    if !is_utf8_first_byte(old) {
490        return s;
491    }
492    let mut bytes = lean_string_bytes(s).to_vec();
493    let len = lean_string_len(s);
494    let marked = (*s).m_other & LEAN_LINEAR_MARK_MASK;
495    lean_dec(s);
496    let mut tmp = Vec::new();
497    encode_utf8(c, &mut tmp);
498    let old_sz = utf8_char_size(old).min(bytes.len() - i);
499    bytes.splice(i..i + old_sz, tmp);
500    let r = mk_string_bytes_unchecked(&bytes, len);
501    (*r).m_other |= marked;
502    r
503}
504
505#[inline]
506pub unsafe fn lean_string_get_byte_fast(s: Obj, i: Obj) -> u8 {
507    *lean_string_cstr(s).add(lean_unbox(i))
508}
509
510#[inline]
511pub unsafe fn lean_string_uget_byte_fast(s: Obj, i: usize) -> u8 {
512    *lean_string_cstr(s).add(i)
513}
514
515/* Comparison and hashing */
516
517#[inline]
518pub unsafe fn lean_string_eq(s1: Obj, s2: Obj) -> bool {
519    s1 == s2
520        || (lean_string_size(s1) == lean_string_size(s2)
521            && lean_string_bytes(s1) == lean_string_bytes(s2))
522}
523
524#[inline]
525pub unsafe fn lean_string_ne(s1: Obj, s2: Obj) -> bool {
526    !lean_string_eq(s1, s2)
527}
528
529#[inline]
530pub unsafe fn lean_string_dec_eq(s1: Obj, s2: Obj) -> u8 {
531    lean_string_eq(s1, s2) as u8
532}
533
534pub unsafe fn lean_string_lt(s1: Obj, s2: Obj) -> bool {
535    lean_string_bytes(s1) < lean_string_bytes(s2)
536}
537
538#[inline]
539pub unsafe fn lean_string_dec_lt(s1: Obj, s2: Obj) -> u8 {
540    lean_string_lt(s1, s2) as u8
541}
542
543/// `compare` as an `Ordering` constructor index (0 lt, 1 eq, 2 gt).
544pub unsafe fn lean_string_compare(s1: Obj, s2: Obj) -> u8 {
545    match lean_string_bytes(s1).cmp(lean_string_bytes(s2)) {
546        core::cmp::Ordering::Less => 0,
547        core::cmp::Ordering::Equal => 1,
548        core::cmp::Ordering::Greater => 2,
549    }
550}
551
552/// MurmurHash64A of the bytes, as `hash_str` in `hash.cpp`.
553pub fn murmur_hash_64a(key: &[u8], seed: u64) -> u64 {
554    const M: u64 = 0xc6a4a7935bd1e995;
555    const R: u32 = 47;
556    let len = key.len();
557    let mut h = seed ^ (len as u64).wrapping_mul(M);
558    let (chunks, rest) = key.as_chunks::<8>();
559    for chunk in chunks {
560        let mut k = u64::from_le_bytes(*chunk);
561        k = k.wrapping_mul(M);
562        k ^= k >> R;
563        k = k.wrapping_mul(M);
564        h ^= k;
565        h = h.wrapping_mul(M);
566    }
567    if !rest.is_empty() {
568        for (i, b) in rest.iter().enumerate() {
569            h ^= (*b as u64) << (8 * i);
570        }
571        h = h.wrapping_mul(M);
572    }
573    h ^= h >> R;
574    h = h.wrapping_mul(M);
575    h ^= h >> R;
576    h
577}
578
579pub unsafe fn lean_string_hash(s: Obj) -> u64 {
580    murmur_hash_64a(lean_string_bytes(s), 11)
581}
582
583pub unsafe fn lean_string_of_usize(n: usize) -> Obj {
584    lean_mk_ascii_string_unchecked(&n.to_string())
585}
586
587pub unsafe fn lean_string_memcmp(s1: Obj, s2: Obj, lstart: Obj, rstart: Obj, len: Obj) -> u8 {
588    let (l, r, n) = (lean_unbox(lstart), lean_unbox(rstart), lean_unbox(len));
589    let a = core::slice::from_raw_parts(lean_string_cstr(s1).add(l), n);
590    let b = core::slice::from_raw_parts(lean_string_cstr(s2).add(r), n);
591    (a == b) as u8
592}
593
594/* Conversions with `ByteArray` */
595
596pub unsafe fn lean_string_to_utf8(s: Obj) -> Obj {
597    let b = lean_string_bytes(s);
598    let r = lean_alloc_sarray(1, b.len(), b.len());
599    ptr::copy_nonoverlapping(b.as_ptr(), crate::array::lean_sarray_cptr(r), b.len());
600    r
601}
602
603/// Consumes the byte array.
604pub unsafe fn lean_string_from_utf8_unchecked(a: Obj) -> Obj {
605    let r = lean_mk_string_from_bytes_unchecked(crate::array::sarray_bytes(a));
606    lean_dec(a);
607    r
608}
609
610pub unsafe fn lean_string_validate_utf8(a: Obj) -> u8 {
611    validate_utf8(crate::array::sarray_bytes(a)).is_some() as u8
612}
613
614pub unsafe fn lean_decode_lossy_utf8(a: Obj) -> Obj {
615    lean_mk_string_from_bytes(crate::array::sarray_bytes(a))
616}
617
618/* Slices (`String.Slice`: string, start byte, end byte) */
619
620unsafe fn slice_bytes<'a>(slice: Obj) -> &'a [u8] {
621    let s = lean_ctor_get(slice, 0);
622    let b = lean_unbox(lean_ctor_get(slice, 1));
623    let e = lean_unbox(lean_ctor_get(slice, 2));
624    core::slice::from_raw_parts(lean_string_cstr(s).add(b), e - b)
625}
626
627pub unsafe fn lean_slice_hash(s: Obj) -> u64 {
628    murmur_hash_64a(slice_bytes(s), 11)
629}
630
631pub unsafe fn lean_slice_dec_lt(s1: Obj, s2: Obj) -> u8 {
632    (slice_bytes(s1) < slice_bytes(s2)) as u8
633}