use super::{
argument_text, flag_text,
flags::ReFlags,
match_set::{MatchSet, Search},
plain, string, SingleResult,
};
use crate::error::{Result, SQLError};
use uqa_core::{
memory::{Produced, ProductionControl, ProductionVec},
ArrayValue, Value,
};
#[derive(Debug)]
pub struct RegexSplit {
matches: MatchSet,
next: usize,
}
impl RegexSplit {
pub fn new(
function: &'static str,
arguments: &[Value],
collation: u32,
control: &ProductionControl<'_>,
) -> Result<Option<Self>> {
control.check()?;
if !(2..=3).contains(&arguments.len()) {
return Err(SQLError::TypeMismatch(format!(
"{function} takes 2 or 3 args"
)));
}
if arguments.iter().any(|value| matches!(value, Value::Null)) {
return Ok(None);
}
let input = argument_text(&arguments[0], control)?;
let pattern = argument_text(&arguments[1], control)?;
let flags = ReFlags::parse(&flag_text(arguments.get(2), control)?)?
.reject_global(SingleResult::named(function))?
.every_match();
let search = Search {
start: 0,
subexpressions: false,
ignore_degenerate: true,
};
let matches = MatchSet::find(&input, &pattern, flags, collation, search, control)?;
Ok(Some(Self { matches, next: 0 }))
}
pub fn next_piece(
&mut self,
control: &ProductionControl<'_>,
) -> Result<Option<Produced<Value>>> {
control.check()?;
let count = self.matches.len();
if self.next > count {
return Ok(None);
}
let start = if self.next == 0 {
Some(0)
} else {
self.matches.span(self.next - 1, 0).end()
};
let end = if self.next == count {
Some(self.matches.input_len())
} else {
self.matches.span(self.next, 0).start()
};
let (Some(start), Some(end)) = (start, end) else {
return Err(SQLError::Internal(
"a regular expression split lost a match boundary".into(),
));
};
let piece = string(self.matches.slice(start..end, control)?, control)?;
self.next += 1;
Ok(Some(piece))
}
}
pub(super) fn array(
args: &[Value],
collation: u32,
control: &ProductionControl<'_>,
) -> Result<Produced<Value>> {
let Some(mut split) = RegexSplit::new("regexp_split_to_array", args, collation, control)?
else {
return plain(Value::Null, control);
};
let mut pieces = ProductionVec::new(*control);
while let Some(piece) = split.next_piece(control)? {
pieces.push_produced(piece)?;
}
drop(split);
let array = ArrayValue::try_new_with_control(pieces.finish()?, control)?
.ok_or_else(|| SQLError::TypeMismatch("invalid regexp_split_to_array result".into()))?;
let (array, memory) = array.into_parts();
control
.finish(Value::Array(array), memory)
.map_err(Into::into)
}