### Example SPARQL Query with SERVICE Clause Source: https://docs.rs/sparopt This example shows a SPARQL query that includes a SERVICE clause pointing to a non-existent endpoint. The optimizer might rewrite this to an empty query. ```sparql SELECT * WHERE { SERVICE {} } ``` -------------------------------- ### Example of SPARQL Query Rewriting Source: https://docs.rs/sparopt/latest/sparopt/index.html Demonstrates how sparopt might rewrite a query containing a non-existent SERVICE endpoint. The optimizer can simplify such queries by removing the problematic SERVICE clause. ```sparql SELECT * WHERE { SERVICE {} } ``` ```sparql SELECT * WHERE {} ``` -------------------------------- ### Parsing Literals from Strings Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Literal.html Demonstrates how to parse different types of literals (simple, language-tagged, typed) from their NTriples serialization using `FromStr`. Includes examples for escaped characters, language tags, and various XSD types. ```rust use oxrdf::vocab::xsd; use oxrdf::{Literal, NamedNode}; use std::str::FromStr; assert_eq!( Literal::from_str("\"ex\\n\"")?, Literal::new_simple_literal("ex\n") ); assert_eq!( Literal::from_str("\"ex\"@en")?, Literal::new_language_tagged_literal("ex", "en")? ); assert_eq!( Literal::from_str("\"2020\"^^")?, Literal::new_typed_literal( "2020", NamedNode::new("http://www.w3.org/2001/XMLSchema#gYear")? ) ); assert_eq!( Literal::from_str("true")?, Literal::new_typed_literal("true", xsd::BOOLEAN) ); assert_eq!( Literal::from_str("+122")?, Literal::new_typed_literal("+122", xsd::INTEGER) ); assert_eq!( Literal::from_str("-122.23")?, Literal::new_typed_literal("-122.23", xsd::DECIMAL) ); assert_eq!( Literal::from_str("-122e+1")?, Literal::new_typed_literal("-122e+1", xsd::DOUBLE) ); ``` -------------------------------- ### Convert NamedNode to NamedNodePattern Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.NamedNodePattern.html Demonstrates how to convert a NamedNode into a NamedNodePattern using the `From` trait. This is useful when constructing patterns that start as specific IRIs. ```rust fn from(node: NamedNode) -> NamedNodePattern ``` -------------------------------- ### Estimate Path Size for Property Path Expressions Source: https://docs.rs/sparopt/latest/src/sparopt/optimizer.rs.html Estimates the size of a property path expression, handling different types of path constructs like sequences, alternatives, and repetitions. It considers whether the start and end of the path are bound. ```rust fn estimate_path_size(start_bound: bool, path: &PropertyPathExpression, end_bound: bool) -> usize { match path { PropertyPathExpression::NamedNode(_) => { estimate_triple_pattern_size(start_bound, true, end_bound) } PropertyPathExpression::Reverse(p) => estimate_path_size(end_bound, p, start_bound), PropertyPathExpression::Sequence(a, b) => { // We do a for loop join in the best direction min( estimate_path_size(start_bound, a, false) .saturating_mul(estimate_path_size(true, b, end_bound)), estimate_path_size(start_bound, a, true) .saturating_mul(estimate_path_size(false, b, end_bound)), ) } PropertyPathExpression::Alternative(a, b) => estimate_path_size(start_bound, a, end_bound) .saturating_add(estimate_path_size(start_bound, b, end_bound)), PropertyPathExpression::ZeroOrMore(p) => { if start_bound && end_bound { 1 } else if start_bound || end_bound { estimate_path_size(start_bound, p, end_bound).saturating_mul(1000) } else { 1_000_000_000 } } PropertyPathExpression::OneOrMore(p) => { if start_bound && end_bound { 1 } else { estimate_path_size(start_bound, p, end_bound).saturating_mul(1000) } } PropertyPathExpression::ZeroOrOne(p) => { if start_bound && end_bound { 1 } else if start_bound || end_bound { estimate_path_size(start_bound, p, end_bound) } else { 1_000_000_000 } } PropertyPathExpression::NegatedPropertySet(_) => { estimate_triple_pattern_size(start_bound, false, end_bound) } } } ``` -------------------------------- ### Get NamedNode as String Slice Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Provides a string slice view of the IRI contained within the NamedNode. ```rust pub fn as_str(&self) -> &str ``` -------------------------------- ### Variable Creation and Formatting Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Variable.html Demonstrates how to create a Variable and format it into a SPARQL-compatible string representation. ```APIDOC ## Variable Struct ### Description A SPARQL query owned variable. ### Usage Example ```rust use oxrdf::Variable; // Create a new variable named "foo" let var = Variable::new("foo").expect("Invalid variable name"); // Format the variable as a SPARQL string assert_eq!("?foo", var.to_string()); ``` ### Methods #### `new(name: impl Into) -> Result` Creates a variable name from a unique identifier. The variable identifier must be valid according to the SPARQL grammar. #### `new_unchecked(name: impl Into) -> Variable` Creates a variable name from a unique identifier without validation. It is the caller’s responsibility to ensure that `id` is a valid blank node identifier according to the SPARQL grammar. `Variable::new()` is a safe version of this constructor and should be used for untrusted data. #### `as_str(&self) -> &str` Returns the variable name as a string slice. #### `into_string(self) -> String` Consumes the `Variable` and returns its name as an owned `String`. #### `as_ref(&self) -> VariableRef<'_>` Returns a reference to the variable name. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Provides the `type_id` method to get the unique identifier of a type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method fn ### Parameters None ### Response #### Success Response - **TypeId**: The unique identifier of the type. ``` -------------------------------- ### type_id Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Gets the TypeId of an object. This is a fundamental method for runtime type identification. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Signature `fn type_id(&self) -> TypeId` ``` -------------------------------- ### Create and Format SPARQL Variable Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Variable.html Demonstrates creating a Variable from a string and converting it to its SPARQL-compatible string representation. Requires the oxrdf crate. ```rust use oxrdf::{Variable, VariableNameParseError}; assert_eq!("?foo", Variable::new("foo")?.to_string()); ``` -------------------------------- ### NamedNode Min Value Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Provides a method to get the minimum of two NamedNode values. ```rust fn min(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Provides an experimental, nightly-only method for cloning data to an uninitialized memory location. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Method unsafe fn ### Parameters - **dest** (*mut u8) - Required - A pointer to the destination memory location. ### Response None ``` -------------------------------- ### RDF Literal String Formatting Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Literal.html Demonstrates how to format RDF literals into N-Triples, Turtle, and SPARQL compatible strings using different constructors. ```rust use oxrdf::Literal; use oxrdf::vocab::xsd; assert_eq!( "\"foo\nbar\"", Literal::new_simple_literal("foo\nbar").to_string() ); assert_eq!( r#"\"1999-01-01\"^^"#, Literal::new_typed_literal("1999-01-01", xsd::DATE).to_string() ); assert_eq!( r#"\"foo\"@en"#, Literal::new_language_tagged_literal("foo", "en")?.to_string() ); ``` -------------------------------- ### NamedNode Max Value Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Provides a method to get the maximum of two NamedNode values. ```rust fn max(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### Expression Construction and Conversion Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Demonstrates the conversion of various expression types into their canonical forms, including logical operations, comparisons, arithmetic, and function calls. This is part of the `From` implementation for `Expression`. ```rust Expression::And(inner) => inner .iter() .map(Into::into) .reduce(|a, b| Self::And(Box::new(a), Box::new(b))) .unwrap_or_else(|| Literal::from(true).into()), Expression::Equal(left, right) => Self::Equal( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::SameTerm(left, right) => Self::SameTerm( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::Greater(left, right) => Self::Greater( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::GreaterOrEqual(left, right) => Self::GreaterOrEqual( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::Less(left, right) => Self::Less( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::LessOrEqual(left, right) => Self::LessOrEqual( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::Add(left, right) => Self::Add( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::Subtract(left, right) => Self::Subtract( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::Multiply(left, right) => Self::Multiply( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::Divide(left, right) => Self::Divide( Box::new(left.as_ref().into()), Box::new(right.as_ref().into()), ), Expression::UnaryPlus(inner) => Self::UnaryPlus(Box::new(inner.as_ref().into())), Expression::UnaryMinus(inner) => Self::UnaryMinus(Box::new(inner.as_ref().into())), Expression::Not(inner) => Self::Not(Box::new(inner.as_ref().into())), Expression::Exists(inner) => Self::Exists(Box::new(inner.as_ref().into())), Expression::Bound(variable) => Self::Bound(variable.clone()), Expression::If(cond, yes, no) => Self::If( Box::new(cond.as_ref().into()), Box::new(yes.as_ref().into()), Box::new(no.as_ref().into()), ), Expression::Coalesce(inner) => Self::Coalesce(inner.iter().map(Into::into).collect()), Expression::FunctionCall(name, args) => { Self::FunctionCall(name.clone(), args.iter().map(Into::into).collect()) } } } } ``` -------------------------------- ### Get NamedNodeRef from NamedNode Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Obtains a reference to the NamedNode, allowing borrowing without consuming the original. ```rust pub fn as_ref(&self) -> NamedNodeRef<'_> ``` -------------------------------- ### Literal Construction Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Literal.html Demonstrates how to construct different types of RDF literals: simple, typed, and language-tagged. ```APIDOC ## Literal Construction ### Description This section details the methods for creating RDF literals. ### Methods #### `new_simple_literal(value: impl Into) -> Literal` Builds an RDF simple literal. #### `new_typed_literal(value: impl Into, datatype: impl Into) -> Literal` Builds an RDF literal with a datatype. #### `new_language_tagged_literal(value: impl Into, language: impl Into) -> Result` Builds an RDF language-tagged string. Returns an error if the language tag is invalid. #### `new_language_tagged_literal_unchecked(value: impl Into, language: impl Into) -> Literal` Builds an RDF language-tagged string without validation. The caller must ensure the language tag is valid BCP47 and lowercase. #### `new_directional_language_tagged_literal(value: impl Into, language: impl Into, direction: impl Into) -> Result` (Available on `rdf-12` feature only) Builds an RDF directional language-tagged string. Returns an error if the language tag is invalid. #### `new_directional_language_tagged_literal_unchecked(value: impl Into, language: impl Into, direction: impl Into) -> Literal` (Available on `rdf-12` feature only) Builds an RDF directional language-tagged string without validation. The caller must ensure the language tag is valid BCP47 and lowercase. ``` -------------------------------- ### Transform AlGraphPattern::Slice Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Converts a Slice graph pattern into its internal representation, preserving start and length. ```rust AlGraphPattern::Slice { inner, start, length, } => Self::Slice { inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)), start: *start, length: *length, } ``` -------------------------------- ### clone_to_uninit Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Performs copy-assignment from self to a destination pointer. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Signature `unsafe fn clone_to_uninit(&self, dest: *mut u8)` ``` -------------------------------- ### Create Slice Operation Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Translates a Slice graph pattern, which limits the results to a specific range (start and length). ```rust GraphPattern::Slice { inner, start, length, } => Self::Slice { inner: Box::new(inner.as_ref().into()), start: *start, length: *length, } ``` -------------------------------- ### Convert AlGraphPattern to GraphPattern (Default) Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Provides a default conversion from AlGraphPattern to GraphPattern using `Self::from_sparql_algebra` with no graph name and an empty HashMap for blank nodes. ```rust impl From<&AlGraphPattern> for GraphPattern { fn from(pattern: &AlGraphPattern) -> Self { Self::from_sparql_algebra(pattern, None, &mut HashMap::new()) } } ``` -------------------------------- ### Slice Operation Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Constructs a Slice operation. Returns the inner operation if start is 0 and length is None, or an empty operation if the inner operation is empty. ```rust pub fn slice(inner: Self, start: usize, length: Option) -> Self { if inner.is_empty() { return Self::empty(); } if start == 0 && length.is_none() { return inner; } Self::Slice { inner: Box::new(inner), start, length, } } ``` -------------------------------- ### VariableTypes Struct Definition Source: https://docs.rs/sparopt/latest/src/sparopt/type_inference.rs.html Defines the `VariableTypes` struct, which holds a map of variables to their inferred types. Provides methods for getting, iterating, intersecting, and unioning type sets. ```rust #[derive(Default, Clone, Debug)] pub struct VariableTypes { inner: HashMap, } impl VariableTypes { pub fn get(&self, variable: &Variable) -> VariableType { self.inner .get(variable) .copied() .unwrap_or(VariableType::UNDEF) } pub fn iter(&self) -> impl Iterator { self.inner.iter() } pub fn intersect_with(&mut self, other: Self) { for (v, t) in other.inner { self.intersect_variable_with(v, t); } } pub fn union_with(&mut self, other: Self) { for (v, t) in &mut self.inner { if other.get(v).undef { t.undef = true; // Might be undefined } } for (v, mut t) in other.inner { self.inner .entry(v) .and_modify(|ex| *ex = *ex | t) .or_insert({ t.undef = true; t }); } } fn intersect_variable_with(&mut self, variable: Variable, t: VariableType) { let t = self.get(&variable) & t; if t != VariableType::UNDEF { self.inner.insert(variable, t); } } } ``` -------------------------------- ### Converting SPARQL Bgp to Graph Patterns Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Transforms a SPARQL Basic Graph Pattern (BGP) into a sequence of QuadPatterns, joined by a default Join algorithm. If the BGP is empty, it returns an empty singleton or a Graph pattern if a graph name is provided. ```rust AlGraphPattern::Bgp { patterns } => patterns .iter() .map(|p| { let (subject, predicate, object) = Self::triple_pattern_from_algebra(p, blank_nodes); Self::QuadPattern { subject, predicate, object, graph_name: graph_name.cloned(), } }) .reduce(|a, b| Self::Join { left: Box::new(a), right: Box::new(b), algorithm: JoinAlgorithm::default(), }) .unwrap_or_else(|| { if let Some(graph_name) = graph_name { Self::Graph { graph_name: graph_name.clone(), } } else { Self::empty_singleton() } }) ``` -------------------------------- ### NamedNode String Representation Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Demonstrates how NamedNode's default string formatter produces N-Triples, Turtle, and SPARQL compatible output. ```rust use oxrdf::NamedNode; assert_eq!( "", NamedNode::new("http://example.com/foo")?.to_string() ); ``` -------------------------------- ### try_from Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Attempts to perform a conversion from one type to another, returning a `Result`. ```APIDOC ## fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ### Signature `fn try_from(value: U) -> Result>::Error>` ``` -------------------------------- ### Expression Conversions (From) Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Details the various ways an Expression can be created from other types. ```APIDOC ## From<&Expression> for Expression ### Description Converts an Expression reference to an owned Expression. ### Method `from(expression: &Expression) -> Self` ## From for Expression ### Description Converts a GroundTerm into an Expression. ### Method `from(value: GroundTerm) -> Self` ## From for Expression ### Description Converts a GroundTermPattern into an Expression. ### Method `from(value: GroundTermPattern) -> Self` ## From for Expression ### Description Converts a Literal into an Expression. ### Method `from(value: Literal) -> Self` ## From for Expression ### Description Converts a NamedNode into an Expression. ### Method `from(value: NamedNode) -> Self` ## From for Expression ### Description Converts a NamedNodePattern into an Expression. ### Method `from(value: NamedNodePattern) -> Self` ## From for Expression ### Description Converts a Variable into an Expression. ### Method `from(value: Variable) -> Self` ## From for Expression ### Description Converts a boolean value into an Expression. ### Method `from(value: bool) -> Self` ``` -------------------------------- ### Build and Validate RDF IRI Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Constructs a valid RDF IRI using the `new` function. It returns a Result, indicating potential parsing errors. ```rust pub fn new(iri: impl Into) -> Result ``` -------------------------------- ### Create Empty Singleton GraphPattern Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Creates a GraphPattern representing an empty singleton, which is a Values pattern with no variables but one empty binding. ```rust pub fn empty_singleton() -> Self { Self::Values { variables: Vec::new(), bindings: vec![Vec::new()], } } ``` -------------------------------- ### Join Algorithm Enum Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Defines the HashBuildLeftProbeRight join algorithm. Used in GraphPattern::Join. ```rust pub enum JoinAlgorithm { HashBuildLeftProbeRight { keys: Vec }, } impl Default for JoinAlgorithm { fn default() -> Self { Self::HashBuildLeftProbeRight { keys: Vec::default(), } } } ``` -------------------------------- ### from Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Creates a new instance of a type from a given value. This is a fundamental conversion trait. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. ### Signature `fn from(t: T) -> T` ``` -------------------------------- ### TryFrom for GroundTermPattern Conversion Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.GroundTermPattern.html Attempts to convert a TermPattern into a GroundTermPattern. This conversion might fail, returning an error. ```rust fn try_from( pattern: TermPattern, ) -> Result>::Error> ``` -------------------------------- ### GraphPattern Methods Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.GraphPattern.html Provides documentation for various methods of the GraphPattern enum, allowing users to construct and manipulate SPARQL graph patterns programmatically. ```APIDOC ## GraphPattern Methods ### `empty()` Creates an empty graph pattern. ### `empty_singleton()` Creates an empty singleton graph pattern. ### `is_empty_singleton()` Checks if the graph pattern is an empty singleton. ### `join(left: GraphPattern, right: GraphPattern, algorithm: JoinAlgorithm)` Joins two graph patterns using a specified algorithm. ### `lateral(left: GraphPattern, right: GraphPattern)` Performs a lateral join between two graph patterns. Available on `crate feature 'sep-0006'` only. ### `left_join(left: GraphPattern, right: GraphPattern, expression: Expression, algorithm: LeftJoinAlgorithm)` Performs a left join between two graph patterns with a specified expression and algorithm. ### `minus(left: GraphPattern, right: GraphPattern, algorithm: MinusAlgorithm)` Performs a minus operation between two graph patterns using a specified algorithm. ### `union(left: GraphPattern, right: GraphPattern)` Performs a union operation between two graph patterns. ### `union_all(args: impl IntoIterator)` Performs a union operation on an iterator of graph patterns. ### `filter(inner: GraphPattern, expression: Expression)` Applies a filter expression to a graph pattern. ### `extend(inner: GraphPattern, variable: Variable, expression: Expression)` Extends a graph pattern by adding a new variable bound to an expression. ### `values(variables: Vec, bindings: Vec>>)` Creates a graph pattern from a list of variables and bindings. ### `order_by(inner: GraphPattern, expression: Vec)` Orders the results of a graph pattern based on a list of expressions. ### `project(inner: GraphPattern, variables: Vec)` Projects a graph pattern to include only the specified variables. ### `distinct(inner: GraphPattern)` Removes duplicate solutions from a graph pattern. ### `reduced(inner: GraphPattern)` Reduces the solutions of a graph pattern. ### `slice(inner: GraphPattern, start: usize, length: Option)` Slices the results of a graph pattern, returning a subset of solutions. ### `group(inner: GraphPattern, variables: Vec, aggregates: Vec<(Variable, AggregateExpression)>)` Groups the results of a graph pattern by specified variables and applies aggregate functions. ### `service(inner: GraphPattern, name: NamedNodePattern, silent: bool)` Applies a SERVICE operation to a graph pattern. ### `lookup_used_variables<'a>(self: &'a GraphPattern, callback: &mut impl FnMut(&'a Variable))` Looks up and processes all used variables in a graph pattern via a callback function. ``` -------------------------------- ### Optimize Graph Pattern Source: https://docs.rs/sparopt/latest/src/sparopt/optimizer.rs.html The main entry point for optimizing a graph pattern. It orchestrates normalization, join reordering, and filter pushing. ```rust pub fn optimize_graph_pattern(pattern: GraphPattern) -> GraphPattern { let pattern = Self::normalize_pattern(pattern, &VariableTypes::default()); let pattern = Self::reorder_joins(pattern, &VariableTypes::default()); Self::push_filters(pattern, Vec::new(), &VariableTypes::default()) } ``` -------------------------------- ### Create Empty GraphPattern Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Provides a method to create an empty GraphPattern, represented as a Values pattern with no variables and no bindings. ```rust pub fn empty() -> Self { Self::Values { variables: Vec::new(), bindings: Vec::new(), } } ``` -------------------------------- ### Expression Equality and Hashing Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Covers the equality comparison and hashing implementations for the Expression type. ```APIDOC ## PartialEq for Expression ### Description Implements partial equality comparison for Expression. ### Methods - `eq(&self, other: &Expression) -> bool`: Tests for equality. - `ne(&self, other: &Rhs) -> bool`: Tests for inequality. ## Hash for Expression ### Description Implements hashing for the Expression type. ### Methods - `hash<__H: Hasher>(&self, state: &mut __H)`: Feeds this value into the given `Hasher`. - `hash_slice(data: &[Self], state: &mut H)`: Feeds a slice of this type into the given `Hasher`. ``` -------------------------------- ### into Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Converts a value into another type by calling the corresponding `From` implementation. ```APIDOC ## fn into(self) -> U ### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ### Signature `fn into(self) -> U` ``` -------------------------------- ### Service Operation Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Constructs a Service operation, which executes a SPARQL service. ```rust pub fn service(inner: Self, name: NamedNodePattern, silent: bool) -> Self { Self::Service { inner: Box::new(inner), name, silent, } } ``` -------------------------------- ### Create Project Operation Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Translates a Project graph pattern, which restricts the variables projected from the inner pattern. ```rust GraphPattern::Project { inner, variables } => Self::Project { inner: Box::new(inner.as_ref().into()), variables: variables.clone(), } ``` -------------------------------- ### Parse SPARQL Variable from String Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Variable.html Shows how to parse a string into a Variable using the FromStr trait. It validates the input against SPARQL grammar. Requires the oxrdf crate. ```rust use oxrdf::Variable; use std::str::FromStr; assert_eq!(Variable::from_str("$foo")?, Variable::new("foo")?); ``` -------------------------------- ### Check Suitability for For Loop Join Source: https://docs.rs/sparopt/latest/src/sparopt/optimizer.rs.html Determines if a given graph pattern is suitable for a for-loop join optimization. This is a placeholder function with a TODO comment, indicating further refinement is needed. ```rust fn is_fit_for_for_loop_join( pattern: &GraphPattern, global_input_types: &VariableTypes, entry_types: &VariableTypes, ) -> bool { // TODO: think more about it match pattern { GraphPattern::Values { .. } | GraphPattern::QuadPattern { .. } | GraphPattern::Path { .. } ``` -------------------------------- ### NamedNode::as_str Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Returns a string slice view of the IRI. ```APIDOC ## NamedNode::as_str ### Description Returns a string slice view of the IRI contained within the `NamedNode`. ### Signature `pub fn as_str(&self) -> &str` ### Returns A string slice (`&str`) representing the IRI. ``` -------------------------------- ### Convert GraphPattern to AlGraphPattern (QuadPattern) Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Converts a GraphPattern::QuadPattern into an AlGraphPattern::Bgp or AlGraphPattern::Graph. If a graph name is present, it wraps the Bgp in a Graph pattern. ```rust impl From<&GraphPattern> for AlGraphPattern { fn from(pattern: &GraphPattern) -> Self { match pattern { GraphPattern::QuadPattern { subject, predicate, object, graph_name, } => { let pattern = Self::Bgp { patterns: vec![TriplePattern { subject: subject.clone().into(), predicate: predicate.clone(), object: object.clone().into(), }], }; if let Some(graph_name) = graph_name { Self::Graph { inner: Box::new(pattern), name: graph_name.clone(), } } else { pattern } } GraphPattern::Path { subject, path, object, graph_name, } => { let pattern = Self::Path { subject: subject.clone().into(), path: path.clone(), object: object.clone().into(), }; if let Some(graph_name) = graph_name { Self::Graph { inner: Box::new(pattern), name: graph_name.clone(), } } else { pattern } } GraphPattern::Graph { graph_name } => Self::Graph { inner: Box::new(AlGraphPattern::Bgp { patterns: Vec::new(), }), name: graph_name.clone(), }, GraphPattern::Join { left, right, .. } => { match (left.as_ref().into(), right.as_ref().into()) { ``` -------------------------------- ### Variable Conversions Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Variable.html Illustrates conversions from Variable to other types like NamedNodePattern, GroundTermPattern, and Expression. ```APIDOC ## Variable Conversions ### Description Demonstrates conversions from `Variable` to other SPARQL-related types. ### Trait Implementations #### `impl From for NamedNodePattern` Converts a `Variable` into a `NamedNodePattern`. #### `impl From for GroundTermPattern` Converts a `Variable` into a `GroundTermPattern`. #### `impl From for Expression` Converts a `Variable` into an `Expression`. #### `impl<'a> From> for Variable` Converts a `VariableRef` into an owned `Variable`. ``` -------------------------------- ### Variable Parsing Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Variable.html Shows how to parse a string into a Variable using the FromStr trait. ```APIDOC ## Variable Parsing ### Description Parses a variable from its SPARQL serialization using the `FromStr` trait. ### Usage Example ```rust use oxrdf::Variable; use std::str::FromStr; // Parse a string into a Variable let parsed_var = Variable::from_str("$foo").expect("Failed to parse variable"); let expected_var = Variable::new("foo").expect("Invalid variable name"); assert_eq!(parsed_var, expected_var); ``` ### Trait Implementation #### `impl FromStr for Variable` ##### `from_str(s: &str) -> Result::Err>` Parses a variable from its SPARQL serialization. ##### `type Err = TermParseError` The associated error which can be returned from parsing. ``` -------------------------------- ### clone_into Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Uses borrowed data to replace owned data, typically by cloning. ```APIDOC ## fn clone_into(&self, target: &mut T) ### Description Uses borrowed data to replace owned data, usually by cloning. ### Signature `fn clone_into(&self, target: &mut T)` ``` -------------------------------- ### Join GraphPatterns Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Combines two GraphPatterns using a specified JoinAlgorithm. Returns an empty pattern if either input pattern is empty. Returns the non-empty pattern if the other is an empty singleton. ```rust pub fn join(left: Self, right: Self, algorithm: JoinAlgorithm) -> Self { if left.is_empty() || right.is_empty() { return Self::empty(); } if left.is_empty_singleton() { return right; } if right.is_empty_singleton() { return left; } Self::Join { left: Box::new(left), right: Box::new(right), algorithm, } } ``` -------------------------------- ### Reduce Graph Patterns with Optimal Join Order Source: https://docs.rs/sparopt/latest/src/sparopt/optimizer.rs.html Reduces a list of graph patterns into a single pattern by iteratively joining them. It selects the join order based on estimated graph pattern sizes to optimize performance. ```rust .into_iter() .reduce(|left, right| { let keys = join_key_variables( &infer_graph_pattern_types(&left, input_types.clone()), &infer_graph_pattern_types(&right, input_types.clone()), input_types, ); if estimate_graph_pattern_size(&left, input_types) <= estimate_graph_pattern_size(&right, input_types) { GraphPattern::join( left, right, JoinAlgorithm::HashBuildLeftProbeRight { keys }, ) } else { GraphPattern::join( right, left, JoinAlgorithm::HashBuildLeftProbeRight { keys }, ) } }) .unwrap() ``` -------------------------------- ### TryFrom for GroundTerm Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.GroundTerm.html Attempts to convert a Term into a GroundTerm. This operation may fail and return an error. ```APIDOC ### impl TryFrom for GroundTerm #### type Error = () #### fn try_from( term: Term, ) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Converting SPARQL Join to Graph Patterns Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Recursively converts SPARQL Join patterns into internal Join operations. Both left and right sides are converted using `from_sparql_algebra`, with a default Join algorithm applied. ```rust AlGraphPattern::Join { left, right } => Self::Join { left: Box::new(Self::from_sparql_algebra(left, graph_name, blank_nodes)), right: Box::new(Self::from_sparql_algebra(right, graph_name, blank_nodes)), algorithm: JoinAlgorithm::default(), } ``` -------------------------------- ### NamedNode::new Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.NamedNode.html Builds and validates an RDF IRI. This is the safe constructor for creating NamedNode instances from potentially untrusted input. ```APIDOC ## NamedNode::new ### Description Builds and validates an RDF IRI. This is the safe constructor for creating NamedNode instances from potentially untrusted input. ### Signature `pub fn new(iri: impl Into) -> Result` ### Parameters * `iri`: A string or type that can be converted into a String, representing the IRI to be validated and built. ### Returns A `Result` containing a `NamedNode` on success, or an `IriParseError` if the IRI is invalid. ``` -------------------------------- ### Convert GroundTriple to Expression (SPARQL 1.2) Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Converts a GroundTriple into an Expression using the Function::Triple call. Requires the 'sparql-12' feature. ```rust #[cfg(feature = "sparql-12")] impl From for Expression { fn from(value: GroundTriple) -> Self { Self::FunctionCall( Function::Triple, vec![ value.subject.into(), value.predicate.into(), value.object.into(), ], ) } } ``` -------------------------------- ### Convert GroundTriplePattern to Expression (SPARQL 1.2) Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Converts a GroundTriplePattern into an Expression using the Function::Triple call. Requires the 'sparql-12' feature. ```rust #[cfg(feature = "sparql-12")] impl From for Expression { fn from(value: GroundTriplePattern) -> Self { Self::FunctionCall( Function::Triple, vec![ value.subject.into(), value.predicate.into(), value.object.into(), ], ) } } ``` -------------------------------- ### Expression Cloning and Debugging Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Documentation for cloning and debugging capabilities of the Expression type. ```APIDOC ## Clone for Expression ### Description Provides methods for cloning an Expression. ### Methods - `clone(&self) -> Expression`: Returns a duplicate of the value. - `clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. ## Debug for Expression ### Description Implements the Debug trait for formatted output of Expression. ### Method `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. ``` -------------------------------- ### Order Pair for Hashing Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Orders two hashable items to ensure consistent ordering for hashing purposes. ```rust fn order_pair(a: T, b: T) -> (T, T) { if hash(&a) <= hash(&b) { (a, b) } else { (b, a) } } ``` -------------------------------- ### Expression Arithmetic Operations Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Provides documentation for the arithmetic operations supported by the Expression type, including addition, subtraction, multiplication, division, and negation. ```APIDOC ## Add for Expression ### Description Implements the addition operation for Expression. ### Method `add(self, rhs: Self) -> Expression` ## Sub for Expression ### Description Implements the subtraction operation for Expression. ### Method `sub(self, rhs: Self) -> Expression` ## Mul for Expression ### Description Implements the multiplication operation for Expression. ### Method `mul(self, rhs: Self) -> Expression` ## Div for Expression ### Description Implements the division operation for Expression. ### Method `div(self, rhs: Self) -> Expression` ## Neg for Expression ### Description Implements the unary negation operation for Expression. ### Method `neg(self) -> Expression` ``` -------------------------------- ### Expression Construction Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Methods for creating new expressions. ```APIDOC ## Expression Construction ### `or_all(args: impl IntoIterator) -> Self` Creates an expression that is true if any of the provided arguments are true. ### `and_all(args: impl IntoIterator) -> Self` Creates an expression that is true if all of the provided arguments are true. ### `equal(left: Self, right: Self) -> Self` Creates an expression that checks for equality between two operands. ### `same_term(left: Self, right: Self) -> Self` Creates an expression that checks if two operands are the same term. ### `greater(left: Self, right: Self) -> Self` Creates an expression that checks if the left operand is greater than the right operand. ### `greater_or_equal(left: Self, right: Self) -> Self` Creates an expression that checks if the left operand is greater than or equal to the right operand. ### `less(left: Self, right: Self) -> Self` Creates an expression that checks if the left operand is less than the right operand. ### `less_or_equal(left: Self, right: Self) -> Self` Creates an expression that checks if the left operand is less than or equal to the right operand. ### `unary_plus(inner: Self) -> Self` Creates an expression representing the unary plus of an operand. ### `exists(inner: GraphPattern) -> Self` Creates an expression that checks for the existence of a graph pattern. ### `if_cond(cond: Self, then: Self, els: Self) -> Self` Creates a conditional expression that evaluates `then` if `cond` is true, otherwise evaluates `els`. ### `coalesce(args: Vec) -> Self` Creates an expression that returns the first non-null value from a list of arguments. ### `call(name: Function, args: Vec) -> Self` Creates an expression that calls a named function with provided arguments. ``` -------------------------------- ### Create SameTerm SPARQL Expression Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Creates a SameTerm expression for SPARQL. Similar to Equal, it handles NamedNode and Literal comparisons directly and ensures consistent operand ordering for other types. ```rust pub fn same_term(left: Self, right: Self) -> Self { match (left, right) { (Self::NamedNode(left), Self::NamedNode(right)) => (left == right).into(), (Self::Literal(left), Self::Literal(right)) if left == right => true.into(), (left, right) => { let (left, right) = order_pair(left, right); Self::SameTerm(Box::new(left), Box::new(right)) } } } ``` -------------------------------- ### Default Join Graph Pattern (No sep-0006) Source: https://docs.rs/sparopt/latest/src/sparopt/optimizer.rs.html Constructs a hash build join operation. This snippet is used when the 'sep-0006' feature is not enabled. ```rust output = GraphPattern::join( output, next, JoinAlgorithm::HashBuildLeftProbeRight { keys: join_key_variables( &output_types, &to_reorder_types[next_id], input_types, ), }, ); ``` -------------------------------- ### Converting SPARQL Graph to Graph Patterns Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Converts a SPARQL Graph pattern into an internal Graph pattern. The inner pattern is recursively converted, and the graph name is preserved. ```rust AlGraphPattern::Graph { inner, name } => Self::Graph { inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)), name: Self::term_pattern_from_algebra(name, blank_nodes), } ``` -------------------------------- ### PartialEq and Eq Implementations for LeftJoinAlgorithm Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.LeftJoinAlgorithm.html Implements equality comparison for LeftJoinAlgorithm. ```rust fn eq(&self, other: &LeftJoinAlgorithm) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### impl VZip for T Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Expression.html Provides a method for zipping with a multi-lane vector. ```APIDOC ## fn vzip(self) -> V ### Description Zips the current value with a multi-lane vector. ### Method fn ### Parameters None ### Response #### Success Response - **V**: The zipped multi-lane vector. ``` -------------------------------- ### Left Join Algorithm Enum Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Defines the HashBuildRightProbeLeft left join algorithm. Used in GraphPattern::LeftJoin. ```rust pub enum LeftJoinAlgorithm { HashBuildRightProbeLeft { keys: Vec }, } impl Default for LeftJoinAlgorithm { fn default() -> Self { Self::HashBuildRightProbeLeft { keys: Vec::default(), } } } ``` -------------------------------- ### Create LessOrEqual SPARQL Expression Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Constructs a LessOrEqual expression for SPARQL, representing the '<=' operator. ```rust pub fn less_or_equal(left: Self, right: Self) -> Self { Self::LessOrEqual(Box::new(left), Box::new(right)) } ``` -------------------------------- ### Create Equal SPARQL Expression Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Creates an Equal expression for SPARQL. It handles NamedNode and Literal comparisons directly, otherwise creates a generic Equal expression, ensuring consistent ordering of operands. ```rust pub fn equal(left: Self, right: Self) -> Self { match (left, right) { (Self::NamedNode(left), Self::NamedNode(right)) => (left == right).into(), (Self::Literal(left), Self::Literal(right)) if left == right => true.into(), (left, right) => { let (left, right) = order_pair(left, right); Self::Equal(Box::new(left), Box::new(right)) } } } ``` -------------------------------- ### Try Convert NamedNodePattern to NamedNode Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.NamedNodePattern.html Demonstrates the attempt to convert a NamedNodePattern back into a NamedNode. This operation can fail if the pattern is actually a Variable, returning an error. ```rust fn try_from( pattern: NamedNodePattern, ) -> Result>::Error> ``` -------------------------------- ### Literal Destructuring Source: https://docs.rs/sparopt/latest/sparopt/algebra/struct.Literal.html Shows how to extract all components of a literal at once. ```APIDOC ## Literal Destructuring ### Description This method allows you to extract all components of a literal in a single operation. ### Method #### `destruct(self) -> (String, Option, Option, Option)` (Available on `rdf-12` feature only) Extracts the value, datatype, language tag, and base direction from the literal. ``` -------------------------------- ### Converting SPARQL Path to Graph Patterns Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Converts a SPARQL Path pattern into an internal Path representation. It transforms subject and object terms using `term_pattern_from_algebra` and includes the graph name if available. ```rust AlGraphPattern::Path { subject, path, object, } => Self::Path { subject: Self::term_pattern_from_algebra(subject, blank_nodes), path: path.clone(), object: Self::term_pattern_from_algebra(object, blank_nodes), graph_name: graph_name.cloned(), } ``` -------------------------------- ### Try Convert Term to GroundTerm Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.GroundTerm.html Attempts to convert a generic Term into a GroundTerm. This operation can fail, returning an error. ```rust impl TryFrom for GroundTerm { type Error = () fn try_from( term: Term, ) -> Result>::Error> } ``` -------------------------------- ### Project Operation Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Constructs a Project operation, which selects specific variables from an inner operation. ```rust pub fn project(inner: Self, variables: Vec) -> Self { Self::Project { inner: Box::new(inner), variables, } } ``` -------------------------------- ### try_into Source: https://docs.rs/sparopt/latest/sparopt/algebra/enum.Function.html Attempts to convert a value into another type, returning a `Result`. ```APIDOC ## fn try_into(self) -> Result>::Error> ### Description Performs the conversion. ### Signature `fn try_into(self) -> Result>::Error>` ``` -------------------------------- ### Create Less SPARQL Expression Source: https://docs.rs/sparopt/latest/src/sparopt/algebra.rs.html Constructs a Less expression for SPARQL, representing the '<' operator. ```rust pub fn less(left: Self, right: Self) -> Self { Self::Less(Box::new(left), Box::new(right)) } ```