use std::sync::Arc;
use zu_common::unicode::{self, NormalForm};
use zu_common::{Result, ZuError, gqlstatus::codes};
use crate::arena::MorselArena;
use crate::bitmap::Bitmap;
use crate::sel::SelVector;
use crate::str::{INLINE_LEN, NO_BUFFERS, StrBuffers, StrBuilder, StrView};
use crate::vector::{Aux, PhysType, ValueVector, VecEncoding};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StrLen {
Chars,
Octets,
}
impl StrLen {
fn name(self) -> &'static str {
match self {
StrLen::Chars => "char_length",
StrLen::Octets => "octet_length",
}
}
pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
match arg {
PhysType::Str => Some(PhysType::Int64),
_ => None,
}
}
pub fn may_raise(self) -> bool {
false
}
}
#[inline(always)]
fn measure(op: StrLen, bytes: &[u8]) -> i64 {
match op {
StrLen::Octets => bytes.len() as i64,
StrLen::Chars => bytes.iter().filter(|b| (**b as i8) >= -0x40).count() as i64,
}
}
pub fn length(arena: &mut MorselArena, op: StrLen, v: &ValueVector) -> Result<ValueVector> {
if op.answer_type(v.phys).is_none() {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?}",
op.name(),
v.phys
)));
}
let len = v.len as usize;
let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
let mut out = ValueVector::flat_uninit(arena, PhysType::Int64, len);
match v.encoding {
VecEncoding::Constant => {
let view = v.constant_value::<StrView>();
let n = measure(op, view.bytes(bufs));
out.values_mut::<i64>()[..len].fill(n);
}
VecEncoding::Dict { .. } => {
let dict = v.dictionary();
let table: Vec<i64> = (0..dict.len())
.map(|i| measure(op, dict.get(i as u32)))
.collect();
let codes = v.codes_u16();
let dst = out.values_mut::<i64>();
for (slot, code) in dst[..len].iter_mut().zip(codes) {
*slot = table[*code as usize];
}
}
VecEncoding::Flat => {
let views = v.values::<StrView>();
let dst = out.values_mut::<i64>();
match op {
StrLen::Octets => {
for (slot, view) in dst[..len].iter_mut().zip(views) {
*slot = view.len() as i64;
}
}
StrLen::Chars => {
for (slot, view) in dst[..len].iter_mut().zip(views) {
*slot = measure(op, view.bytes(bufs));
}
}
}
}
}
out.validity = carried(arena, v, len);
Ok(out)
}
fn carried(arena: &mut MorselArena, v: &ValueVector, len: usize) -> Option<Bitmap> {
v.validity.as_ref().map(|valid| {
let mut copy = Bitmap::new_in(arena, len, true);
copy.and_with(valid);
copy
})
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StrFold {
Upper,
Lower,
}
impl StrFold {
fn name(self) -> &'static str {
match self {
StrFold::Upper => "upper",
StrFold::Lower => "lower",
}
}
pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
match arg {
PhysType::Str => Some(PhysType::Str),
_ => None,
}
}
pub fn may_raise(self) -> bool {
false
}
}
fn long_bytes(v: &ValueVector) -> usize {
let outside = |n: usize| if n > INLINE_LEN { n } else { 0 };
match v.encoding {
VecEncoding::Constant => outside(v.constant_value::<StrView>().len()),
VecEncoding::Dict { .. } => {
let dict = v.dictionary();
(0..dict.len())
.map(|i| outside(dict.get(i as u32).len()))
.sum()
}
VecEncoding::Flat => v
.values::<StrView>()
.iter()
.map(|view| outside(view.len()))
.sum(),
}
}
#[inline(always)]
fn fold_into(op: StrFold, src: &[u8], dst: &mut [u8]) {
dst.copy_from_slice(src);
match op {
StrFold::Upper => dst.make_ascii_uppercase(),
StrFold::Lower => dst.make_ascii_lowercase(),
}
}
pub fn fold(arena: &mut MorselArena, op: StrFold, v: &ValueVector) -> Result<ValueVector> {
if op.answer_type(v.phys).is_none() {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?}",
op.name(),
v.phys
)));
}
let len = v.len as usize;
let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
let mut build = StrBuilder::with_capacity(long_bytes(v));
match v.encoding {
VecEncoding::Constant => {
let view = v.constant_value::<StrView>();
let bytes = view.bytes(bufs);
let one = build.push_with(bytes.len(), |dst| fold_into(op, bytes, dst));
out.values_mut::<StrView>()[..len].fill(one);
}
VecEncoding::Dict { .. } => {
let dict = v.dictionary();
let table: Vec<StrView> = (0..dict.len())
.map(|i| {
let entry = dict.get(i as u32);
build.push_with(entry.len(), |dst| fold_into(op, entry, dst))
})
.collect();
let codes = v.codes_u16();
let dst = out.values_mut::<StrView>();
for (slot, code) in dst[..len].iter_mut().zip(codes) {
*slot = table[*code as usize];
}
}
VecEncoding::Flat => {
let views = v.values::<StrView>();
let dst = out.values_mut::<StrView>();
for (slot, view) in dst[..len].iter_mut().zip(views) {
let bytes = view.bytes(bufs);
*slot = build.push_with(bytes.len(), |room| fold_into(op, bytes, room));
}
}
}
out.aux = Aux::Str(Arc::new(build.finish()));
out.validity = carried(arena, v, len);
Ok(out)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StrTrim {
Both,
Leading,
Trailing,
}
impl StrTrim {
fn name(self) -> &'static str {
match self {
StrTrim::Both => "trim",
StrTrim::Leading => "ltrim",
StrTrim::Trailing => "rtrim",
}
}
fn front(self) -> bool {
matches!(self, StrTrim::Both | StrTrim::Leading)
}
fn back(self) -> bool {
matches!(self, StrTrim::Both | StrTrim::Trailing)
}
pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
match arg {
PhysType::Str => Some(PhysType::Str),
_ => None,
}
}
pub fn may_raise(self) -> bool {
false
}
}
#[derive(Debug, Default)]
pub struct TrimSet {
ascii: u128,
wide: Vec<Box<[u8]>>,
}
impl TrimSet {
pub fn new(chars: &str) -> Self {
let mut set = Self::default();
for c in chars.chars() {
if c.is_ascii() {
set.ascii |= 1u128 << (c as u8);
} else {
let mut buf = [0u8; 4];
let bytes = c.encode_utf8(&mut buf).as_bytes();
if !set.wide.iter().any(|w| &**w == bytes) {
set.wide.push(bytes.into());
}
}
}
set
}
pub fn is_empty(&self) -> bool {
self.ascii == 0 && self.wide.is_empty()
}
#[inline(always)]
fn width_at(&self, bytes: &[u8]) -> Option<usize> {
let head = bytes[0];
if head < 0x80 {
return ((self.ascii >> head) & 1 == 1).then_some(1);
}
self.wide
.iter()
.find(|w| bytes.starts_with(w))
.map(|w| w.len())
}
#[inline(always)]
fn width_before(&self, bytes: &[u8]) -> Option<usize> {
let last = bytes[bytes.len() - 1];
if last < 0x80 {
return ((self.ascii >> last) & 1 == 1).then_some(1);
}
self.wide
.iter()
.find(|w| bytes.ends_with(w))
.map(|w| w.len())
}
}
#[inline(always)]
fn kept(ends: StrTrim, set: &TrimSet, bytes: &[u8]) -> (usize, usize) {
let mut start = 0;
let mut end = bytes.len();
if ends.front() {
while start < end {
match set.width_at(&bytes[start..end]) {
Some(n) => start += n,
None => break,
}
}
}
if ends.back() {
while start < end {
match set.width_before(&bytes[start..end]) {
Some(n) => end -= n,
None => break,
}
}
}
(start, end - start)
}
pub fn trim(
arena: &mut MorselArena,
ends: StrTrim,
set: &TrimSet,
v: &ValueVector,
) -> Result<ValueVector> {
if ends.answer_type(v.phys).is_none() {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?}",
ends.name(),
v.phys
)));
}
let len = v.len as usize;
let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
let mut made = None;
match v.encoding {
VecEncoding::Constant => {
let view = v.constant_value::<StrView>();
let bytes = view.bytes(bufs);
let (at, n) = kept(ends, set, bytes);
out.values_mut::<StrView>()[..len].fill(view.sub(bytes, at, n));
}
VecEncoding::Dict { .. } => {
let dict = v.dictionary();
let mut build = StrBuilder::with_capacity(long_bytes(v));
let table: Vec<StrView> = (0..dict.len())
.map(|i| {
let entry = dict.get(i as u32);
let (at, n) = kept(ends, set, entry);
build.push(&entry[at..at + n])
})
.collect();
let codes = v.codes_u16();
let dst = out.values_mut::<StrView>();
for (slot, code) in dst[..len].iter_mut().zip(codes) {
*slot = table[*code as usize];
}
made = Some(build.finish());
}
VecEncoding::Flat => {
let views = v.values::<StrView>();
let dst = out.values_mut::<StrView>();
for (slot, view) in dst[..len].iter_mut().zip(views) {
let bytes = view.bytes(bufs);
let (at, n) = kept(ends, set, bytes);
*slot = view.sub(bytes, at, n);
}
}
}
out.aux = match made {
Some(bufs) => Aux::Str(Arc::new(bufs)),
None => match &v.aux {
Aux::Str(bufs) => Aux::Str(Arc::clone(bufs)),
_ => Aux::None,
},
};
out.validity = carried(arena, v, len);
Ok(out)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StrNorm {
Into(NormalForm),
Test(NormalForm),
}
impl StrNorm {
fn name(self) -> &'static str {
match self {
StrNorm::Into(_) => "normalize",
StrNorm::Test(_) => "is_normalized",
}
}
pub fn form(self) -> NormalForm {
match self {
StrNorm::Into(form) | StrNorm::Test(form) => form,
}
}
pub fn answer_type(self, arg: PhysType) -> Option<PhysType> {
match (self, arg) {
(StrNorm::Into(_), PhysType::Str) => Some(PhysType::Str),
(StrNorm::Test(_), PhysType::Str) => Some(PhysType::Bool),
_ => None,
}
}
pub fn may_raise(self) -> bool {
false
}
}
fn all_ascii(v: &ValueVector, bufs: &StrBuffers) -> bool {
match v.encoding {
VecEncoding::Constant => v.constant_value::<StrView>().bytes(bufs).is_ascii(),
VecEncoding::Dict { .. } => false,
VecEncoding::Flat => v
.values::<StrView>()
.iter()
.all(|view| view.bytes(bufs).is_ascii()),
}
}
#[inline]
fn put(build: &mut StrBuilder, form: NormalForm, bytes: &[u8]) -> StrView {
if bytes.is_ascii() {
return build.push(bytes);
}
match std::str::from_utf8(bytes) {
Ok(s) => build.push(unicode::normalize(s, form).as_bytes()),
Err(_) => build.push(bytes),
}
}
pub fn normalize(
arena: &mut MorselArena,
form: NormalForm,
v: &ValueVector,
) -> Result<ValueVector> {
let op = StrNorm::Into(form);
if op.answer_type(v.phys).is_none() {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?}",
op.name(),
v.phys
)));
}
let len = v.len as usize;
let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
if all_ascii(v, bufs) {
let dst = out.values_mut::<StrView>();
match v.encoding {
VecEncoding::Constant => dst[..len].fill(v.constant_value::<StrView>()),
_ => {
for (slot, view) in dst[..len].iter_mut().zip(v.values::<StrView>()) {
*slot = *view;
}
}
}
out.aux = match &v.aux {
Aux::Str(bufs) => Aux::Str(Arc::clone(bufs)),
_ => Aux::None,
};
} else {
let mut build = StrBuilder::with_capacity(long_bytes(v));
match v.encoding {
VecEncoding::Constant => {
let view = v.constant_value::<StrView>();
let one = put(&mut build, form, view.bytes(bufs));
out.values_mut::<StrView>()[..len].fill(one);
}
VecEncoding::Dict { .. } => {
let dict = v.dictionary();
let table: Vec<StrView> = (0..dict.len())
.map(|i| put(&mut build, form, dict.get(i as u32)))
.collect();
let codes = v.codes_u16();
let dst = out.values_mut::<StrView>();
for (slot, code) in dst[..len].iter_mut().zip(codes) {
*slot = table[*code as usize];
}
}
VecEncoding::Flat => {
let views = v.values::<StrView>();
let dst = out.values_mut::<StrView>();
for (slot, view) in dst[..len].iter_mut().zip(views) {
*slot = put(&mut build, form, view.bytes(bufs));
}
}
}
out.aux = Aux::Str(Arc::new(build.finish()));
}
out.validity = carried(arena, v, len);
Ok(out)
}
pub fn normalized(
form: NormalForm,
negated: bool,
v: &ValueVector,
out: &mut Bitmap,
) -> Result<()> {
let op = StrNorm::Test(form);
debug_assert_eq!(out.len(), v.len as usize);
if op.answer_type(v.phys).is_none() {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?}",
op.name(),
v.phys
)));
}
let len = v.len as usize;
let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
let holds = |bytes: &[u8]| match std::str::from_utf8(bytes) {
Ok(s) => unicode::is_normalized(s, form),
Err(_) => true,
};
match v.encoding {
VecEncoding::Constant => {
if holds(v.constant_value::<StrView>().bytes(bufs)) != negated {
out.words_mut().fill(!0u64);
}
}
VecEncoding::Dict { .. } => {
let dict = v.dictionary();
let table: Vec<bool> = (0..dict.len())
.map(|i| holds(dict.get(i as u32)) != negated)
.collect();
for (row, code) in v.codes_u16()[..len].iter().enumerate() {
if table[*code as usize] {
out.set(row);
}
}
}
VecEncoding::Flat => {
for (row, view) in v.values::<StrView>()[..len].iter().enumerate() {
if holds(view.bytes(bufs)) != negated {
out.set(row);
}
}
}
}
if let Some(valid) = &v.validity {
out.and_with(valid);
}
out.mask_tail();
Ok(())
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StrCut {
Left,
Right,
}
impl StrCut {
fn name(self) -> &'static str {
match self {
StrCut::Left => "left",
StrCut::Right => "right",
}
}
pub fn answer_type(self, arg: PhysType, count: PhysType) -> Option<PhysType> {
match (arg, count) {
(PhysType::Str, PhysType::Int64) => Some(PhysType::Str),
_ => None,
}
}
pub fn may_raise(self) -> bool {
true
}
}
#[inline(always)]
fn prefix_end(bytes: &[u8], count: usize) -> usize {
let mut at = 0;
for _ in 0..count {
if at == bytes.len() {
break;
}
at += 1;
while at < bytes.len() && bytes[at] & 0xC0 == 0x80 {
at += 1;
}
}
at
}
#[inline(always)]
fn suffix_start(bytes: &[u8], count: usize) -> usize {
let mut at = bytes.len();
for _ in 0..count {
if at == 0 {
break;
}
at -= 1;
while at > 0 && bytes[at] & 0xC0 == 0x80 {
at -= 1;
}
}
at
}
#[inline(always)]
fn taken(cut: StrCut, bytes: &[u8], count: usize) -> (usize, usize) {
match cut {
StrCut::Left => (0, prefix_end(bytes, count)),
StrCut::Right => {
let at = suffix_start(bytes, count);
(at, bytes.len() - at)
}
}
}
#[inline(always)]
fn count_at(n: &ValueVector, row: usize) -> usize {
let c = match n.encoding {
VecEncoding::Constant => n.constant_value::<i64>(),
_ => n.values::<i64>()[row],
};
c.max(0) as usize
}
fn check_counts(
cut: StrCut,
s: &ValueVector,
n: &ValueVector,
sel: Option<&SelVector>,
len: usize,
) -> Result<()> {
let lowest = match n.encoding {
VecEncoding::Constant => n.constant_value::<i64>(),
_ => n.values::<i64>()[..len].iter().copied().min().unwrap_or(0),
};
if lowest >= 0 {
return Ok(());
}
let visit = |row: usize| -> Result<()> {
if !s.is_valid(row) || !n.is_valid(row) {
return Ok(());
}
let asked = match n.encoding {
VecEncoding::Constant => n.constant_value::<i64>(),
_ => n.values::<i64>()[row],
};
if asked < 0 {
return Err(ZuError::gql(
codes::C22011,
format!(
"{}() was asked for {asked} characters, and a string has no negative number of them",
cut.name()
),
));
}
Ok(())
};
match sel {
Some(sel) => {
for &row in sel.as_slice() {
visit(row as usize)?;
}
}
None => {
for row in 0..len {
visit(row)?;
}
}
}
Ok(())
}
pub fn cut(
arena: &mut MorselArena,
cut: StrCut,
s: &ValueVector,
n: &ValueVector,
sel: Option<&SelVector>,
) -> Result<ValueVector> {
debug_assert_eq!(s.len, n.len);
if cut.answer_type(s.phys, n.phys).is_none() {
return Err(ZuError::InvalidArgument(format!(
"no {}() kernel for {:?} and {:?}",
cut.name(),
s.phys,
n.phys
)));
}
if matches!(n.encoding, VecEncoding::Dict { .. }) {
return Err(ZuError::InvalidArgument(
"substring counts on dict vectors: materialize first".into(),
));
}
let len = s.len as usize;
check_counts(cut, s, n, sel, len)?;
let one_count = matches!(n.encoding, VecEncoding::Constant);
let bufs = s.str_buffers().unwrap_or(&NO_BUFFERS);
let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
let mut made = None;
match s.encoding {
VecEncoding::Constant => {
let view = s.constant_value::<StrView>();
let bytes = view.bytes(bufs);
let dst = out.values_mut::<StrView>();
if one_count {
let (at, took) = taken(cut, bytes, count_at(n, 0));
dst[..len].fill(view.sub(bytes, at, took));
} else {
for (row, slot) in dst[..len].iter_mut().enumerate() {
let (at, took) = taken(cut, bytes, count_at(n, row));
*slot = view.sub(bytes, at, took);
}
}
}
VecEncoding::Dict { .. } => {
let dict = s.dictionary();
let codes = s.codes_u16();
let mut build = StrBuilder::with_capacity(long_bytes(s));
let dst = out.values_mut::<StrView>();
if one_count {
let count = count_at(n, 0);
let table: Vec<StrView> = (0..dict.len())
.map(|i| {
let entry = dict.get(i as u32);
let (at, took) = taken(cut, entry, count);
build.push(&entry[at..at + took])
})
.collect();
for (slot, code) in dst[..len].iter_mut().zip(codes) {
*slot = table[*code as usize];
}
} else {
for (row, slot) in dst[..len].iter_mut().enumerate() {
let entry = dict.get(codes[row] as u32);
let (at, took) = taken(cut, entry, count_at(n, row));
*slot = build.push(&entry[at..at + took]);
}
}
made = Some(build.finish());
}
VecEncoding::Flat => {
let views = s.values::<StrView>();
let dst = out.values_mut::<StrView>();
for (row, (slot, view)) in dst[..len].iter_mut().zip(views).enumerate() {
let bytes = view.bytes(bufs);
let (at, took) = taken(cut, bytes, count_at(n, row));
*slot = view.sub(bytes, at, took);
}
}
}
out.aux = match made {
Some(bufs) => Aux::Str(Arc::new(bufs)),
None => match &s.aux {
Aux::Str(bufs) => Aux::Str(Arc::clone(bufs)),
_ => Aux::None,
},
};
out.validity = match (&s.validity, &n.validity) {
(None, None) => None,
(left, right) => {
let mut copy = Bitmap::new_in(arena, len, true);
if let Some(valid) = left {
copy.and_with(valid);
}
if let Some(valid) = right {
copy.and_with(valid);
}
Some(copy)
}
};
Ok(out)
}
const DIGITS: usize = 21;
fn written(n: i64, buf: &mut [u8; DIGITS]) -> &[u8] {
let mut at = buf.len();
let mut left = n.unsigned_abs();
loop {
at -= 1;
buf[at] = b'0' + (left % 10) as u8;
left /= 10;
if left == 0 {
break;
}
}
if n < 0 {
at -= 1;
buf[at] = b'-';
}
&buf[at..]
}
pub fn element_ids(arena: &mut MorselArena, table: u32, rows: &ValueVector) -> Result<ValueVector> {
if !matches!(rows.phys, PhysType::Int64) {
return Err(ZuError::InvalidArgument(format!(
"no ELEMENT_ID() kernel for {:?}",
rows.phys
)));
}
if matches!(rows.encoding, VecEncoding::Dict { .. }) {
return Err(ZuError::InvalidArgument(
"element identifiers over a dict vector: materialize first".into(),
));
}
let len = rows.len as usize;
let mut digits = [0u8; DIGITS];
let table = written(i64::from(table), &mut digits);
let mut buf = [0u8; 13];
buf[0] = b'n';
buf[1] = b':';
buf[2..2 + table.len()].copy_from_slice(table);
buf[2 + table.len()] = b':';
let head = &buf[..3 + table.len()];
let mut out = ValueVector::flat_uninit(arena, PhysType::Str, len);
let mut build = StrBuilder::new();
let mut row_digits = [0u8; DIGITS];
let one = |build: &mut StrBuilder, row: i64, room: &mut [u8; DIGITS]| {
let tail = written(row, room);
build.push_with(head.len() + tail.len(), |dst| {
dst[..head.len()].copy_from_slice(head);
dst[head.len()..].copy_from_slice(tail);
})
};
match rows.encoding {
VecEncoding::Constant => {
let view = one(&mut build, rows.constant_value::<i64>(), &mut row_digits);
out.values_mut::<StrView>()[..len].fill(view);
}
_ => {
let vals = rows.values::<i64>();
let dst = out.values_mut::<StrView>();
for (slot, &row) in dst[..len].iter_mut().zip(vals) {
*slot = one(&mut build, row, &mut row_digits);
}
}
}
out.aux = Aux::Str(Arc::new(build.finish()));
out.validity = carried(arena, rows, len);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::str::Dictionary;
use crate::vector::{Aux, str_vector};
use std::sync::Arc;
#[test]
fn the_two_lengths_part_company_outside_ascii() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["", "abc", "héllo", "🙂", "a\tb"]);
let chars = length(&mut arena, StrLen::Chars, &v).unwrap();
assert_eq!(chars.phys, PhysType::Int64);
assert_eq!(chars.values::<i64>(), &[0, 3, 5, 1, 3]);
let octets = length(&mut arena, StrLen::Octets, &v).unwrap();
assert_eq!(octets.values::<i64>(), &[0, 3, 6, 4, 3]);
}
#[test]
fn a_string_too_long_to_sit_inline_is_measured_through_its_buffer() {
let mut arena = MorselArena::new();
let long = "a string well past the twelve bytes a view holds";
let v = str_vector(&mut arena, &["short", long]);
let chars = length(&mut arena, StrLen::Chars, &v).unwrap();
assert_eq!(chars.values::<i64>(), &[5, long.chars().count() as i64]);
let octets = length(&mut arena, StrLen::Octets, &v).unwrap();
assert_eq!(octets.values::<i64>(), &[5, long.len() as i64]);
}
#[test]
fn a_constant_is_measured_once() {
let mut arena = MorselArena::new();
let mut v = ValueVector::constant(
&mut arena,
PhysType::Str,
StrView::inline("héllo".as_bytes()),
4,
);
v.aux = Aux::None;
let out = length(&mut arena, StrLen::Chars, &v).unwrap();
assert_eq!(out.values::<i64>(), &[5, 5, 5, 5]);
}
#[test]
fn a_dictionary_is_measured_a_table_at_a_time() {
let mut arena = MorselArena::new();
let entries = ["", "a", "héllo", "🙂"];
let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
let codes = [3u16, 0, 2, 1, 2];
let v = ValueVector::dict_str(&mut arena, &codes, dict);
let chars = length(&mut arena, StrLen::Chars, &v).unwrap();
assert_eq!(chars.values::<i64>(), &[1, 0, 5, 1, 5]);
let octets = length(&mut arena, StrLen::Octets, &v).unwrap();
assert_eq!(octets.values::<i64>(), &[4, 0, 6, 1, 6]);
}
#[test]
fn a_null_argument_answers_null_and_not_nought() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &["ab", "", "cde"]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let out = length(&mut arena, StrLen::Chars, &v).unwrap();
assert!(!out.is_valid(1), "null in, null out");
assert!(out.is_valid(0) && out.is_valid(2));
assert_eq!(out.values::<i64>()[0], 2);
assert_eq!(out.values::<i64>()[2], 3);
}
#[test]
fn a_length_cannot_raise_and_answers_a_whole_number() {
assert!(!StrLen::Chars.may_raise());
assert!(!StrLen::Octets.may_raise());
assert_eq!(
StrLen::Chars.answer_type(PhysType::Str),
Some(PhysType::Int64)
);
assert_eq!(StrLen::Octets.answer_type(PhysType::Int64), None);
}
fn read(v: &ValueVector) -> Vec<String> {
let bufs = v.str_buffers().unwrap_or(&NO_BUFFERS);
v.values::<StrView>()
.iter()
.map(|view| String::from_utf8(view.bytes(bufs).to_vec()).unwrap())
.collect()
}
#[test]
fn a_fold_moves_the_english_letters_and_nothing_else() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["Ann", "bo", "", "héllo", "🙂 x9"]);
let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
assert_eq!(up.phys, PhysType::Str);
assert_eq!(read(&up), ["ANN", "BO", "", "HéLLO", "🙂 X9"]);
let down = fold(&mut arena, StrFold::Lower, &v).unwrap();
assert_eq!(read(&down), ["ann", "bo", "", "héllo", "🙂 x9"]);
}
#[test]
fn a_long_answer_lands_in_a_buffer_and_a_short_one_does_not() {
let mut arena = MorselArena::new();
let long = "a string well past the twelve bytes a view holds";
let v = str_vector(&mut arena, &["short", long]);
let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
let views = up.values::<StrView>();
assert!(views[0].is_inline(), "a short answer stays in its view");
assert!(!views[1].is_inline(), "a long one goes to the buffer");
assert_eq!(read(&up), ["SHORT", &long.to_ascii_uppercase()]);
}
#[test]
fn a_constant_is_folded_once() {
let mut arena = MorselArena::new();
let mut v = ValueVector::constant(
&mut arena,
PhysType::Str,
StrView::inline("héllo".as_bytes()),
3,
);
v.aux = Aux::None;
let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
assert_eq!(read(&up), ["HéLLO", "HéLLO", "HéLLO"]);
}
#[test]
fn a_dictionary_is_folded_a_table_at_a_time() {
let mut arena = MorselArena::new();
let entries = ["Ann", "a longer name than a view holds", "bo"];
let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
let codes = [2u16, 0, 1, 0, 1];
let v = ValueVector::dict_str(&mut arena, &codes, dict);
let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
assert_eq!(
read(&up),
read(&fold(&mut arena, StrFold::Upper, &flat).unwrap())
);
assert_eq!(read(&up)[0], "BO");
assert_eq!(read(&up)[2], entries[1].to_ascii_uppercase());
}
#[test]
fn a_fold_of_a_null_is_null() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &["Ann", "Bo", "Cy"]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let up = fold(&mut arena, StrFold::Upper, &v).unwrap();
assert!(!up.is_valid(1), "null in, null out");
assert!(up.is_valid(0) && up.is_valid(2));
assert_eq!(read(&up)[0], "ANN");
assert_eq!(read(&up)[2], "CY");
}
#[test]
fn a_fold_cannot_raise_and_answers_a_string() {
assert!(!StrFold::Upper.may_raise());
assert!(!StrFold::Lower.may_raise());
assert_eq!(
StrFold::Lower.answer_type(PhysType::Str),
Some(PhysType::Str)
);
assert_eq!(StrFold::Upper.answer_type(PhysType::Float64), None);
}
#[test]
fn each_end_trims_the_end_it_names() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &[" ann ", "bo", " ", ""]);
let set = TrimSet::new(" ");
let both = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
assert_eq!(both.phys, PhysType::Str);
assert_eq!(read(&both), ["ann", "bo", "", ""]);
let front = trim(&mut arena, StrTrim::Leading, &set, &v).unwrap();
assert_eq!(read(&front), ["ann ", "bo", "", ""]);
let back = trim(&mut arena, StrTrim::Trailing, &set, &v).unwrap();
assert_eq!(read(&back), [" ann", "bo", "", ""]);
}
#[test]
fn a_set_takes_any_of_its_members_off() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["xyxaxbyx", "xxx", "axb"]);
let set = TrimSet::new("xy");
let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
assert_eq!(read(&out), ["axb", "", "axb"]);
}
#[test]
fn a_wide_member_comes_off_whole() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["ééhélloé", "🙂a🙂", "é🙂é"]);
let set = TrimSet::new("é🙂");
let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
assert_eq!(read(&out), ["héllo", "a", ""]);
let v = str_vector(&mut arena, &["ñ"]);
let out = trim(&mut arena, StrTrim::Both, &TrimSet::new("é"), &v).unwrap();
assert_eq!(read(&out), ["ñ"]);
}
#[test]
fn an_empty_set_answers_the_string_it_was_given() {
let mut arena = MorselArena::new();
let set = TrimSet::new("");
assert!(set.is_empty());
let v = str_vector(&mut arena, &[" ann ", ""]);
let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
assert_eq!(read(&out), [" ann ", ""]);
}
#[test]
fn a_trimmed_string_points_back_at_what_it_was_trimmed_from() {
let mut arena = MorselArena::new();
let long = " a string well past the twelve bytes a view holds ";
let v = str_vector(&mut arena, &[long, " short "]);
let out = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v).unwrap();
assert_eq!(read(&out), [long.trim(), "short"]);
let views = out.values::<StrView>();
assert!(!views[0].is_inline(), "a long answer stays in the buffer");
assert!(views[1].is_inline(), "a short one fits in its view");
let (Aux::Str(theirs), Aux::Str(ours)) = (&v.aux, &out.aux) else {
panic!("a chunk with a long string in it carries buffers");
};
assert!(Arc::ptr_eq(theirs, ours));
}
#[test]
fn a_constant_is_trimmed_once() {
let mut arena = MorselArena::new();
let mut v = ValueVector::constant(
&mut arena,
PhysType::Str,
StrView::inline(" ann ".as_bytes()),
3,
);
v.aux = Aux::None;
let out = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v).unwrap();
assert_eq!(read(&out), ["ann", "ann", "ann"]);
}
#[test]
fn a_dictionary_is_trimmed_a_table_at_a_time() {
let mut arena = MorselArena::new();
let entries = [" a longer entry than a view holds ", " ann ", "bo "];
let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
let codes = [2u16, 0, 1, 0];
let v = ValueVector::dict_str(&mut arena, &codes, dict);
let set = TrimSet::new(" ");
let out = trim(&mut arena, StrTrim::Both, &set, &v).unwrap();
let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
assert_eq!(
read(&out),
read(&trim(&mut arena, StrTrim::Both, &set, &flat).unwrap())
);
assert_eq!(read(&out)[0], "bo");
assert_eq!(read(&out)[1], entries[0].trim());
}
#[test]
fn a_trim_of_a_null_is_null() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &[" ann ", " bo ", " cy "]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let out = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v).unwrap();
assert!(!out.is_valid(1), "null in, null out");
assert!(out.is_valid(0) && out.is_valid(2));
assert_eq!(read(&out)[0], "ann");
assert_eq!(read(&out)[2], "cy");
}
#[test]
fn a_trim_cannot_raise_and_answers_a_string() {
assert!(!StrTrim::Both.may_raise());
assert_eq!(
StrTrim::Leading.answer_type(PhysType::Str),
Some(PhysType::Str)
);
assert_eq!(StrTrim::Trailing.answer_type(PhysType::Int64), None);
}
#[test]
fn a_form_puts_an_accent_together_or_leaves_it_apart() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["h\u{e9}llo", "he\u{301}llo", "plain"]);
let together = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
assert_eq!(together.phys, PhysType::Str);
assert_eq!(read(&together), ["h\u{e9}llo", "h\u{e9}llo", "plain"]);
let apart = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
assert_eq!(read(&apart), ["he\u{301}llo", "he\u{301}llo", "plain"]);
}
#[test]
fn a_compatibility_form_answers_a_string_of_another_length() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["o\u{fb01}ce"]);
let canonical = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
assert_eq!(read(&canonical), ["o\u{fb01}ce"]);
let compat = normalize(&mut arena, NormalForm::Nfkc, &v).unwrap();
assert_eq!(read(&compat), ["ofice"]);
assert!("o\u{fb01}ce".len() > "ofice".len());
}
#[test]
fn a_plain_column_is_answered_without_a_byte_being_copied() {
let mut arena = MorselArena::new();
let long = "a plain string well past the twelve bytes a view holds";
let v = str_vector(&mut arena, &[long, "short"]);
let out = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
assert_eq!(read(&out), [long, "short"]);
let (Aux::Str(theirs), Aux::Str(ours)) = (&v.aux, &out.aux) else {
panic!("a chunk with a long string in it carries buffers");
};
assert!(Arc::ptr_eq(theirs, ours));
}
#[test]
fn a_long_answer_lands_in_a_buffer_of_its_own() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["h\u{e9}llo th\u{e9}re"]);
let out = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
assert_eq!(read(&out), ["he\u{301}llo the\u{301}re"]);
assert!(!out.values::<StrView>()[0].is_inline());
}
#[test]
fn a_constant_is_normalized_once() {
let mut arena = MorselArena::new();
let mut v = ValueVector::constant(
&mut arena,
PhysType::Str,
StrView::inline("h\u{e9}llo".as_bytes()),
3,
);
v.aux = Aux::None;
let out = normalize(&mut arena, NormalForm::Nfd, &v).unwrap();
assert_eq!(read(&out), ["he\u{301}llo"; 3]);
}
#[test]
fn a_dictionary_is_normalized_a_table_at_a_time() {
let mut arena = MorselArena::new();
let entries = [
"a\u{301} longer entry than a view holds",
"bo",
"h\u{e9}llo",
];
let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
let codes = [2u16, 0, 1, 0];
let v = ValueVector::dict_str(&mut arena, &codes, dict);
let out = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
assert_eq!(
read(&out),
read(&normalize(&mut arena, NormalForm::Nfc, &flat).unwrap())
);
assert_eq!(read(&out)[0], "h\u{e9}llo");
assert_eq!(read(&out)[1], "\u{e1} longer entry than a view holds");
}
#[test]
fn a_normalize_of_a_null_is_null() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &["he\u{301}llo", "bo", "cy"]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let out = normalize(&mut arena, NormalForm::Nfc, &v).unwrap();
assert!(!out.is_valid(1), "null in, null out");
assert!(out.is_valid(0) && out.is_valid(2));
assert_eq!(read(&out)[0], "h\u{e9}llo");
assert_eq!(read(&out)[2], "cy");
}
fn passed(bits: &Bitmap) -> Vec<usize> {
(0..bits.len()).filter(|i| bits.get(*i)).collect()
}
#[test]
fn the_test_answers_the_rows_that_are_in_the_form() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["h\u{e9}llo", "he\u{301}llo", "plain"]);
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
assert_eq!(passed(&bits), [0, 2]);
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfc, true, &v, &mut bits).unwrap();
assert_eq!(passed(&bits), [1]);
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfd, false, &v, &mut bits).unwrap();
assert_eq!(passed(&bits), [1, 2]);
}
#[test]
fn the_test_reads_a_constant_and_a_table_the_same_way() {
let mut arena = MorselArena::new();
let mut v = ValueVector::constant(
&mut arena,
PhysType::Str,
StrView::inline("he\u{301}llo".as_bytes()),
3,
);
v.aux = Aux::None;
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
assert!(passed(&bits).is_empty());
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfd, false, &v, &mut bits).unwrap();
assert_eq!(passed(&bits), [0, 1, 2]);
let entries = ["he\u{301}llo", "h\u{e9}llo", "plain"];
let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
let codes = [0u16, 1, 2, 0];
let v = ValueVector::dict_str(&mut arena, &codes, dict);
let mut bits = Bitmap::new_in(&mut arena, 4, false);
normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
let want: Vec<usize> = codes
.iter()
.enumerate()
.filter(|(_, c)| entries[**c as usize] != "he\u{301}llo")
.map(|(i, _)| i)
.collect();
assert_eq!(passed(&bits), want);
}
#[test]
fn a_null_is_in_neither_answer() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &["h\u{e9}llo", "he\u{301}llo", "cy"]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfc, false, &v, &mut bits).unwrap();
assert_eq!(passed(&bits), [0, 2]);
let mut bits = Bitmap::new_in(&mut arena, 3, false);
normalized(NormalForm::Nfc, true, &v, &mut bits).unwrap();
assert!(passed(&bits).is_empty(), "the null row is in neither");
}
#[test]
fn a_normalization_cannot_raise_and_the_two_answer_apart() {
let into = StrNorm::Into(NormalForm::Nfkd);
let test = StrNorm::Test(NormalForm::Nfkd);
assert!(!into.may_raise() && !test.may_raise());
assert_eq!(into.form(), NormalForm::Nfkd);
assert_eq!(into.answer_type(PhysType::Str), Some(PhysType::Str));
assert_eq!(test.answer_type(PhysType::Str), Some(PhysType::Bool));
assert_eq!(into.answer_type(PhysType::Int64), None);
assert_eq!(test.answer_type(PhysType::Float64), None);
}
#[test]
fn a_number_is_not_a_string() {
let mut arena = MorselArena::new();
let v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2]);
let Err(err) = length(&mut arena, StrLen::Chars, &v) else {
panic!("a number was measured as a string");
};
assert!(err.to_string().contains("char_length"));
let Err(err) = fold(&mut arena, StrFold::Upper, &v) else {
panic!("a number was folded as a string");
};
assert!(err.to_string().contains("upper"));
let Err(err) = trim(&mut arena, StrTrim::Both, &TrimSet::new(" "), &v) else {
panic!("a number was trimmed as a string");
};
assert!(err.to_string().contains("trim"));
let Err(err) = normalize(&mut arena, NormalForm::Nfc, &v) else {
panic!("a number was normalized as a string");
};
assert!(err.to_string().contains("normalize"));
let mut bits = Bitmap::new_in(&mut arena, 2, false);
let Err(err) = normalized(NormalForm::Nfc, false, &v, &mut bits) else {
panic!("a number was tested as a string");
};
assert!(err.to_string().contains("is_normalized"));
}
fn same_count(arena: &mut MorselArena, n: i64, len: usize) -> ValueVector {
ValueVector::constant(arena, PhysType::Int64, n, len)
}
fn counts(arena: &mut MorselArena, vals: &[i64]) -> ValueVector {
ValueVector::flat_from(arena, PhysType::Int64, vals)
}
#[test]
fn a_cut_counts_characters_and_not_bytes() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["h\u{e9}llo", "\u{1f642}ab", "plain"]);
let two = same_count(&mut arena, 2, 3);
let left = cut(&mut arena, StrCut::Left, &v, &two, None).unwrap();
assert_eq!(left.phys, PhysType::Str);
assert_eq!(read(&left), ["h\u{e9}", "\u{1f642}a", "pl"]);
let right = cut(&mut arena, StrCut::Right, &v, &two, None).unwrap();
assert_eq!(read(&right), ["lo", "ab", "in"]);
}
#[test]
fn the_ends_of_the_range_are_answers_and_not_conditions() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["abc", "", "h\u{e9}llo"]);
let plenty = same_count(&mut arena, 40, 3);
let out = cut(&mut arena, StrCut::Left, &v, &plenty, None).unwrap();
assert_eq!(read(&out), ["abc", "", "h\u{e9}llo"]);
let none = same_count(&mut arena, 0, 3);
let out = cut(&mut arena, StrCut::Right, &v, &none, None).unwrap();
assert_eq!(read(&out), ["", "", ""]);
}
#[test]
fn a_plain_column_is_cut_without_a_byte_being_copied() {
let mut arena = MorselArena::new();
let long = "a plain string well past the twelve bytes a view holds";
let v = str_vector(&mut arena, &[long, "short"]);
let count = same_count(&mut arena, 30, 2);
let out = cut(&mut arena, StrCut::Right, &v, &count, None).unwrap();
assert_eq!(read(&out), [&long[long.len() - 30..], "short"]);
let (Aux::Str(theirs), Aux::Str(ours)) = (&v.aux, &out.aux) else {
panic!("a chunk with a long string in it carries buffers");
};
assert!(Arc::ptr_eq(theirs, ours));
}
#[test]
fn a_constant_is_cut_once_or_a_row_at_a_time() {
let mut arena = MorselArena::new();
let mut v = ValueVector::constant(
&mut arena,
PhysType::Str,
StrView::inline("h\u{e9}llo".as_bytes()),
3,
);
v.aux = Aux::None;
let two = same_count(&mut arena, 2, 3);
let out = cut(&mut arena, StrCut::Left, &v, &two, None).unwrap();
assert_eq!(read(&out), ["h\u{e9}", "h\u{e9}", "h\u{e9}"]);
let varying = counts(&mut arena, &[1, 3, 5]);
let out = cut(&mut arena, StrCut::Left, &v, &varying, None).unwrap();
assert_eq!(read(&out), ["h", "h\u{e9}l", "h\u{e9}llo"]);
}
#[test]
fn a_dictionary_is_cut_a_table_at_a_time_or_a_row_at_a_time() {
let mut arena = MorselArena::new();
let entries = ["a longer entry than a view holds", "bo", "h\u{e9}llo"];
let dict = Arc::new(Dictionary::from_sorted(entries.iter()));
let codes = [2u16, 0, 1, 0];
let v = ValueVector::dict_str(&mut arena, &codes, dict);
let flat = str_vector(&mut arena, &codes.map(|c| entries[c as usize]));
let four = same_count(&mut arena, 4, 4);
let out = cut(&mut arena, StrCut::Left, &v, &four, None).unwrap();
assert_eq!(
read(&out),
read(&cut(&mut arena, StrCut::Left, &flat, &four, None).unwrap())
);
assert_eq!(read(&out)[0], "h\u{e9}ll");
let varying = counts(&mut arena, &[1, 2, 2, 40]);
let out = cut(&mut arena, StrCut::Right, &v, &varying, None).unwrap();
assert_eq!(
read(&out),
read(&cut(&mut arena, StrCut::Right, &flat, &varying, None).unwrap())
);
assert_eq!(read(&out)[3], "a longer entry than a view holds");
}
#[test]
fn a_null_on_either_side_answers_null() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &["abc", "def", "ghi"]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(0);
v.validity = Some(valid);
let mut n = counts(&mut arena, &[2, 2, 2]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
n.validity = Some(valid);
let out = cut(&mut arena, StrCut::Left, &v, &n, None).unwrap();
assert!(!out.is_valid(0), "a null string answers null");
assert!(!out.is_valid(1), "a null count answers null");
assert!(out.is_valid(2));
assert_eq!(read(&out)[2], "gh");
}
#[test]
fn a_negative_count_raises_the_standards_condition() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["abc", "def"]);
let n = counts(&mut arena, &[1, -2]);
let Err(err) = cut(&mut arena, StrCut::Right, &v, &n, None) else {
panic!("a negative count was answered");
};
assert_eq!(err.gqlstatus().map(|s| s.to_string()), Some("22011".into()));
assert!(err.to_string().contains("right()"), "{err}");
assert!(err.to_string().contains("-2"), "{err}");
}
#[test]
fn a_row_that_was_never_evaluated_raises_nothing() {
let mut arena = MorselArena::new();
let mut v = str_vector(&mut arena, &["abc", "def", "ghi"]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
v.validity = Some(valid);
let n = counts(&mut arena, &[3, -1, -1]);
let mut bits = Bitmap::new_in(&mut arena, 3, false);
bits.set(0);
bits.set(1);
let sel = SelVector::from_bitmap(&mut arena, &bits);
let out = cut(&mut arena, StrCut::Left, &v, &n, Some(&sel)).unwrap();
assert_eq!(read(&out)[0], "abc");
let Err(err) = cut(&mut arena, StrCut::Left, &v, &n, None) else {
panic!("the unselected row's count was never looked at");
};
assert!(err.to_string().contains("left()"), "{err}");
}
#[test]
fn a_cut_can_raise_and_wants_a_string_and_a_number() {
assert!(StrCut::Left.may_raise() && StrCut::Right.may_raise());
assert_eq!(
StrCut::Left.answer_type(PhysType::Str, PhysType::Int64),
Some(PhysType::Str)
);
assert!(
StrCut::Left
.answer_type(PhysType::Str, PhysType::Float64)
.is_none()
);
let mut arena = MorselArena::new();
let v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2]);
let n = counts(&mut arena, &[1, 1]);
let Err(err) = cut(&mut arena, StrCut::Left, &v, &n, None) else {
panic!("a number was cut as a string");
};
assert!(err.to_string().contains("left()"), "{err}");
}
#[test]
fn an_identifier_is_the_table_and_the_row() {
let mut arena = MorselArena::new();
let rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[0i64, 7, 1234567]);
let ids = element_ids(&mut arena, 3, &rows).unwrap();
assert_eq!(ids.phys, PhysType::Str);
assert_eq!(read(&ids), vec!["n:3:0", "n:3:7", "n:3:1234567"]);
}
#[test]
fn an_identifier_is_what_the_row_engine_writes() {
let mut arena = MorselArena::new();
for (table, row) in [(0u32, 0i64), (1, 2), (10, 99), (u32::MAX, 4_294_967_296)] {
let rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[row]);
let ids = element_ids(&mut arena, table, &rows).unwrap();
assert_eq!(read(&ids), vec![format!("n:{table}:{row}")]);
}
}
#[test]
fn an_identifier_too_long_to_sit_inline_goes_to_the_buffer() {
let mut arena = MorselArena::new();
let rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[5i64, 9_876_543_210_123]);
let ids = element_ids(&mut arena, 65535, &rows).unwrap();
let views = ids.values::<StrView>();
assert!(views[0].is_inline(), "a short identifier stays in the view");
assert!(!views[1].is_inline(), "a long one does not");
assert_eq!(
read(&ids),
vec!["n:65535:5", "n:65535:9876543210123"],
"and both read back the same"
);
}
#[test]
fn a_constant_row_is_written_once() {
let mut arena = MorselArena::new();
let rows = ValueVector::constant(&mut arena, PhysType::Int64, 12i64, 4);
let ids = element_ids(&mut arena, 0, &rows).unwrap();
assert_eq!(read(&ids), vec!["n:0:12"; 4]);
}
#[test]
fn a_null_row_has_no_identifier() {
let mut arena = MorselArena::new();
let mut rows = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 0, 3]);
let mut valid = Bitmap::new_in(&mut arena, 3, true);
valid.clear(1);
rows.validity = Some(valid);
let ids = element_ids(&mut arena, 2, &rows).unwrap();
let valid = ids.validity.as_ref().expect("the answer carries validity");
assert!(valid.get(0) && !valid.get(1) && valid.get(2));
}
#[test]
fn identifiers_want_a_column_of_rows() {
let mut arena = MorselArena::new();
let v = str_vector(&mut arena, &["ann"]);
let Err(err) = element_ids(&mut arena, 0, &v) else {
panic!("a column of strings was read as rows");
};
assert!(err.to_string().contains("ELEMENT_ID()"), "{err}");
}
}