use super::{
EntitySchema, Error, IndexValue, MemberNeedle, Term, TermOperand, contains_member, scalar_bytes,
};
pub(super) struct PredicateRow<'a> {
pub entity: &'a EntitySchema,
pub bytes: &'a [u8],
pub values: &'a [IndexValue<'a>],
pub spans: &'a [(u16, u16)],
pub span_fields: u32,
}
impl<'a> PredicateRow<'a> {
fn accepts(
&self,
term: &Term,
component: &mut Vec<u8>,
right_component: &mut Vec<u8>,
) -> Result<bool, Error> {
let left = term.field;
let position = left.position;
let field = &self.entity.fields[position];
let span = || {
let (start, end) = self.spans[position];
&self.bytes[usize::from(start)..usize::from(end)]
};
let read = |field: super::ResolvedField| {
field.read(self.entity, self.bytes, self.values, self.spans)
};
let value = read(left)?;
let (rhs, encoded, optional) = match &term.operand {
TermOperand::Literal {
value: IndexValue::Absent,
..
} => {
let absent = if left.member.is_none() && self.span_fields & (1 << position) != 0 {
span()[0] == 0
} else {
value == IndexValue::Absent
};
return Ok(term.comparison.accepts_absent(absent));
}
TermOperand::Literal { bytes, value: rhs } => {
(*rhs, Some(bytes.as_slice()), left.optional(self.entity))
}
TermOperand::Member { item, needle } => {
let needle = match needle {
MemberNeedle::Literal(value) => *value,
MemberNeedle::Field(right) => read(*right)?,
};
return if needle == IndexValue::Absent {
Ok(false)
} else {
contains_member(span(), field.optional, *item, needle)
};
}
TermOperand::Length(threshold) => {
let actual = if left.member.is_some() {
match value {
IndexValue::Absent => None,
value => Some(scalar_bytes(value).ok_or(Error::Corrupt)?.len() as u32),
}
} else {
crate::codec::validated_length(span(), field.optional)
};
return Ok(term.comparison.accepts_length(actual, *threshold));
}
TermOperand::Field(right) => (read(*right)?, None, false),
};
if value == IndexValue::Absent || rhs == IndexValue::Absent {
return Ok(term.comparison.accepts_absent(value == rhs));
}
if let Some(matches) = term.comparison.accepts_values(value, rhs) {
return Ok(matches);
}
let right = encoded.unwrap_or_else(|| {
right_component.clear();
rhs.append_component(false, right_component);
right_component
});
component.clear();
value.append_component(optional, component);
Ok(term
.comparison
.accepts(Some(component), Some(right), optional))
}
pub(super) fn matches(
&self,
terms: &[Term],
component: &mut Vec<u8>,
right_component: &mut Vec<u8>,
) -> Result<bool, Error> {
let mut clause_matches = false;
for term in terms {
clause_matches = clause_matches || self.accepts(term, component, right_component)?;
if !term.or_next {
if !clause_matches {
return Ok(false);
}
clause_matches = false;
}
}
Ok(true)
}
}