Skip to main content

zu_vector/kernels/
strings.rs

1//! The string library as vector kernels (ISO 20.9, features GF04 to
2//! GF07).
3//!
4//! The numeric kernels beside this one all answer a number the same
5//! width as the register they wrote it in, so the only question they
6//! had was whether a row has an answer. A string function asks a
7//! second question the numeric ones never do: where do the answer's
8//! bytes live. The two length functions are here first because they
9//! are the ones that do not ask it. An answer that is a count is a
10//! whole number, so the output is an ordinary integer vector and
11//! nothing is written into the arena but numbers.
12//!
13//! That makes the lengths the place to settle the other half of the
14//! string story, which is the encodings. A column of strings reaches a
15//! kernel three ways: flat views, one constant standing for the chunk,
16//! and dictionary codes over a shared table of entries. The numeric
17//! kernels refuse the third and ask the caller to materialize first;
18//! here it is the cheapest of the three, because the length of a code
19//! is the length of its entry and a chunk of two thousand rows over a
20//! table of a thousand entries costs a thousand counts and a gather
21//! rather than two thousand counts. The narrower the table the wider
22//! the gap, and a column of a few dozen distinct values is where the
23//! saving is worth having.
24//!
25//! The functions that answer a string sort themselves by how many
26//! bytes they have to put somewhere. A trim puts none anywhere, since
27//! what it answers is a part of what it was handed and those bytes are
28//! already in a buffer somebody is holding, so its answers point back
29//! into the argument, and the two substring functions are the same
30//! thing counted from one end. A fold writes as much as it was handed,
31//! an ASCII fold never changing a byte's width. Anything that can
32//! change a length, which is what a normal form does, has to write out
33//! an amount it cannot know in advance, and that is the case the
34//! builder exists for.
35
36use std::sync::Arc;
37
38use zu_common::unicode::{self, NormalForm};
39use zu_common::{Result, ZuError, gqlstatus::codes};
40
41use crate::arena::MorselArena;
42use crate::bitmap::Bitmap;
43use crate::sel::SelVector;
44use crate::str::{INLINE_LEN, NO_BUFFERS, StrBuffers, StrBuilder, StrView};
45use crate::vector::{Aux, PhysType, ValueVector, VecEncoding};
46
47/// Which length a call asked for.
48///
49/// The two are one kernel because they differ in a single line and
50/// agree about everything else that is hard: the encodings, the nulls,
51/// and the fact that neither can raise.
52#[derive(Clone, Copy, PartialEq, Eq, Debug)]
53pub enum StrLen {
54    /// CHAR_LENGTH, and CHARACTER_LENGTH under its long spelling. The
55    /// count of characters, which over UTF-8 is the count of bytes
56    /// that are not continuations of the one before them.
57    Chars,
58    /// OCTET_LENGTH. The count of bytes, which a view carries in its
59    /// header, so this one never reads a payload at all.
60    Octets,
61}
62
63impl StrLen {
64    fn name(self) -> &'static str {
65        match self {
66            StrLen::Chars => "char_length",
67            StrLen::Octets => "octet_length",
68        }
69    }
70
71    /// The type the answers land in. A count is a whole number
72    /// whatever it counted, and the argument has to be a string.
73    pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
74        match arg {
75            PhysType::Str => Some(PhysType::Int64),
76            _ => None,
77        }
78    }
79
80    /// Whether a row could have no answer. Neither of these can: every
81    /// string has a length, and the count of anything a column holds
82    /// is far inside the range of an integer.
83    pub fn may_raise(self) -> bool {
84        false
85    }
86}
87
88/// The length of one string, in whichever unit was asked for.
89///
90/// The character count is written as a fold over the bytes rather than
91/// as a decode, because a byte begins a character exactly when it is
92/// not a continuation byte, and that is one comparison per byte with
93/// nothing the compiler cannot lay out flat. It is the answer the row
94/// engine gives, which counts what Rust calls chars.
95#[inline(always)]
96fn measure(op: StrLen, bytes: &[u8]) -> i64 {
97    match op {
98        StrLen::Octets => bytes.len() as i64,
99        StrLen::Chars => bytes.iter().filter(|b| (**b as i8) >= -0x40).count() as i64,
100    }
101}
102
103/// Evaluate `op(v)` into a new flat integer vector.
104///
105/// Nothing here can raise, so unlike the numeric kernels there is no
106/// pass to decide whether the loop is allowed to run. A row outside
107/// the selection and a row holding a null are measured anyway, since
108/// measuring one costs less than the branch that would skip it and
109/// neither answer is ever read.
110pub fn length(arena: &mut MorselArena, op: StrLen, v: &ValueVector) -> Result<ValueVector> {
111    if op.answer_type(v.phys).is_none() {
112        return Err(ZuError::InvalidArgument(format!(
113            "no {}() kernel for {:?}",
114            op.name(),
115            v.phys
116        )));
117    }
118    let len = v.len as usize;
119    let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
120    let mut out = ValueVector::flat_uninit(arena, PhysType::Int64, len);
121    match v.encoding {
122        // One string standing for the chunk, so one measurement stands
123        // for every row of it.
124        VecEncoding::Constant => {
125            let view = v.constant_value::<StrView>();
126            let n = measure(op, view.bytes(bufs));
127            out.values_mut::<i64>()[..len].fill(n);
128        }
129        // Codes over a shared table. The length of a code is the
130        // length of its entry, so the table is measured once and the
131        // rows are a gather over the answers.
132        VecEncoding::Dict { .. } => {
133            let dict = v.dictionary();
134            let table: Vec<i64> = (0..dict.len())
135                .map(|i| measure(op, dict.get(i as u32)))
136                .collect();
137            let codes = v.codes_u16();
138            let dst = out.values_mut::<i64>();
139            for (slot, code) in dst[..len].iter_mut().zip(codes) {
140                *slot = table[*code as usize];
141            }
142        }
143        VecEncoding::Flat => {
144            let views = v.values::<StrView>();
145            let dst = out.values_mut::<i64>();
146            match op {
147                // A view carries its byte count in its header, so the
148                // count of bytes is a read of the header and the
149                // payload is never touched at all.
150                StrLen::Octets => {
151                    for (slot, view) in dst[..len].iter_mut().zip(views) {
152                        *slot = view.len() as i64;
153                    }
154                }
155                StrLen::Chars => {
156                    for (slot, view) in dst[..len].iter_mut().zip(views) {
157                        *slot = measure(op, view.bytes(bufs));
158                    }
159                }
160            }
161        }
162    }
163    out.validity = carried(arena, v, len);
164    Ok(out)
165}
166
167/// NULL in, NULL out: the answer is null exactly where the argument
168/// was, and the bitmap is copied only where the argument carries one,
169/// an absent one meaning every row is valid and costing nothing.
170fn carried(arena: &mut MorselArena, v: &ValueVector, len: usize) -> Option<Bitmap> {
171    v.validity.as_ref().map(|valid| {
172        let mut copy = Bitmap::new_in(arena, len, true);
173        copy.and_with(valid);
174        copy
175    })
176}
177
178/// Which fold a call asked for.
179///
180/// Both are the ASCII fold, which is the fold the row engine does and
181/// the one the standard's default collation asks for: a letter of the
182/// English alphabet changes case and every other byte is left as it
183/// stands. It is worth saying what that buys, because it is the whole
184/// reason these two are the string library's easy pair. An ASCII fold
185/// never changes a byte's width, so the answer is exactly as long as
186/// the argument, an answer that sat inside its view still sits inside
187/// one, and a chunk's worth of answers needs no more room than the
188/// chunk it was made from. A fold with a Unicode table behind it would
189/// have none of that.
190#[derive(Clone, Copy, PartialEq, Eq, Debug)]
191pub enum StrFold {
192    /// UPPER.
193    Upper,
194    /// LOWER.
195    Lower,
196}
197
198impl StrFold {
199    fn name(self) -> &'static str {
200        match self {
201            StrFold::Upper => "upper",
202            StrFold::Lower => "lower",
203        }
204    }
205
206    /// The type the answers land in. A folded string is a string.
207    pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
208        match arg {
209            PhysType::Str => Some(PhysType::Str),
210            _ => None,
211        }
212    }
213
214    /// Whether a row could have no answer. Every string folds.
215    pub fn may_raise(self) -> bool {
216        false
217    }
218}
219
220/// How many bytes of `v` live outside their views, which is how much
221/// room a length preserving answer needs in the builder.
222///
223/// A short string is carried by the view itself and its answer will be
224/// too, so it asks for nothing here. The dictionary case counts each
225/// entry once, which is what the answers cost as well, the rows
226/// pointing at bytes rather than holding them.
227fn long_bytes(v: &ValueVector) -> usize {
228    let outside = |n: usize| if n > INLINE_LEN { n } else { 0 };
229    match v.encoding {
230        VecEncoding::Constant => outside(v.constant_value::<StrView>().len()),
231        VecEncoding::Dict { .. } => {
232            let dict = v.dictionary();
233            (0..dict.len())
234                .map(|i| outside(dict.get(i as u32).len()))
235                .sum()
236        }
237        VecEncoding::Flat => v
238            .values::<StrView>()
239            .iter()
240            .map(|view| outside(view.len()))
241            .sum(),
242    }
243}
244
245/// Fold `src` into `dst`, which is the same length.
246#[inline(always)]
247fn fold_into(op: StrFold, src: &[u8], dst: &mut [u8]) {
248    dst.copy_from_slice(src);
249    match op {
250        StrFold::Upper => dst.make_ascii_uppercase(),
251        StrFold::Lower => dst.make_ascii_lowercase(),
252    }
253}
254
255/// Evaluate `op(v)` into a new flat string vector.
256///
257/// The answers are flat views whatever the argument was, since a chunk
258/// of computed strings is read back by row and the encodings are the
259/// scan's business rather than a kernel's. What the encodings still
260/// decide is how much folding happens: a constant folds once, and
261/// codes over a table fold the table rather than the rows, so the
262/// bytes of an entry are written into the answer once however many
263/// rows point at it and the rest of the work is a gather over views.
264/// Only a flat argument folds a string a row.
265pub fn fold(arena: &mut MorselArena, op: StrFold, v: &ValueVector) -> Result<ValueVector> {
266    if op.answer_type(v.phys).is_none() {
267        return Err(ZuError::InvalidArgument(format!(
268            "no {}() kernel for {:?}",
269            op.name(),
270            v.phys
271        )));
272    }
273    let len = v.len as usize;
274    let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
275    let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
276    // What a fold answers is as long as what it was handed, so the room
277    // the long answers need is the room the long arguments took and the
278    // buffer is right the first time. Reading it is a walk of the view
279    // headers, which the fold is about to walk anyway.
280    let mut build = StrBuilder::with_capacity(long_bytes(v));
281    match v.encoding {
282        VecEncoding::Constant => {
283            let view = v.constant_value::<StrView>();
284            let bytes = view.bytes(bufs);
285            let one = build.push_with(bytes.len(), |dst| fold_into(op, bytes, dst));
286            out.values_mut::<StrView>()[..len].fill(one);
287        }
288        VecEncoding::Dict { .. } => {
289            let dict = v.dictionary();
290            let table: Vec<StrView> = (0..dict.len())
291                .map(|i| {
292                    let entry = dict.get(i as u32);
293                    build.push_with(entry.len(), |dst| fold_into(op, entry, dst))
294                })
295                .collect();
296            let codes = v.codes_u16();
297            let dst = out.values_mut::<StrView>();
298            for (slot, code) in dst[..len].iter_mut().zip(codes) {
299                *slot = table[*code as usize];
300            }
301        }
302        VecEncoding::Flat => {
303            let views = v.values::<StrView>();
304            let dst = out.values_mut::<StrView>();
305            for (slot, view) in dst[..len].iter_mut().zip(views) {
306                let bytes = view.bytes(bufs);
307                *slot = build.push_with(bytes.len(), |room| fold_into(op, bytes, room));
308            }
309        }
310    }
311    out.aux = Aux::Str(Arc::new(build.finish()));
312    out.validity = carried(arena, v, len);
313    Ok(out)
314}
315
316/// Which ends a trim takes characters off.
317///
318/// ISO 20.24 spells six functions here and the kernel knows three,
319/// because the whole of what the six disagree about is settled before a
320/// plan is built. `TRIM` takes one character and raises `22027` when it
321/// is handed more, and `BTRIM`, `LTRIM` and `RTRIM` take a set; that is
322/// a question about what was written, not about what the loop does, so
323/// the compiler asks it against the written set and this is left with
324/// the only thing that varies a row at a time.
325#[derive(Clone, Copy, PartialEq, Eq, Debug)]
326pub enum StrTrim {
327    /// TRIM and BTRIM: both ends.
328    Both,
329    /// TRIM LEADING and LTRIM: the front.
330    Leading,
331    /// TRIM TRAILING and RTRIM: the back.
332    Trailing,
333}
334
335impl StrTrim {
336    fn name(self) -> &'static str {
337        match self {
338            StrTrim::Both => "trim",
339            StrTrim::Leading => "ltrim",
340            StrTrim::Trailing => "rtrim",
341        }
342    }
343
344    fn front(self) -> bool {
345        matches!(self, StrTrim::Both | StrTrim::Leading)
346    }
347
348    fn back(self) -> bool {
349        matches!(self, StrTrim::Both | StrTrim::Trailing)
350    }
351
352    /// The type the answers land in. A trimmed string is a string.
353    pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
354        match arg {
355            PhysType::Str => Some(PhysType::Str),
356            _ => None,
357        }
358    }
359
360    /// Whether a row could have no answer. The one condition in the
361    /// trim family is about the trim set rather than about a row, and
362    /// it is settled at compile time, so nothing here can raise.
363    pub fn may_raise(self) -> bool {
364        false
365    }
366}
367
368/// The characters a trim takes off, in the form the loop wants them.
369///
370/// The set is written once in a statement and asked about once a
371/// character, so it is worth preparing. The plain characters become a
372/// bitmask, one bit each, which is the whole test for the sets almost
373/// every statement writes: a space, or a handful of punctuation. Any
374/// character past ASCII is kept as the bytes it is written as, and
375/// matching is then a comparison of bytes rather than a decode.
376///
377/// Bytes are enough because of what UTF-8 is. A byte below 128 is
378/// always a whole character and never part of a longer one, and the
379/// encoding of a character is never the front or the back of another
380/// character's encoding, so a match on bytes is a match on characters
381/// and no member of the set can be found halfway through something
382/// else.
383#[derive(Debug, Default)]
384pub struct TrimSet {
385    /// One bit a character for the members below 128.
386    ascii: u128,
387    /// The encodings of the members above it, which is usually none.
388    wide: Vec<Box<[u8]>>,
389}
390
391impl TrimSet {
392    /// The set a statement wrote, prepared.
393    pub fn new(chars: &str) -> Self {
394        let mut set = Self::default();
395        for c in chars.chars() {
396            if c.is_ascii() {
397                set.ascii |= 1u128 << (c as u8);
398            } else {
399                let mut buf = [0u8; 4];
400                let bytes = c.encode_utf8(&mut buf).as_bytes();
401                if !set.wide.iter().any(|w| &**w == bytes) {
402                    set.wide.push(bytes.into());
403                }
404            }
405        }
406        set
407    }
408
409    /// Whether the set has anything in it. An empty one trims nothing,
410    /// which is the answer the row engine gives too.
411    pub fn is_empty(&self) -> bool {
412        self.ascii == 0 && self.wide.is_empty()
413    }
414
415    /// How many bytes the character at the front of `bytes` takes, when
416    /// that character is a member. `bytes` is not empty.
417    #[inline(always)]
418    fn width_at(&self, bytes: &[u8]) -> Option<usize> {
419        let head = bytes[0];
420        if head < 0x80 {
421            return ((self.ascii >> head) & 1 == 1).then_some(1);
422        }
423        self.wide
424            .iter()
425            .find(|w| bytes.starts_with(w))
426            .map(|w| w.len())
427    }
428
429    /// The same for the character at the back of `bytes`.
430    #[inline(always)]
431    fn width_before(&self, bytes: &[u8]) -> Option<usize> {
432        let last = bytes[bytes.len() - 1];
433        if last < 0x80 {
434            return ((self.ascii >> last) & 1 == 1).then_some(1);
435        }
436        self.wide
437            .iter()
438            .find(|w| bytes.ends_with(w))
439            .map(|w| w.len())
440    }
441}
442
443/// The part of `bytes` a trim leaves: where it starts and how long it
444/// is.
445///
446/// Nothing is written here, which is the point. A trim of a string that
447/// has nothing to take off walks one character at each end it trims and
448/// answers the string it was given, and a trim that takes plenty off
449/// still only walks what it takes.
450#[inline(always)]
451fn kept(ends: StrTrim, set: &TrimSet, bytes: &[u8]) -> (usize, usize) {
452    let mut start = 0;
453    let mut end = bytes.len();
454    if ends.front() {
455        while start < end {
456            match set.width_at(&bytes[start..end]) {
457                Some(n) => start += n,
458                None => break,
459            }
460        }
461    }
462    if ends.back() {
463        while start < end {
464            match set.width_before(&bytes[start..end]) {
465                Some(n) => end -= n,
466                None => break,
467            }
468        }
469    }
470    (start, end - start)
471}
472
473/// Evaluate `ends(v, set)` into a new flat string vector.
474///
475/// This is the string kernel that fills no buffer. What a trim answers
476/// is a part of what it was handed, and a part of a string is bytes
477/// that are already somewhere, so a flat argument's answers are views
478/// back into the argument's own buffers and the answer vector holds the
479/// same buffers rather than a copy of them. A chunk of two thousand
480/// trimmed strings costs two thousand views and not one byte more.
481///
482/// That is a saving in memory rather than in time. The walk still
483/// tests the set once for every character it takes off, which on the
484/// bench's fifteen byte strings costs about what the fold's copy of
485/// the same string costs, so the two run level there.
486///
487/// A dictionary is the one shape that cannot do that, since the entries
488/// of a table are not bytes a view can name, so the table's answers are
489/// written out once an entry and the rows gather over them. That is
490/// still a table's worth of copying rather than a chunk's.
491pub fn trim(
492    arena: &mut MorselArena,
493    ends: StrTrim,
494    set: &TrimSet,
495    v: &ValueVector,
496) -> Result<ValueVector> {
497    if ends.answer_type(v.phys).is_none() {
498        return Err(ZuError::InvalidArgument(format!(
499            "no {}() kernel for {:?}",
500            ends.name(),
501            v.phys
502        )));
503    }
504    let len = v.len as usize;
505    let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
506    let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
507    // Set only where the answers' bytes had to be written somewhere,
508    // which is the dictionary and nothing else.
509    let mut made = None;
510    match v.encoding {
511        VecEncoding::Constant => {
512            let view = v.constant_value::<StrView>();
513            let bytes = view.bytes(bufs);
514            let (at, n) = kept(ends, set, bytes);
515            out.values_mut::<StrView>()[..len].fill(view.sub(bytes, at, n));
516        }
517        VecEncoding::Dict { .. } => {
518            let dict = v.dictionary();
519            let mut build = StrBuilder::with_capacity(long_bytes(v));
520            let table: Vec<StrView> = (0..dict.len())
521                .map(|i| {
522                    let entry = dict.get(i as u32);
523                    let (at, n) = kept(ends, set, entry);
524                    build.push(&entry[at..at + n])
525                })
526                .collect();
527            let codes = v.codes_u16();
528            let dst = out.values_mut::<StrView>();
529            for (slot, code) in dst[..len].iter_mut().zip(codes) {
530                *slot = table[*code as usize];
531            }
532            made = Some(build.finish());
533        }
534        VecEncoding::Flat => {
535            let views = v.values::<StrView>();
536            let dst = out.values_mut::<StrView>();
537            for (slot, view) in dst[..len].iter_mut().zip(views) {
538                let bytes = view.bytes(bufs);
539                let (at, n) = kept(ends, set, bytes);
540                *slot = view.sub(bytes, at, n);
541            }
542        }
543    }
544    out.aux = match made {
545        Some(bufs) => Aux::Str(Arc::new(bufs)),
546        // The argument's buffers, held rather than copied, because the
547        // answers are pointing into them.
548        None => match &v.aux {
549            Aux::Str(bufs) => Aux::Str(Arc::clone(bufs)),
550            _ => Aux::None,
551        },
552    };
553    out.validity = carried(arena, v, len);
554    Ok(out)
555}
556
557/// Which of the two normalization functions a call asked for.
558///
559/// They are one kernel's worth of thinking read two ways. `NORMALIZE`
560/// answers the string a form asks for and `IS NORMALIZED` answers
561/// whether the argument is that string already, so the second is the
562/// first with a comparison in place of an answer, and the standard
563/// defines it in exactly those words rather than through the quick
564/// check properties.
565///
566/// What separates them here is where the answer goes. A normalized
567/// string is a string and lands in a vector; a test is a predicate and
568/// lands in a bitmap, the way a comparison does, so the two have
569/// separate entry points below and this says which is which for the
570/// compiler's benefit.
571#[derive(Clone, Copy, PartialEq, Eq, Debug)]
572pub enum StrNorm {
573    /// NORMALIZE(s, form).
574    Into(NormalForm),
575    /// s IS NORMALIZED form.
576    Test(NormalForm),
577}
578
579impl StrNorm {
580    fn name(self) -> &'static str {
581        match self {
582            StrNorm::Into(_) => "normalize",
583            StrNorm::Test(_) => "is_normalized",
584        }
585    }
586
587    /// The form the call named, which the statement wrote or which the
588    /// standard's default supplied.
589    pub fn form(self) -> NormalForm {
590        match self {
591            StrNorm::Into(form) | StrNorm::Test(form) => form,
592        }
593    }
594
595    /// The type the answers land in. Both want a string; one gives a
596    /// string back and the other gives a truth value.
597    pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
598        match (self, arg) {
599            (StrNorm::Into(_), PhysType::Str) => Some(PhysType::Str),
600            (StrNorm::Test(_), PhysType::Str) => Some(PhysType::Bool),
601            _ => None,
602        }
603    }
604
605    /// Whether a row could have no answer. Every string has a normal
606    /// form and every string either is in it or is not, so neither of
607    /// these can raise.
608    pub fn may_raise(self) -> bool {
609        false
610    }
611}
612
613/// Whether every string in `v` is plain ASCII, in which case a
614/// normalization has nothing to do to any of them.
615///
616/// This is the question worth asking before the work starts. No
617/// character below 128 decomposes, canonically or by compatibility, and
618/// none of them is a combining mark, so a string of them is in all four
619/// forms already and what a normalization answers is what it was
620/// handed. Asking is a walk of the bytes with nothing to decide, which
621/// runs a word at a time, against a walk that decodes every character,
622/// looks it up, sorts what comes back and writes it out again.
623///
624/// The dictionary encoding is not asked, because its answer would not
625/// help. The bytes of a table entry are not bytes a view can point at,
626/// so a coded chunk writes its table out either way.
627fn all_ascii(v: &ValueVector, bufs: &StrBuffers) -> bool {
628    match v.encoding {
629        VecEncoding::Constant => v.constant_value::<StrView>().bytes(bufs).is_ascii(),
630        VecEncoding::Dict { .. } => false,
631        VecEncoding::Flat => v
632            .values::<StrView>()
633            .iter()
634            .all(|view| view.bytes(bufs).is_ascii()),
635    }
636}
637
638/// One string, normalized into the builder.
639///
640/// The ASCII test is asked a second time here, a string at a time,
641/// because a chunk holding one accented string still holds plenty that
642/// are plain and a plain one is a copy rather than a decode. What the
643/// test costs when the answer is no is a walk of bytes the
644/// normalization is about to walk anyway.
645///
646/// Bytes that are not UTF-8 cannot arrive, a vector's strings being
647/// UTF-8 by construction, and if they somehow did then handing them
648/// back as they stand loses nothing that was there. A kernel that
649/// promised it cannot raise does not get to change its mind over a
650/// buffer that was already wrong.
651#[inline]
652fn put(build: &mut StrBuilder, form: NormalForm, bytes: &[u8]) -> StrView {
653    if bytes.is_ascii() {
654        return build.push(bytes);
655    }
656    match std::str::from_utf8(bytes) {
657        Ok(s) => build.push(unicode::normalize(s, form).as_bytes()),
658        Err(_) => build.push(bytes),
659    }
660}
661
662/// Evaluate `NORMALIZE(v, form)` into a new flat string vector.
663///
664/// This is the string function the builder was built for. A trim
665/// answers a part of what it was handed and a fold answers something
666/// exactly as long, so both of them know where the answer's bytes are
667/// going before they start. A normal form knows neither: composing
668/// makes a string shorter, decomposing makes it longer, and how much
669/// either way is a fact about the characters rather than about the
670/// count of them. So the answers are written out and the room for them
671/// is a guess, the argument's own long bytes, which is right for
672/// everything a query normally holds and grows when it is not.
673///
674/// The one shape that costs nothing is the one nearly every column is:
675/// all ASCII, where the answers are the argument's own strings and the
676/// vector hands its buffers over the way a trim does.
677pub fn normalize(
678    arena: &mut MorselArena,
679    form: NormalForm,
680    v: &ValueVector,
681) -> Result<ValueVector> {
682    let op = StrNorm::Into(form);
683    if op.answer_type(v.phys).is_none() {
684        return Err(ZuError::InvalidArgument(format!(
685            "no {}() kernel for {:?}",
686            op.name(),
687            v.phys
688        )));
689    }
690    let len = v.len as usize;
691    let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
692    let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
693    if all_ascii(v, bufs) {
694        let dst = out.values_mut::<StrView>();
695        match v.encoding {
696            VecEncoding::Constant => dst[..len].fill(v.constant_value::<StrView>()),
697            _ => {
698                for (slot, view) in dst[..len].iter_mut().zip(v.values::<StrView>()) {
699                    *slot = *view;
700                }
701            }
702        }
703        // The argument's buffers, held rather than copied, because the
704        // answers are its own strings and are reading them where they
705        // already lie.
706        out.aux = match &v.aux {
707            Aux::Str(bufs) => Aux::Str(Arc::clone(bufs)),
708            _ => Aux::None,
709        };
710    } else {
711        let mut build = StrBuilder::with_capacity(long_bytes(v));
712        match v.encoding {
713            VecEncoding::Constant => {
714                let view = v.constant_value::<StrView>();
715                let one = put(&mut build, form, view.bytes(bufs));
716                out.values_mut::<StrView>()[..len].fill(one);
717            }
718            VecEncoding::Dict { .. } => {
719                let dict = v.dictionary();
720                let table: Vec<StrView> = (0..dict.len())
721                    .map(|i| put(&mut build, form, dict.get(i as u32)))
722                    .collect();
723                let codes = v.codes_u16();
724                let dst = out.values_mut::<StrView>();
725                for (slot, code) in dst[..len].iter_mut().zip(codes) {
726                    *slot = table[*code as usize];
727                }
728            }
729            VecEncoding::Flat => {
730                let views = v.values::<StrView>();
731                let dst = out.values_mut::<StrView>();
732                for (slot, view) in dst[..len].iter_mut().zip(views) {
733                    *slot = put(&mut build, form, view.bytes(bufs));
734                }
735            }
736        }
737        out.aux = Aux::Str(Arc::new(build.finish()));
738    }
739    out.validity = carried(arena, v, len);
740    Ok(out)
741}
742
743/// Write `v IS [NOT] NORMALIZED form` into `out`, which must be sized to
744/// the vector and cleared.
745///
746/// The negation is carried in rather than done afterwards, and that is
747/// not a shortcut but the only correct place for it. A predicate over a
748/// column of three-valued logic is a bitmap of the rows that passed, so
749/// a null row is off in the bitmap; taking the complement of the bitmap
750/// would turn every null row into a row that passed, and a null is not
751/// normalized and is not unnormalized either. Deciding the row here and
752/// masking the nulls off afterwards answers `IS NOT NORMALIZED` the way
753/// the row engine answers it, which is why there is no general NOT over
754/// a predicate register anywhere in this crate.
755pub fn normalized(
756    form: NormalForm,
757    negated: bool,
758    v: &ValueVector,
759    out: &mut Bitmap,
760) -> Result<()> {
761    let op = StrNorm::Test(form);
762    debug_assert_eq!(out.len(), v.len as usize);
763    if op.answer_type(v.phys).is_none() {
764        return Err(ZuError::InvalidArgument(format!(
765            "no {}() kernel for {:?}",
766            op.name(),
767            v.phys
768        )));
769    }
770    let len = v.len as usize;
771    let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
772    // ASCII is in every form already, which the row engine's answer
773    // reads as well, so a plain column is decided without a table being
774    // touched. Bytes that are not UTF-8 are called normalized for the
775    // same reason the other kernel hands them back untouched.
776    let holds = |bytes: &[u8]| match std::str::from_utf8(bytes) {
777        Ok(s) => unicode::is_normalized(s, form),
778        Err(_) => true,
779    };
780    match v.encoding {
781        VecEncoding::Constant => {
782            if holds(v.constant_value::<StrView>().bytes(bufs)) != negated {
783                out.words_mut().fill(!0u64);
784            }
785        }
786        VecEncoding::Dict { .. } => {
787            let dict = v.dictionary();
788            let table: Vec<bool> = (0..dict.len())
789                .map(|i| holds(dict.get(i as u32)) != negated)
790                .collect();
791            for (row, code) in v.codes_u16()[..len].iter().enumerate() {
792                if table[*code as usize] {
793                    out.set(row);
794                }
795            }
796        }
797        VecEncoding::Flat => {
798            for (row, view) in v.values::<StrView>()[..len].iter().enumerate() {
799                if holds(view.bytes(bufs)) != negated {
800                    out.set(row);
801                }
802            }
803        }
804    }
805    // A row with no string in it has no answer either way.
806    if let Some(valid) = &v.validity {
807        out.and_with(valid);
808    }
809    out.mask_tail();
810    Ok(())
811}
812
813/// Which end of a string a substring function counts from.
814///
815/// `LEFT` and `RIGHT` are the whole of the substring function in GQL,
816/// `SUBSTRING` being a word the standard has reserved and left without
817/// a meaning, so a query that wants the middle of a string writes one
818/// of these inside the other. They are one kernel because the only
819/// thing that differs is which end the walk starts at.
820#[derive(Clone, Copy, PartialEq, Eq, Debug)]
821pub enum StrCut {
822    /// `LEFT(s, n)`: the first n characters.
823    Left,
824    /// `RIGHT(s, n)`: the last n characters.
825    Right,
826}
827
828impl StrCut {
829    fn name(self) -> &'static str {
830        match self {
831            StrCut::Left => "left",
832            StrCut::Right => "right",
833        }
834    }
835
836    /// The type the answers land in. A part of a string is a string,
837    /// and the count has to be a whole number by the time it gets here:
838    /// a float count is one the row engine either truncates or raises
839    /// over, and both of those are its own words, so a column of them
840    /// goes back to it.
841    pub fn answer_type(self, arg: PhysType, count: PhysType) -> Option<PhysType> {
842        match (arg, count) {
843            (PhysType::Str, PhysType::Int64) => Some(PhysType::Str),
844            _ => None,
845        }
846    }
847
848    /// Whether a row could have no answer. A count is a number a row
849    /// can hold and a negative one raises `22011`, so the answer here
850    /// is yes and the compiler settles the case where the statement
851    /// wrote the count out.
852    pub fn may_raise(self) -> bool {
853        true
854    }
855}
856
857/// Where the first `count` characters of `bytes` end.
858///
859/// The walk is over what it takes rather than over what it was handed,
860/// which is what makes a cut cheap on a long string: `LEFT(s, 3)` looks
861/// at three characters however many the column holds. A character is
862/// one lead byte and the continuation bytes behind it, and a byte that
863/// is not UTF-8 counts as a character of its own, which is the only
864/// answer available and never reached through the row engine's types.
865#[inline(always)]
866fn prefix_end(bytes: &[u8], count: usize) -> usize {
867    let mut at = 0;
868    for _ in 0..count {
869        if at == bytes.len() {
870            break;
871        }
872        at += 1;
873        while at < bytes.len() && bytes[at] & 0xC0 == 0x80 {
874            at += 1;
875        }
876    }
877    at
878}
879
880/// Where the last `count` characters of `bytes` begin, walked from the
881/// back the same way.
882#[inline(always)]
883fn suffix_start(bytes: &[u8], count: usize) -> usize {
884    let mut at = bytes.len();
885    for _ in 0..count {
886        if at == 0 {
887            break;
888        }
889        at -= 1;
890        while at > 0 && bytes[at] & 0xC0 == 0x80 {
891            at -= 1;
892        }
893    }
894    at
895}
896
897/// The part of `bytes` a cut keeps: where it starts and how long it is.
898#[inline(always)]
899fn taken(cut: StrCut, bytes: &[u8], count: usize) -> (usize, usize) {
900    match cut {
901        StrCut::Left => (0, prefix_end(bytes, count)),
902        StrCut::Right => {
903            let at = suffix_start(bytes, count);
904            (at, bytes.len() - at)
905        }
906    }
907}
908
909/// The count a row asks for, clamped at nought.
910///
911/// A negative count has already raised by the time this runs, unless
912/// the row is one nobody selected or one whose string is null, and
913/// neither of those has an answer anybody reads.
914#[inline(always)]
915fn count_at(n: &ValueVector, row: usize) -> usize {
916    let c = match n.encoding {
917        VecEncoding::Constant => n.constant_value::<i64>(),
918        _ => n.values::<i64>()[row],
919    };
920    c.max(0) as usize
921}
922
923/// Raises what the row engine raises for the first selected row that
924/// asks for a negative number of characters.
925///
926/// The order matters and is the row engine's. A null string answers
927/// null before the count is looked at, so `LEFT(null, -1)` is null and
928/// not a condition, and a null count answers null as well. What is left
929/// is a row holding a string and a negative number, which is the one
930/// the standard gives `22011` to.
931///
932/// The fold comes first: a chunk whose counts are all at nought or
933/// above has no such row in it whatever the strings are, and that is
934/// every chunk a statement with a written count produces.
935fn check_counts(
936    cut: StrCut,
937    s: &ValueVector,
938    n: &ValueVector,
939    sel: Option<&SelVector>,
940    len: usize,
941) -> Result<()> {
942    let lowest = match n.encoding {
943        VecEncoding::Constant => n.constant_value::<i64>(),
944        _ => n.values::<i64>()[..len].iter().copied().min().unwrap_or(0),
945    };
946    if lowest >= 0 {
947        return Ok(());
948    }
949    let visit = |row: usize| -> Result<()> {
950        if !s.is_valid(row) || !n.is_valid(row) {
951            return Ok(());
952        }
953        let asked = match n.encoding {
954            VecEncoding::Constant => n.constant_value::<i64>(),
955            _ => n.values::<i64>()[row],
956        };
957        if asked < 0 {
958            return Err(ZuError::gql(
959                codes::C22011,
960                format!(
961                    "{}() was asked for {asked} characters, and a string has no negative number of them",
962                    cut.name()
963                ),
964            ));
965        }
966        Ok(())
967    };
968    match sel {
969        Some(sel) => {
970            for &row in sel.as_slice() {
971                visit(row as usize)?;
972            }
973        }
974        None => {
975            for row in 0..len {
976                visit(row)?;
977            }
978        }
979    }
980    Ok(())
981}
982
983/// Evaluate `cut(s, n)` into a new flat string vector.
984///
985/// This is the trim's trick a second time. What a cut answers is a part
986/// of what it was handed, so a flat or a constant argument's answers
987/// are views back into the argument's own bytes and the answer vector
988/// holds the same buffers rather than a copy of them. What is new is
989/// that the part is decided by a second column rather than by something
990/// the statement wrote, so the two encodings multiply: a count that is
991/// the same for the whole chunk lets a dictionary cut its table once,
992/// and a count that varies makes a coded column write a row at a time,
993/// since two rows over one entry no longer answer the same thing.
994///
995/// A dictionary is the one shape that has to write at all, an entry of
996/// a table not being bytes a view can name. Everything else copies
997/// nothing.
998pub fn cut(
999    arena: &mut MorselArena,
1000    cut: StrCut,
1001    s: &ValueVector,
1002    n: &ValueVector,
1003    sel: Option<&SelVector>,
1004) -> Result<ValueVector> {
1005    debug_assert_eq!(s.len, n.len);
1006    if cut.answer_type(s.phys, n.phys).is_none() {
1007        return Err(ZuError::InvalidArgument(format!(
1008            "no {}() kernel for {:?} and {:?}",
1009            cut.name(),
1010            s.phys,
1011            n.phys
1012        )));
1013    }
1014    if matches!(n.encoding, VecEncoding::Dict { .. }) {
1015        return Err(ZuError::InvalidArgument(
1016            "substring counts on dict vectors: materialize first".into(),
1017        ));
1018    }
1019    let len = s.len as usize;
1020    check_counts(cut, s, n, sel, len)?;
1021    let one_count = matches!(n.encoding, VecEncoding::Constant);
1022    let bufs = s.str_buffers().unwrap_or(&NO_BUFFERS);
1023    let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
1024    // Set only where the answers' bytes had to be written somewhere,
1025    // which is the dictionary and nothing else.
1026    let mut made = None;
1027    match s.encoding {
1028        VecEncoding::Constant => {
1029            let view = s.constant_value::<StrView>();
1030            let bytes = view.bytes(bufs);
1031            let dst = out.values_mut::<StrView>();
1032            if one_count {
1033                let (at, took) = taken(cut, bytes, count_at(n, 0));
1034                dst[..len].fill(view.sub(bytes, at, took));
1035            } else {
1036                for (row, slot) in dst[..len].iter_mut().enumerate() {
1037                    let (at, took) = taken(cut, bytes, count_at(n, row));
1038                    *slot = view.sub(bytes, at, took);
1039                }
1040            }
1041        }
1042        VecEncoding::Dict { .. } => {
1043            let dict = s.dictionary();
1044            let codes = s.codes_u16();
1045            let mut build = StrBuilder::with_capacity(long_bytes(s));
1046            let dst = out.values_mut::<StrView>();
1047            if one_count {
1048                let count = count_at(n, 0);
1049                let table: Vec<StrView> = (0..dict.len())
1050                    .map(|i| {
1051                        let entry = dict.get(i as u32);
1052                        let (at, took) = taken(cut, entry, count);
1053                        build.push(&entry[at..at + took])
1054                    })
1055                    .collect();
1056                for (slot, code) in dst[..len].iter_mut().zip(codes) {
1057                    *slot = table[*code as usize];
1058                }
1059            } else {
1060                for (row, slot) in dst[..len].iter_mut().enumerate() {
1061                    let entry = dict.get(codes[row] as u32);
1062                    let (at, took) = taken(cut, entry, count_at(n, row));
1063                    *slot = build.push(&entry[at..at + took]);
1064                }
1065            }
1066            made = Some(build.finish());
1067        }
1068        VecEncoding::Flat => {
1069            let views = s.values::<StrView>();
1070            let dst = out.values_mut::<StrView>();
1071            for (row, (slot, view)) in dst[..len].iter_mut().zip(views).enumerate() {
1072                let bytes = view.bytes(bufs);
1073                let (at, took) = taken(cut, bytes, count_at(n, row));
1074                *slot = view.sub(bytes, at, took);
1075            }
1076        }
1077    }
1078    out.aux = match made {
1079        Some(bufs) => Aux::Str(Arc::new(bufs)),
1080        // The argument's buffers, held rather than copied, because the
1081        // answers are pointing into them.
1082        None => match &s.aux {
1083            Aux::Str(bufs) => Aux::Str(Arc::clone(bufs)),
1084            _ => Aux::None,
1085        },
1086    };
1087    // Either argument being null makes the answer null, which is two
1088    // columns' worth of validity rather than one.
1089    out.validity = match (&s.validity, &n.validity) {
1090        (None, None) => None,
1091        (left, right) => {
1092            let mut copy = Bitmap::new_in(arena, len, true);
1093            if let Some(valid) = left {
1094                copy.and_with(valid);
1095            }
1096            if let Some(valid) = right {
1097                copy.and_with(valid);
1098            }
1099            Some(copy)
1100        }
1101    };
1102    Ok(out)
1103}
1104
1105/// The longest a number takes here: twenty digits and a sign.
1106const DIGITS: usize = 21;
1107
1108/// `n` written into the end of `buf`, answered as the part of `buf`
1109/// that holds it.
1110///
1111/// Backwards, because the last digit is the one arithmetic hands over
1112/// first. Writing it forwards means measuring the number before writing
1113/// it, which is the same chain of divides a second time, and a division
1114/// per digit is most of what an identifier costs.
1115fn written(n: i64, buf: &mut [u8; DIGITS]) -> &[u8] {
1116    let mut at = buf.len();
1117    let mut left = n.unsigned_abs();
1118    loop {
1119        at -= 1;
1120        buf[at] = b'0' + (left % 10) as u8;
1121        left /= 10;
1122        if left == 0 {
1123            break;
1124        }
1125    }
1126    if n < 0 {
1127        at -= 1;
1128        buf[at] = b'-';
1129    }
1130    &buf[at..]
1131}
1132
1133/// The identifiers of a chunk's nodes, which is `n:` and then the table
1134/// and the row each node sits at.
1135///
1136/// A level of a plan has one table for every row it will ever produce
1137/// and carries the row itself as a column, so the identifier is a head
1138/// written once for the whole chunk and a number written once a row.
1139/// That is the reason this is a kernel rather than a call: the argument
1140/// is a node and no chunk holds one, but the two numbers a node is made
1141/// of are both here already.
1142///
1143/// The row is an integer and not a string, so nothing about the answer
1144/// is read out of the argument the way a trim or a substring reads its
1145/// answer out of the string it was handed. Every identifier is written,
1146/// and nearly all of them are written into the view itself: a table
1147/// under ten and a row under nine digits is twelve bytes, which is what
1148/// fits inline, so a chunk of a normal graph fills no buffer at all.
1149///
1150/// A negative row cannot come out of storage and is written with its
1151/// sign rather than being refused, since a kernel that answers for
1152/// every input it can be handed is one fewer thing to get right.
1153pub fn element_ids(arena: &mut MorselArena, table: u32, rows: &ValueVector) -> Result<ValueVector> {
1154    if !matches!(rows.phys, PhysType::Int64) {
1155        return Err(ZuError::InvalidArgument(format!(
1156            "no ELEMENT_ID() kernel for {:?}",
1157            rows.phys
1158        )));
1159    }
1160    if matches!(rows.encoding, VecEncoding::Dict { .. }) {
1161        return Err(ZuError::InvalidArgument(
1162            "element identifiers over a dict vector: materialize first".into(),
1163        ));
1164    }
1165    let len = rows.len as usize;
1166    // `n:` and the table and a colon, which is at most thirteen bytes
1167    // and the same bytes for every row of the chunk.
1168    let mut digits = [0u8; DIGITS];
1169    let table = written(i64::from(table), &mut digits);
1170    let mut buf = [0u8; 13];
1171    buf[0] = b'n';
1172    buf[1] = b':';
1173    buf[2..2 + table.len()].copy_from_slice(table);
1174    buf[2 + table.len()] = b':';
1175    let head = &buf[..3 + table.len()];
1176
1177    let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
1178    let mut build = StrBuilder::new();
1179    let mut row_digits = [0u8; DIGITS];
1180    let one = |build: &mut StrBuilder, row: i64, room: &mut [u8; DIGITS]| {
1181        let tail = written(row, room);
1182        build.push_with(head.len() + tail.len(), |dst| {
1183            dst[..head.len()].copy_from_slice(head);
1184            dst[head.len()..].copy_from_slice(tail);
1185        })
1186    };
1187    match rows.encoding {
1188        VecEncoding::Constant => {
1189            let view = one(&mut build, rows.constant_value::<i64>(), &mut row_digits);
1190            out.values_mut::<StrView>()[..len].fill(view);
1191        }
1192        // Flat, the dictionary having been turned away above.
1193        _ => {
1194            let vals = rows.values::<i64>();
1195            let dst = out.values_mut::<StrView>();
1196            for (slot, &row) in dst[..len].iter_mut().zip(vals) {
1197                *slot = one(&mut build, row, &mut row_digits);
1198            }
1199        }
1200    }
1201    out.aux = Aux::Str(Arc::new(build.finish()));
1202    // A row broadcast in from an optional match that found nothing is
1203    // null, and the identifier of a node that is not there is null too.
1204    out.validity = carried(arena, rows, len);
1205    Ok(out)
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use super::*;
1211    use crate::str::Dictionary;
1212    use crate::vector::{Aux, str_vector};
1213    use std::sync::Arc;
1214
1215    /// A count of characters and a count of bytes are the same number
1216    /// only while the strings are plain, and they part company at the
1217    /// first one that is not.
1218    #[test]
1219    fn the_two_lengths_part_company_outside_ascii() {
1220        let mut arena = MorselArena::new();
1221        let v = str_vector(&mut arena, &["", "abc", "héllo", "🙂", "a\tb"]);
1222        let chars = length(&mut arena, StrLen::Chars, &v).unwrap();
1223        assert_eq!(chars.phys, PhysType::Int64);
1224        assert_eq!(chars.values::<i64>(), &[0, 3, 5, 1, 3]);
1225        let octets = length(&mut arena, StrLen::Octets, &v).unwrap();
1226        assert_eq!(octets.values::<i64>(), &[0, 3, 6, 4, 3]);
1227    }
1228
1229    /// A string longer than a view holds inline lives in a buffer, and
1230    /// the character count has to resolve through it rather than
1231    /// reading the header and stopping.
1232    #[test]
1233    fn a_string_too_long_to_sit_inline_is_measured_through_its_buffer() {
1234        let mut arena = MorselArena::new();
1235        let long = "a string well past the twelve bytes a view holds";
1236        let v = str_vector(&mut arena, &["short", long]);
1237        let chars = length(&mut arena, StrLen::Chars, &v).unwrap();
1238        assert_eq!(chars.values::<i64>(), &[5, long.chars().count() as i64]);
1239        let octets = length(&mut arena, StrLen::Octets, &v).unwrap();
1240        assert_eq!(octets.values::<i64>(), &[5, long.len() as i64]);
1241    }
1242
1243    /// One string standing for the chunk is measured once, and the
1244    /// answer is the same for every row of it.
1245    #[test]
1246    fn a_constant_is_measured_once() {
1247        let mut arena = MorselArena::new();
1248        let mut v = ValueVector::constant(
1249            &mut arena,
1250            PhysType::Str,
1251            StrView::inline("héllo".as_bytes()),
1252            4,
1253        );
1254        v.aux = Aux::None;
1255        let out = length(&mut arena, StrLen::Chars, &v).unwrap();
1256        assert_eq!(out.values::<i64>(), &[5, 5, 5, 5]);
1257    }
1258
1259    /// Codes over a shared table, which the numeric kernels refuse and
1260    /// this one answers faster than either of the other two encodings.
1261    /// The answer has to be what the same strings flat would have
1262    /// given.
1263    #[test]
1264    fn a_dictionary_is_measured_a_table_at_a_time() {
1265        let mut arena = MorselArena::new();
1266        let entries = ["", "a", "héllo", "🙂"];
1267        let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
1268        let codes = [3u16, 0, 2, 1, 2];
1269        let v = ValueVector::dict_str(&mut arena, &codes, dict);
1270        let chars = length(&mut arena, StrLen::Chars, &v).unwrap();
1271        assert_eq!(chars.values::<i64>(), &[1, 0, 5, 1, 5]);
1272        let octets = length(&mut arena, StrLen::Octets, &v).unwrap();
1273        assert_eq!(octets.values::<i64>(), &[4, 0, 6, 1, 6]);
1274    }
1275
1276    /// A null argument answers null rather than nought, which is the
1277    /// one thing a count must not quietly get wrong: nought is the
1278    /// length of the empty string and says something else entirely.
1279    #[test]
1280    fn a_null_argument_answers_null_and_not_nought() {
1281        let mut arena = MorselArena::new();
1282        let mut v = str_vector(&mut arena, &["ab", "", "cde"]);
1283        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1284        valid.clear(1);
1285        v.validity = Some(valid);
1286        let out = length(&mut arena, StrLen::Chars, &v).unwrap();
1287        assert!(!out.is_valid(1), "null in, null out");
1288        assert!(out.is_valid(0) && out.is_valid(2));
1289        assert_eq!(out.values::<i64>()[0], 2);
1290        assert_eq!(out.values::<i64>()[2], 3);
1291    }
1292
1293    /// Neither of these has a row it cannot answer, which is what lets
1294    /// one of them stand in a projection and behind an OR where a root
1295    /// or a distance from nought cannot.
1296    #[test]
1297    fn a_length_cannot_raise_and_answers_a_whole_number() {
1298        assert!(!StrLen::Chars.may_raise());
1299        assert!(!StrLen::Octets.may_raise());
1300        assert_eq!(
1301            StrLen::Chars.answer_type(PhysType::Str),
1302            Some(PhysType::Int64)
1303        );
1304        assert_eq!(StrLen::Octets.answer_type(PhysType::Int64), None);
1305    }
1306
1307    /// Reads a string vector back the way a sink would, so a test can
1308    /// say what a fold answered without caring which side of the
1309    /// twelve byte line each answer fell.
1310    fn read(v: &ValueVector) -> Vec<String> {
1311        let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
1312        v.values::<StrView>()
1313            .iter()
1314            .map(|view| String::from_utf8(view.bytes(bufs).to_vec()).unwrap())
1315            .collect()
1316    }
1317
1318    /// The fold is the ASCII one, so the English letters change case
1319    /// and everything else is left exactly as it stands, an accented
1320    /// letter and an emoji included.
1321    #[test]
1322    fn a_fold_moves_the_english_letters_and_nothing_else() {
1323        let mut arena = MorselArena::new();
1324        let v = str_vector(&mut arena, &["Ann", "bo", "", "héllo", "🙂 x9"]);
1325        let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
1326        assert_eq!(up.phys, PhysType::Str);
1327        assert_eq!(read(&up), ["ANN", "BO", "", "HéLLO", "🙂 X9"]);
1328        let down = fold(&mut arena, StrFold::Lower, &v).unwrap();
1329        assert_eq!(read(&down), ["ann", "bo", "", "héllo", "🙂 x9"]);
1330    }
1331
1332    /// An answer longer than a view holds has to land in the builder's
1333    /// buffer and read back through it, and an answer that fits stays
1334    /// inside its view, so a chunk holding both has to answer both.
1335    #[test]
1336    fn a_long_answer_lands_in_a_buffer_and_a_short_one_does_not() {
1337        let mut arena = MorselArena::new();
1338        let long = "a string well past the twelve bytes a view holds";
1339        let v = str_vector(&mut arena, &["short", long]);
1340        let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
1341        let views = up.values::<StrView>();
1342        assert!(views[0].is_inline(), "a short answer stays in its view");
1343        assert!(!views[1].is_inline(), "a long one goes to the buffer");
1344        assert_eq!(read(&up), ["SHORT", &long.to_ascii_uppercase()]);
1345    }
1346
1347    /// One string standing for the chunk is folded once, and every row
1348    /// reads the one answer back.
1349    #[test]
1350    fn a_constant_is_folded_once() {
1351        let mut arena = MorselArena::new();
1352        let mut v = ValueVector::constant(
1353            &mut arena,
1354            PhysType::Str,
1355            StrView::inline("héllo".as_bytes()),
1356            3,
1357        );
1358        v.aux = Aux::None;
1359        let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
1360        assert_eq!(read(&up), ["HéLLO", "HéLLO", "HéLLO"]);
1361    }
1362
1363    /// Codes over a table fold the table rather than the rows, and the
1364    /// answer still has to be what the same strings flat would have
1365    /// given, repeated codes and all.
1366    #[test]
1367    fn a_dictionary_is_folded_a_table_at_a_time() {
1368        let mut arena = MorselArena::new();
1369        let entries = ["Ann", "a longer name than a view holds", "bo"];
1370        let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
1371        let codes = [2u16, 0, 1, 0, 1];
1372        let v = ValueVector::dict_str(&mut arena, &codes, dict);
1373        let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
1374        let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
1375        assert_eq!(
1376            read(&up),
1377            read(&fold(&mut arena, StrFold::Upper, &flat).unwrap())
1378        );
1379        assert_eq!(read(&up)[0], "BO");
1380        assert_eq!(read(&up)[2], entries[1].to_ascii_uppercase());
1381    }
1382
1383    /// A null argument answers null, and the rows around it answer
1384    /// what they would have answered on their own.
1385    #[test]
1386    fn a_fold_of_a_null_is_null() {
1387        let mut arena = MorselArena::new();
1388        let mut v = str_vector(&mut arena, &["Ann", "Bo", "Cy"]);
1389        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1390        valid.clear(1);
1391        v.validity = Some(valid);
1392        let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
1393        assert!(!up.is_valid(1), "null in, null out");
1394        assert!(up.is_valid(0) && up.is_valid(2));
1395        assert_eq!(read(&up)[0], "ANN");
1396        assert_eq!(read(&up)[2], "CY");
1397    }
1398
1399    /// Neither fold has a row it cannot answer, and a folded string is
1400    /// a string.
1401    #[test]
1402    fn a_fold_cannot_raise_and_answers_a_string() {
1403        assert!(!StrFold::Upper.may_raise());
1404        assert!(!StrFold::Lower.may_raise());
1405        assert_eq!(
1406            StrFold::Lower.answer_type(PhysType::Str),
1407            Some(PhysType::Str)
1408        );
1409        assert_eq!(StrFold::Upper.answer_type(PhysType::Float64), None);
1410    }
1411
1412    /// The three ends, over a set of one character, which is the shape
1413    /// TRIM itself is limited to.
1414    #[test]
1415    fn each_end_trims_the_end_it_names() {
1416        let mut arena = MorselArena::new();
1417        let v = str_vector(&mut arena, &["  ann  ", "bo", "   ", ""]);
1418        let set = TrimSet::new(" ");
1419        let both = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
1420        assert_eq!(both.phys, PhysType::Str);
1421        assert_eq!(read(&both), ["ann", "bo", "", ""]);
1422        let front = trim(&mut arena, StrTrim::Leading, &set, &v).unwrap();
1423        assert_eq!(read(&front), ["ann  ", "bo", "", ""]);
1424        let back = trim(&mut arena, StrTrim::Trailing, &set, &v).unwrap();
1425        assert_eq!(read(&back), ["  ann", "bo", "", ""]);
1426    }
1427
1428    /// A set of several characters, which is what btrim and its two
1429    /// neighbours exist for: any member comes off, in any order, until
1430    /// something that is not a member is reached.
1431    #[test]
1432    fn a_set_takes_any_of_its_members_off() {
1433        let mut arena = MorselArena::new();
1434        let v = str_vector(&mut arena, &["xyxaxbyx", "xxx", "axb"]);
1435        let set = TrimSet::new("xy");
1436        let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
1437        assert_eq!(read(&out), ["axb", "", "axb"]);
1438    }
1439
1440    /// A member past ASCII is matched as the bytes it is written as,
1441    /// and matching bytes has to still be matching characters: a trim
1442    /// of the accented letter must not eat half of it or half of
1443    /// anything else.
1444    #[test]
1445    fn a_wide_member_comes_off_whole() {
1446        let mut arena = MorselArena::new();
1447        let v = str_vector(&mut arena, &["ééhélloé", "🙂a🙂", "é🙂é"]);
1448        let set = TrimSet::new("é🙂");
1449        let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
1450        assert_eq!(read(&out), ["héllo", "a", ""]);
1451        // The accented letter's second byte is a continuation byte and
1452        // shares it with plenty of others, so a trim that matched bytes
1453        // one at a time would cut this string apart.
1454        let v = str_vector(&mut arena, &["ñ"]);
1455        let out = trim(&mut arena, StrTrim::Both, &TrimSet::new("é"), &v).unwrap();
1456        assert_eq!(read(&out), ["ñ"]);
1457    }
1458
1459    /// An empty set trims nothing, which is what the row engine
1460    /// answers: nothing is a member, so the first character at either
1461    /// end stops the walk.
1462    #[test]
1463    fn an_empty_set_answers_the_string_it_was_given() {
1464        let mut arena = MorselArena::new();
1465        let set = TrimSet::new("");
1466        assert!(set.is_empty());
1467        let v = str_vector(&mut arena, &["  ann  ", ""]);
1468        let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
1469        assert_eq!(read(&out), ["  ann  ", ""]);
1470    }
1471
1472    /// The whole reason a trim costs no memory: a flat argument's
1473    /// answers point back into the argument's own bytes, so the answer
1474    /// vector holds the buffers it was handed and fills none of its
1475    /// own.
1476    #[test]
1477    fn a_trimmed_string_points_back_at_what_it_was_trimmed_from() {
1478        let mut arena = MorselArena::new();
1479        let long = "  a string well past the twelve bytes a view holds  ";
1480        let v = str_vector(&mut arena, &[long, "  short  "]);
1481        let out = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v).unwrap();
1482        assert_eq!(read(&out), [long.trim(), "short"]);
1483        let views = out.values::<StrView>();
1484        assert!(!views[0].is_inline(), "a long answer stays in the buffer");
1485        assert!(views[1].is_inline(), "a short one fits in its view");
1486        // Handed over, not copied: the answers are reading the
1487        // argument's bytes where they already lie.
1488        let (Aux::Str(theirs), Aux::Str(ours)) = (&v.aux, &out.aux) else {
1489            panic!("a chunk with a long string in it carries buffers");
1490        };
1491        assert!(Arc::ptr_eq(theirs, ours));
1492    }
1493
1494    /// One string standing for the chunk is trimmed once, and every row
1495    /// reads the one answer back.
1496    #[test]
1497    fn a_constant_is_trimmed_once() {
1498        let mut arena = MorselArena::new();
1499        let mut v = ValueVector::constant(
1500            &mut arena,
1501            PhysType::Str,
1502            StrView::inline("  ann  ".as_bytes()),
1503            3,
1504        );
1505        v.aux = Aux::None;
1506        let out = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v).unwrap();
1507        assert_eq!(read(&out), ["ann", "ann", "ann"]);
1508    }
1509
1510    /// Codes over a table trim the table rather than the rows, and the
1511    /// answer still has to be what the same strings flat would have
1512    /// given.
1513    #[test]
1514    fn a_dictionary_is_trimmed_a_table_at_a_time() {
1515        let mut arena = MorselArena::new();
1516        let entries = ["  a longer entry than a view holds  ", " ann ", "bo  "];
1517        let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
1518        let codes = [2u16, 0, 1, 0];
1519        let v = ValueVector::dict_str(&mut arena, &codes, dict);
1520        let set = TrimSet::new(" ");
1521        let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
1522        let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
1523        assert_eq!(
1524            read(&out),
1525            read(&trim(&mut arena, StrTrim::Both, &set, &flat).unwrap())
1526        );
1527        assert_eq!(read(&out)[0], "bo");
1528        assert_eq!(read(&out)[1], entries[0].trim());
1529    }
1530
1531    /// A null argument answers null, and the rows around it answer what
1532    /// they would have answered on their own.
1533    #[test]
1534    fn a_trim_of_a_null_is_null() {
1535        let mut arena = MorselArena::new();
1536        let mut v = str_vector(&mut arena, &[" ann ", " bo ", " cy "]);
1537        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1538        valid.clear(1);
1539        v.validity = Some(valid);
1540        let out = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v).unwrap();
1541        assert!(!out.is_valid(1), "null in, null out");
1542        assert!(out.is_valid(0) && out.is_valid(2));
1543        assert_eq!(read(&out)[0], "ann");
1544        assert_eq!(read(&out)[2], "cy");
1545    }
1546
1547    /// No trim has a row it cannot answer, the one condition in the
1548    /// family being about the set rather than about a row, and a
1549    /// trimmed string is a string.
1550    #[test]
1551    fn a_trim_cannot_raise_and_answers_a_string() {
1552        assert!(!StrTrim::Both.may_raise());
1553        assert_eq!(
1554            StrTrim::Leading.answer_type(PhysType::Str),
1555            Some(PhysType::Str)
1556        );
1557        assert_eq!(StrTrim::Trailing.answer_type(PhysType::Int64), None);
1558    }
1559
1560    /// The composed letter and the letter with its accent behind it are
1561    /// the same string, and which of the two a form answers is the
1562    /// whole of what the two canonical forms disagree about.
1563    #[test]
1564    fn a_form_puts_an_accent_together_or_leaves_it_apart() {
1565        let mut arena = MorselArena::new();
1566        let v = str_vector(&mut arena, &["h\u{e9}llo", "he\u{301}llo", "plain"]);
1567        let together = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
1568        assert_eq!(together.phys, PhysType::Str);
1569        assert_eq!(read(&together), ["h\u{e9}llo", "h\u{e9}llo", "plain"]);
1570        let apart = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
1571        assert_eq!(read(&apart), ["he\u{301}llo", "he\u{301}llo", "plain"]);
1572    }
1573
1574    /// The compatibility forms answer something the canonical ones do
1575    /// not, and the answer is a different length from the argument,
1576    /// which is the case that rules out both the trim's trick and the
1577    /// fold's sizing.
1578    #[test]
1579    fn a_compatibility_form_answers_a_string_of_another_length() {
1580        let mut arena = MorselArena::new();
1581        let v = str_vector(&mut arena, &["o\u{fb01}ce"]);
1582        let canonical = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
1583        assert_eq!(read(&canonical), ["o\u{fb01}ce"]);
1584        let compat = normalize(&mut arena, NormalForm::Nfkc, &v).unwrap();
1585        assert_eq!(read(&compat), ["ofice"]);
1586        assert!("o\u{fb01}ce".len() > "ofice".len());
1587    }
1588
1589    /// The column nearly every query holds: plain strings, which are in
1590    /// all four forms already. The answers are the argument's own
1591    /// strings, so the vector holds the buffers it was handed and fills
1592    /// none of its own, and not a byte is copied.
1593    #[test]
1594    fn a_plain_column_is_answered_without_a_byte_being_copied() {
1595        let mut arena = MorselArena::new();
1596        let long = "a plain string well past the twelve bytes a view holds";
1597        let v = str_vector(&mut arena, &[long, "short"]);
1598        let out = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
1599        assert_eq!(read(&out), [long, "short"]);
1600        let (Aux::Str(theirs), Aux::Str(ours)) = (&v.aux, &out.aux) else {
1601            panic!("a chunk with a long string in it carries buffers");
1602        };
1603        assert!(Arc::ptr_eq(theirs, ours));
1604    }
1605
1606    /// An answer longer than a view holds lands in the builder's buffer
1607    /// and reads back through it, which is what a decomposition of a
1608    /// string that was already nearly too long asks for.
1609    #[test]
1610    fn a_long_answer_lands_in_a_buffer_of_its_own() {
1611        let mut arena = MorselArena::new();
1612        let v = str_vector(&mut arena, &["h\u{e9}llo th\u{e9}re"]);
1613        let out = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
1614        assert_eq!(read(&out), ["he\u{301}llo the\u{301}re"]);
1615        assert!(!out.values::<StrView>()[0].is_inline());
1616    }
1617
1618    /// One string standing for the chunk is normalized once, and every
1619    /// row reads the one answer back.
1620    #[test]
1621    fn a_constant_is_normalized_once() {
1622        let mut arena = MorselArena::new();
1623        let mut v = ValueVector::constant(
1624            &mut arena,
1625            PhysType::Str,
1626            StrView::inline("h\u{e9}llo".as_bytes()),
1627            3,
1628        );
1629        v.aux = Aux::None;
1630        let out = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
1631        assert_eq!(read(&out), ["he\u{301}llo"; 3]);
1632    }
1633
1634    /// Codes over a table normalize the table rather than the rows, and
1635    /// the answer still has to be what the same strings flat would have
1636    /// given.
1637    #[test]
1638    fn a_dictionary_is_normalized_a_table_at_a_time() {
1639        let mut arena = MorselArena::new();
1640        let entries = [
1641            "a\u{301} longer entry than a view holds",
1642            "bo",
1643            "h\u{e9}llo",
1644        ];
1645        let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
1646        let codes = [2u16, 0, 1, 0];
1647        let v = ValueVector::dict_str(&mut arena, &codes, dict);
1648        let out = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
1649        let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
1650        assert_eq!(
1651            read(&out),
1652            read(&normalize(&mut arena, NormalForm::Nfc, &flat).unwrap())
1653        );
1654        assert_eq!(read(&out)[0], "h\u{e9}llo");
1655        assert_eq!(read(&out)[1], "\u{e1} longer entry than a view holds");
1656    }
1657
1658    /// A null argument answers null, and the rows around it answer what
1659    /// they would have answered on their own.
1660    #[test]
1661    fn a_normalize_of_a_null_is_null() {
1662        let mut arena = MorselArena::new();
1663        let mut v = str_vector(&mut arena, &["he\u{301}llo", "bo", "cy"]);
1664        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1665        valid.clear(1);
1666        v.validity = Some(valid);
1667        let out = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
1668        assert!(!out.is_valid(1), "null in, null out");
1669        assert!(out.is_valid(0) && out.is_valid(2));
1670        assert_eq!(read(&out)[0], "h\u{e9}llo");
1671        assert_eq!(read(&out)[2], "cy");
1672    }
1673
1674    /// Reads a predicate back as the rows that passed.
1675    fn passed(bits: &Bitmap) -> Vec<usize> {
1676        (0..bits.len()).filter(|i| bits.get(*i)).collect()
1677    }
1678
1679    /// The test answers the rows that are in the form already, and the
1680    /// negated test answers the rows that are not, plain strings being
1681    /// in every form and so in neither answer's way.
1682    #[test]
1683    fn the_test_answers_the_rows_that_are_in_the_form() {
1684        let mut arena = MorselArena::new();
1685        let v = str_vector(&mut arena, &["h\u{e9}llo", "he\u{301}llo", "plain"]);
1686        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1687        normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
1688        assert_eq!(passed(&bits), [0, 2]);
1689        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1690        normalized(NormalForm::Nfc, true, &v, &mut bits).unwrap();
1691        assert_eq!(passed(&bits), [1]);
1692        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1693        normalized(NormalForm::Nfd, false, &v, &mut bits).unwrap();
1694        assert_eq!(passed(&bits), [1, 2]);
1695    }
1696
1697    /// The other two encodings answer what the same strings flat would
1698    /// have answered, a constant deciding the chunk in one test and a
1699    /// table deciding it in one test an entry.
1700    #[test]
1701    fn the_test_reads_a_constant_and_a_table_the_same_way() {
1702        let mut arena = MorselArena::new();
1703        let mut v = ValueVector::constant(
1704            &mut arena,
1705            PhysType::Str,
1706            StrView::inline("he\u{301}llo".as_bytes()),
1707            3,
1708        );
1709        v.aux = Aux::None;
1710        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1711        normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
1712        assert!(passed(&bits).is_empty());
1713        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1714        normalized(NormalForm::Nfd, false, &v, &mut bits).unwrap();
1715        assert_eq!(passed(&bits), [0, 1, 2]);
1716
1717        // Sorted the way a table on disk is sorted, which puts the
1718        // decomposed spelling first: its second byte is the plain
1719        // letter and the composed one's is the front of an accent.
1720        let entries = ["he\u{301}llo", "h\u{e9}llo", "plain"];
1721        let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
1722        let codes = [0u16, 1, 2, 0];
1723        let v = ValueVector::dict_str(&mut arena, &codes, dict);
1724        let mut bits = Bitmap::new_in(&mut arena, 4, false);
1725        normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
1726        let want: Vec<usize> = codes
1727            .iter()
1728            .enumerate()
1729            .filter(|(_, c)| entries[**c as usize] != "he\u{301}llo")
1730            .map(|(i, _)| i)
1731            .collect();
1732        assert_eq!(passed(&bits), want);
1733    }
1734
1735    /// A null is not normalized and is not unnormalized either, so it
1736    /// is missing from both answers. This is the reason the negation is
1737    /// carried into the kernel: a complement of the plain answer would
1738    /// have called this row unnormalized.
1739    #[test]
1740    fn a_null_is_in_neither_answer() {
1741        let mut arena = MorselArena::new();
1742        let mut v = str_vector(&mut arena, &["h\u{e9}llo", "he\u{301}llo", "cy"]);
1743        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1744        valid.clear(1);
1745        v.validity = Some(valid);
1746        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1747        normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
1748        assert_eq!(passed(&bits), [0, 2]);
1749        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1750        normalized(NormalForm::Nfc, true, &v, &mut bits).unwrap();
1751        assert!(passed(&bits).is_empty(), "the null row is in neither");
1752    }
1753
1754    /// Neither normalization has a row it cannot answer, and the two
1755    /// land in different places: a string for one, a truth value for
1756    /// the other.
1757    #[test]
1758    fn a_normalization_cannot_raise_and_the_two_answer_apart() {
1759        let into = StrNorm::Into(NormalForm::Nfkd);
1760        let test = StrNorm::Test(NormalForm::Nfkd);
1761        assert!(!into.may_raise() && !test.may_raise());
1762        assert_eq!(into.form(), NormalForm::Nfkd);
1763        assert_eq!(into.answer_type(PhysType::Str), Some(PhysType::Str));
1764        assert_eq!(test.answer_type(PhysType::Str), Some(PhysType::Bool));
1765        assert_eq!(into.answer_type(PhysType::Int64), None);
1766        assert_eq!(test.answer_type(PhysType::Float64), None);
1767    }
1768
1769    /// A number is not a string, and a kernel handed one says so
1770    /// rather than reading sixteen bytes of it as a view.
1771    #[test]
1772    fn a_number_is_not_a_string() {
1773        let mut arena = MorselArena::new();
1774        let v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2]);
1775        let Err(err) = length(&mut arena, StrLen::Chars, &v) else {
1776            panic!("a number was measured as a string");
1777        };
1778        assert!(err.to_string().contains("char_length"));
1779        let Err(err) = fold(&mut arena, StrFold::Upper, &v) else {
1780            panic!("a number was folded as a string");
1781        };
1782        assert!(err.to_string().contains("upper"));
1783        let Err(err) = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v) else {
1784            panic!("a number was trimmed as a string");
1785        };
1786        assert!(err.to_string().contains("trim"));
1787        let Err(err) = normalize(&mut arena, NormalForm::Nfc, &v) else {
1788            panic!("a number was normalized as a string");
1789        };
1790        assert!(err.to_string().contains("normalize"));
1791        let mut bits = Bitmap::new_in(&mut arena, 2, false);
1792        let Err(err) = normalized(NormalForm::Nfc, false, &v, &mut bits) else {
1793            panic!("a number was tested as a string");
1794        };
1795        assert!(err.to_string().contains("is_normalized"));
1796    }
1797
1798    /// A count that is the same for the whole chunk, which is what a
1799    /// statement writing the number out produces.
1800    fn same_count(arena: &mut MorselArena, n: i64, len: usize) -> ValueVector {
1801        ValueVector::constant(arena, PhysType::Int64, n, len)
1802    }
1803
1804    /// A count a row, which is what a column in the second argument
1805    /// produces.
1806    fn counts(arena: &mut MorselArena, vals: &[i64]) -> ValueVector {
1807        ValueVector::flat_from(arena, PhysType::Int64, vals)
1808    }
1809
1810    /// The two ends of the one walk, counted in characters rather than
1811    /// in bytes, so an accented letter and an emoji each count once and
1812    /// neither is cut in half.
1813    #[test]
1814    fn a_cut_counts_characters_and_not_bytes() {
1815        let mut arena = MorselArena::new();
1816        let v = str_vector(&mut arena, &["h\u{e9}llo", "\u{1f642}ab", "plain"]);
1817        let two = same_count(&mut arena, 2, 3);
1818        let left = cut(&mut arena, StrCut::Left, &v, &two, None).unwrap();
1819        assert_eq!(left.phys, PhysType::Str);
1820        assert_eq!(read(&left), ["h\u{e9}", "\u{1f642}a", "pl"]);
1821        let right = cut(&mut arena, StrCut::Right, &v, &two, None).unwrap();
1822        assert_eq!(read(&right), ["lo", "ab", "in"]);
1823    }
1824
1825    /// A cut asked for more characters than there are answers the whole
1826    /// string, and one asked for none answers the empty string, which
1827    /// are the two ends of the range and both of them are answers
1828    /// rather than conditions.
1829    #[test]
1830    fn the_ends_of_the_range_are_answers_and_not_conditions() {
1831        let mut arena = MorselArena::new();
1832        let v = str_vector(&mut arena, &["abc", "", "h\u{e9}llo"]);
1833        let plenty = same_count(&mut arena, 40, 3);
1834        let out = cut(&mut arena, StrCut::Left, &v, &plenty, None).unwrap();
1835        assert_eq!(read(&out), ["abc", "", "h\u{e9}llo"]);
1836        let none = same_count(&mut arena, 0, 3);
1837        let out = cut(&mut arena, StrCut::Right, &v, &none, None).unwrap();
1838        assert_eq!(read(&out), ["", "", ""]);
1839    }
1840
1841    /// The trim's trick again: a part of a string is bytes that are
1842    /// already in a buffer somebody is holding, so a flat column is cut
1843    /// without a byte being copied and the answer holds the argument's
1844    /// own buffers.
1845    #[test]
1846    fn a_plain_column_is_cut_without_a_byte_being_copied() {
1847        let mut arena = MorselArena::new();
1848        let long = "a plain string well past the twelve bytes a view holds";
1849        let v = str_vector(&mut arena, &[long, "short"]);
1850        let count = same_count(&mut arena, 30, 2);
1851        let out = cut(&mut arena, StrCut::Right, &v, &count, None).unwrap();
1852        assert_eq!(read(&out), [&long[long.len() - 30..], "short"]);
1853        let (Aux::Str(theirs), Aux::Str(ours)) = (&v.aux, &out.aux) else {
1854            panic!("a chunk with a long string in it carries buffers");
1855        };
1856        assert!(Arc::ptr_eq(theirs, ours));
1857    }
1858
1859    /// One string standing for the chunk is cut once where the count is
1860    /// one number, and a row at a time where the count is a column,
1861    /// since two rows over one string no longer answer the same thing.
1862    #[test]
1863    fn a_constant_is_cut_once_or_a_row_at_a_time() {
1864        let mut arena = MorselArena::new();
1865        let mut v = ValueVector::constant(
1866            &mut arena,
1867            PhysType::Str,
1868            StrView::inline("h\u{e9}llo".as_bytes()),
1869            3,
1870        );
1871        v.aux = Aux::None;
1872        let two = same_count(&mut arena, 2, 3);
1873        let out = cut(&mut arena, StrCut::Left, &v, &two, None).unwrap();
1874        assert_eq!(read(&out), ["h\u{e9}", "h\u{e9}", "h\u{e9}"]);
1875        let varying = counts(&mut arena, &[1, 3, 5]);
1876        let out = cut(&mut arena, StrCut::Left, &v, &varying, None).unwrap();
1877        assert_eq!(read(&out), ["h", "h\u{e9}l", "h\u{e9}llo"]);
1878    }
1879
1880    /// A dictionary is the one shape that has to write, an entry of a
1881    /// table not being bytes a view can name. One count cuts the table
1882    /// once and the rows gather over the answers; a count a row cuts a
1883    /// row at a time. Both have to answer what the same strings flat
1884    /// would have answered.
1885    #[test]
1886    fn a_dictionary_is_cut_a_table_at_a_time_or_a_row_at_a_time() {
1887        let mut arena = MorselArena::new();
1888        let entries = ["a longer entry than a view holds", "bo", "h\u{e9}llo"];
1889        let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
1890        let codes = [2u16, 0, 1, 0];
1891        let v = ValueVector::dict_str(&mut arena, &codes, dict);
1892        let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
1893        let four = same_count(&mut arena, 4, 4);
1894        let out = cut(&mut arena, StrCut::Left, &v, &four, None).unwrap();
1895        assert_eq!(
1896            read(&out),
1897            read(&cut(&mut arena, StrCut::Left, &flat, &four, None).unwrap())
1898        );
1899        assert_eq!(read(&out)[0], "h\u{e9}ll");
1900        let varying = counts(&mut arena, &[1, 2, 2, 40]);
1901        let out = cut(&mut arena, StrCut::Right, &v, &varying, None).unwrap();
1902        assert_eq!(
1903            read(&out),
1904            read(&cut(&mut arena, StrCut::Right, &flat, &varying, None).unwrap())
1905        );
1906        assert_eq!(read(&out)[3], "a longer entry than a view holds");
1907    }
1908
1909    /// Either argument being null makes the answer null, which is two
1910    /// columns' worth of validity rather than one.
1911    #[test]
1912    fn a_null_on_either_side_answers_null() {
1913        let mut arena = MorselArena::new();
1914        let mut v = str_vector(&mut arena, &["abc", "def", "ghi"]);
1915        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1916        valid.clear(0);
1917        v.validity = Some(valid);
1918        let mut n = counts(&mut arena, &[2, 2, 2]);
1919        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1920        valid.clear(1);
1921        n.validity = Some(valid);
1922        let out = cut(&mut arena, StrCut::Left, &v, &n, None).unwrap();
1923        assert!(!out.is_valid(0), "a null string answers null");
1924        assert!(!out.is_valid(1), "a null count answers null");
1925        assert!(out.is_valid(2));
1926        assert_eq!(read(&out)[2], "gh");
1927    }
1928
1929    /// A string has no negative number of characters, and the condition
1930    /// the standard gives that is the row engine's, in the row engine's
1931    /// words, so a statement cannot tell which engine answered it.
1932    #[test]
1933    fn a_negative_count_raises_the_standards_condition() {
1934        let mut arena = MorselArena::new();
1935        let v = str_vector(&mut arena, &["abc", "def"]);
1936        let n = counts(&mut arena, &[1, -2]);
1937        let Err(err) = cut(&mut arena, StrCut::Right, &v, &n, None) else {
1938            panic!("a negative count was answered");
1939        };
1940        assert_eq!(err.gqlstatus().map(|s| s.to_string()), Some("22011".into()));
1941        assert!(err.to_string().contains("right()"), "{err}");
1942        assert!(err.to_string().contains("-2"), "{err}");
1943    }
1944
1945    /// The rows the condition is raised over are the rows the row
1946    /// engine evaluated: a row nobody selected is not one of them, and
1947    /// neither is a row whose string is null, since a null answers null
1948    /// before the count is looked at.
1949    #[test]
1950    fn a_row_that_was_never_evaluated_raises_nothing() {
1951        let mut arena = MorselArena::new();
1952        let mut v = str_vector(&mut arena, &["abc", "def", "ghi"]);
1953        let mut valid = Bitmap::new_in(&mut arena, 3, true);
1954        valid.clear(1);
1955        v.validity = Some(valid);
1956        let n = counts(&mut arena, &[3, -1, -1]);
1957        let mut bits = Bitmap::new_in(&mut arena, 3, false);
1958        bits.set(0);
1959        bits.set(1);
1960        let sel = SelVector::from_bitmap(&mut arena, &bits);
1961        let out = cut(&mut arena, StrCut::Left, &v, &n, Some(&sel)).unwrap();
1962        assert_eq!(read(&out)[0], "abc");
1963        let Err(err) = cut(&mut arena, StrCut::Left, &v, &n, None) else {
1964            panic!("the unselected row's count was never looked at");
1965        };
1966        assert!(err.to_string().contains("left()"), "{err}");
1967    }
1968
1969    /// A cut says it can raise, which is what keeps it out of a
1970    /// projection unless the compiler settled the count. A number is
1971    /// not a string here either, and neither is a string a count.
1972    #[test]
1973    fn a_cut_can_raise_and_wants_a_string_and_a_number() {
1974        assert!(StrCut::Left.may_raise() && StrCut::Right.may_raise());
1975        assert_eq!(
1976            StrCut::Left.answer_type(PhysType::Str, PhysType::Int64),
1977            Some(PhysType::Str)
1978        );
1979        assert!(
1980            StrCut::Left
1981                .answer_type(PhysType::Str, PhysType::Float64)
1982                .is_none()
1983        );
1984        let mut arena = MorselArena::new();
1985        let v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2]);
1986        let n = counts(&mut arena, &[1, 1]);
1987        let Err(err) = cut(&mut arena, StrCut::Left, &v, &n, None) else {
1988            panic!("a number was cut as a string");
1989        };
1990        assert!(err.to_string().contains("left()"), "{err}");
1991    }
1992
1993    /// An identifier is the head the chunk shares and the row itself,
1994    /// and the rows a graph really holds are counted from nought, so
1995    /// the digits are the whole of what varies.
1996    #[test]
1997    fn an_identifier_is_the_table_and_the_row() {
1998        let mut arena = MorselArena::new();
1999        let rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[0i64, 7, 1234567]);
2000        let ids = element_ids(&mut arena, 3, &rows).unwrap();
2001        assert_eq!(ids.phys, PhysType::Str);
2002        assert_eq!(read(&ids), vec!["n:3:0", "n:3:7", "n:3:1234567"]);
2003    }
2004
2005    /// The row engine writes the same two numbers with the same
2006    /// punctuation, and the two engines answering one query differently
2007    /// is the failure this kernel exists to not have.
2008    #[test]
2009    fn an_identifier_is_what_the_row_engine_writes() {
2010        let mut arena = MorselArena::new();
2011        for (table, row) in [(0u32, 0i64), (1, 2), (10, 99), (u32::MAX, 4_294_967_296)] {
2012            let rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[row]);
2013            let ids = element_ids(&mut arena, table, &rows).unwrap();
2014            assert_eq!(read(&ids), vec![format!("n:{table}:{row}")]);
2015        }
2016    }
2017
2018    /// A row past the twelve bytes a view holds is written into the
2019    /// buffer behind it, and the answer reads back the same either way.
2020    #[test]
2021    fn an_identifier_too_long_to_sit_inline_goes_to_the_buffer() {
2022        let mut arena = MorselArena::new();
2023        let rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[5i64, 9_876_543_210_123]);
2024        let ids = element_ids(&mut arena, 65535, &rows).unwrap();
2025        let views = ids.values::<StrView>();
2026        assert!(views[0].is_inline(), "a short identifier stays in the view");
2027        assert!(!views[1].is_inline(), "a long one does not");
2028        assert_eq!(
2029            read(&ids),
2030            vec!["n:65535:5", "n:65535:9876543210123"],
2031            "and both read back the same"
2032        );
2033    }
2034
2035    /// One row standing for the chunk is written once.
2036    #[test]
2037    fn a_constant_row_is_written_once() {
2038        let mut arena = MorselArena::new();
2039        let rows = ValueVector::constant(&mut arena, PhysType::Int64, 12i64, 4);
2040        let ids = element_ids(&mut arena, 0, &rows).unwrap();
2041        assert_eq!(read(&ids), vec!["n:0:12"; 4]);
2042    }
2043
2044    /// A node that is not there has no identifier, which is the row an
2045    /// optional match left behind.
2046    #[test]
2047    fn a_null_row_has_no_identifier() {
2048        let mut arena = MorselArena::new();
2049        let mut rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 0, 3]);
2050        let mut valid = Bitmap::new_in(&mut arena, 3, true);
2051        valid.clear(1);
2052        rows.validity = Some(valid);
2053        let ids = element_ids(&mut arena, 2, &rows).unwrap();
2054        let valid = ids.validity.as_ref().expect("the answer carries validity");
2055        assert!(valid.get(0) && !valid.get(1) && valid.get(2));
2056    }
2057
2058    /// The two numbers a node is made of are numbers, so a column of
2059    /// anything else is not a chunk of nodes and is refused rather than
2060    /// read as one.
2061    #[test]
2062    fn identifiers_want_a_column_of_rows() {
2063        let mut arena = MorselArena::new();
2064        let v = str_vector(&mut arena, &["ann"]);
2065        let Err(err) = element_ids(&mut arena, 0, &v) else {
2066            panic!("a column of strings was read as rows");
2067        };
2068        assert!(err.to_string().contains("ELEMENT_ID()"), "{err}");
2069    }
2070}