rudof_rdf/rdf_core/query/variable_solution_index.rs
1use crate::rdf_core::{Rdf, query::QuerySolution};
2
3/// Trait for types that can index into a SPARQL query solution.
4///
5/// This trait abstracts over different ways to access variables in a
6/// [`QuerySolution`]. It allows the same lookup API to work with numeric
7/// indices, string variable names, or wrapped variable name types.
8///
9/// # Type Parameters
10///
11/// * `S` - The RDF graph type implementing [`Rdf`]
12pub trait VariableSolutionIndex<S: Rdf> {
13 /// Returns the position index of a variable in the query solution.
14 ///
15 /// This method attempts to locate the variable in the solution and returns
16 /// its zero-based position index if found.
17 ///
18 /// # Arguments
19 ///
20 /// * `solution` - The query solution to search within
21 fn index(self, solution: &QuerySolution<S>) -> Option<usize>;
22}
23
24impl<S: Rdf> VariableSolutionIndex<S> for usize {
25 /// Returns the numeric index directly without validation.
26 ///
27 /// This implementation provides O(1) direct positional access to variables
28 /// in a query solution. It does not validate that the index is within bounds;
29 /// validation should be performed by the caller when accessing the value.
30 ///
31 /// # Arguments
32 ///
33 /// * `_` - The query solution (unused, as the index is already known)
34 fn index(self, _: &QuerySolution<S>) -> Option<usize> {
35 Some(self)
36 }
37}
38
39impl<S: Rdf> VariableSolutionIndex<S> for &str {
40 /// Finds the index of a variable by name string.
41 ///
42 /// This implementation performs a linear search through the solution's
43 /// variables to find one matching the provided name string. The search
44 /// compares against the bare variable name (without `?` or `$` prefix).
45 ///
46 /// # Arguments
47 ///
48 /// * `solution` - The query solution to search
49 fn index(self, solution: &QuerySolution<S>) -> Option<usize> {
50 solution.variables_iter().position(|v| v.as_str() == self)
51 }
52}