Applies more clippy lints

pull/10/head
Tpt 6 years ago
parent fa270a220c
commit 071b3934b7
  1. 3
      clippy.toml
  2. 33
      lib/src/lib.rs
  3. 2
      lib/src/model/blank_node.rs
  4. 30
      lib/src/model/literal.rs
  5. 2
      lib/src/model/named_node.rs
  6. 16
      lib/src/rio/ntriples/mod.rs
  7. 16
      lib/src/rio/turtle/mod.rs
  8. 275
      lib/src/sparql/algebra.rs
  9. 19
      lib/src/sparql/eval.rs
  10. 4
      lib/src/sparql/mod.rs
  11. 22
      lib/src/sparql/parser.rs
  12. 46
      lib/src/sparql/plan.rs
  13. 64
      lib/src/sparql/sparql_grammar.rustpeg
  14. 13
      lib/src/sparql/xml_results.rs
  15. 8
      lib/src/store/encoded.rs
  16. 18
      lib/src/store/memory.rs
  17. 2
      lib/src/store/mod.rs
  18. 28
      lib/src/store/numeric_encoder.rs
  19. 28
      lib/src/store/rocksdb.rs
  20. 4
      lib/src/utils.rs
  21. 17
      python/src/lib.rs

@ -0,0 +1,3 @@
cyclomatic-complexity-threshold = 50
too-many-arguments-threshold = 10
type-complexity-threshold = 500

@ -1,3 +1,36 @@
#![cfg_attr(
feature = "cargo-clippy",
warn(
cast_possible_truncation,
cast_possible_wrap,
cast_precision_loss,
cast_sign_loss,
default_trait_access,
empty_enum,
enum_glob_use,
expl_impl_clone_on_copy,
explicit_into_iter_loop,
filter_map,
if_not_else,
inline_always,
invalid_upcast_comparisons,
items_after_statements,
linkedlist,
//TODO match_same_arms,
maybe_infinite_iter,
mut_mut,
needless_continue,
option_map_unwrap_or,
//TODO option_map_unwrap_or_else,
pub_enum_variant_names,
replace_consts,
result_map_unwrap_or_else,
//TODO single_match_else,
string_add_assign,
unicode_not_nfc
)
)]
extern crate byteorder;
#[macro_use]
extern crate error_chain;

@ -32,7 +32,7 @@ impl fmt::Display for BlankNode {
impl Default for BlankNode {
/// Builds a new RDF [blank node](https://www.w3.org/TR/rdf11-concepts/#dfn-blank-node) with a unique id
fn default() -> Self {
BlankNode { id: Uuid::new_v4() }
Self { id: Uuid::new_v4() }
}
}

@ -107,16 +107,15 @@ impl Literal {
/// The literal [lexical form](https://www.w3.org/TR/rdf11-concepts/#dfn-lexical-form)
pub fn value(&self) -> Cow<String> {
match self.0 {
LiteralContent::SimpleLiteral(ref value) | LiteralContent::String(ref value) => {
Cow::Borrowed(value)
}
LiteralContent::LanguageTaggedString { ref value, .. } => Cow::Borrowed(value),
LiteralContent::SimpleLiteral(ref value)
| LiteralContent::String(ref value)
| LiteralContent::LanguageTaggedString { ref value, .. }
| LiteralContent::TypedLiteral { ref value, .. } => Cow::Borrowed(value),
LiteralContent::Boolean(value) => Cow::Owned(value.to_string()),
LiteralContent::Float(value) => Cow::Owned(value.to_string()),
LiteralContent::Double(value) => Cow::Owned(value.to_string()),
LiteralContent::Integer(value) => Cow::Owned(value.to_string()),
LiteralContent::Decimal(value) => Cow::Owned(value.to_string()),
LiteralContent::TypedLiteral { ref value, .. } => Cow::Borrowed(value),
}
}
@ -152,8 +151,7 @@ impl Literal {
/// or have been created by `Literal::new_simple_literal`.
pub fn is_plain(&self) -> bool {
match self.0 {
LiteralContent::SimpleLiteral(_) => true,
LiteralContent::LanguageTaggedString { .. } => true,
LiteralContent::SimpleLiteral(_) | LiteralContent::LanguageTaggedString { .. } => true,
_ => false,
}
}
@ -201,8 +199,7 @@ impl Literal {
/// Checks if the literal has the datatype [xsd:decimal](http://www.w3.org/2001/XMLSchema#decimal) or one of its sub datatype and is valid
pub fn is_decimal(&self) -> bool {
match self.0 {
LiteralContent::Integer(_) => true,
LiteralContent::Decimal(_) => true,
LiteralContent::Integer(_) | LiteralContent::Decimal(_) => true,
_ => false,
}
}
@ -213,13 +210,12 @@ impl Literal {
LiteralContent::SimpleLiteral(ref value) | LiteralContent::String(ref value) => {
Some(!value.is_empty())
}
LiteralContent::LanguageTaggedString { .. } => None,
LiteralContent::Boolean(value) => Some(value),
LiteralContent::Float(value) => Some(!value.is_zero()),
LiteralContent::Double(value) => Some(!value.is_zero()),
LiteralContent::Integer(value) => Some(!value.is_zero()),
LiteralContent::Decimal(value) => Some(!value.is_zero()),
LiteralContent::TypedLiteral { .. } => None,
_ => None,
}
}
@ -326,37 +322,37 @@ impl From<i128> for Literal {
impl From<i64> for Literal {
fn from(value: i64) -> Self {
Literal(LiteralContent::Integer(value as i128))
Literal(LiteralContent::Integer(value.into()))
}
}
impl From<i32> for Literal {
fn from(value: i32) -> Self {
Literal(LiteralContent::Integer(value as i128))
Literal(LiteralContent::Integer(value.into()))
}
}
impl From<i16> for Literal {
fn from(value: i16) -> Self {
Literal(LiteralContent::Integer(value as i128))
Literal(LiteralContent::Integer(value.into()))
}
}
impl From<u64> for Literal {
fn from(value: u64) -> Self {
Literal(LiteralContent::Integer(value as i128))
Literal(LiteralContent::Integer(value.into()))
}
}
impl From<u32> for Literal {
fn from(value: u32) -> Self {
Literal(LiteralContent::Integer(value as i128))
Literal(LiteralContent::Integer(value.into()))
}
}
impl From<u16> for Literal {
fn from(value: u16) -> Self {
Literal(LiteralContent::Integer(value as i128))
Literal(LiteralContent::Integer(value.into()))
}
}

@ -65,6 +65,6 @@ impl FromStr for NamedNode {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Ok(NamedNode::new(Url::parse(s)?))
Ok(Self::new(Url::parse(s)?))
}
}

@ -1,13 +1,15 @@
///Implements https://www.w3.org/TR/n-triples/
mod grammar {
#![allow(unknown_lints)]
#![allow(
suspicious_else_formatting,
len_zero,
single_match,
unit_arg,
naive_bytecount
#![cfg_attr(
feature = "cargo-clippy",
allow(
suspicious_else_formatting,
len_zero,
single_match,
unit_arg,
naive_bytecount
)
)]
use rio::utils::unescape_characters;

@ -1,13 +1,15 @@
/// Implements https://www.w3.org/TR/turtle/
mod grammar {
#![allow(unknown_lints)]
#![allow(
suspicious_else_formatting,
len_zero,
single_match,
unit_arg,
naive_bytecount
#![cfg_attr(
feature = "cargo-clippy",
allow(
suspicious_else_formatting,
len_zero,
single_match,
unit_arg,
naive_bytecount
)
)]
use model::*;

@ -181,7 +181,7 @@ impl StaticBindings {
impl Default for StaticBindings {
fn default() -> Self {
StaticBindings {
Self {
variables: Vec::default(),
values: Vec::default(),
}
@ -401,24 +401,24 @@ impl<'a> fmt::Display for SparqlTripleOrPathPattern<'a> {
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)]
pub enum Expression {
ConstantExpression(TermOrVariable),
OrExpression(Box<Expression>, Box<Expression>),
AndExpression(Box<Expression>, Box<Expression>),
EqualExpression(Box<Expression>, Box<Expression>),
NotEqualExpression(Box<Expression>, Box<Expression>),
GreaterExpression(Box<Expression>, Box<Expression>),
GreaterOrEqExpression(Box<Expression>, Box<Expression>),
LowerExpression(Box<Expression>, Box<Expression>),
LowerOrEqExpression(Box<Expression>, Box<Expression>),
InExpression(Box<Expression>, Vec<Expression>),
NotInExpression(Box<Expression>, Vec<Expression>),
AddExpression(Box<Expression>, Box<Expression>),
SubExpression(Box<Expression>, Box<Expression>),
MulExpression(Box<Expression>, Box<Expression>),
DivExpression(Box<Expression>, Box<Expression>),
UnaryPlusExpression(Box<Expression>),
UnaryMinusExpression(Box<Expression>),
UnaryNotExpression(Box<Expression>),
Constant(TermOrVariable),
Or(Box<Expression>, Box<Expression>),
And(Box<Expression>, Box<Expression>),
Equal(Box<Expression>, Box<Expression>),
NotEqual(Box<Expression>, Box<Expression>),
Greater(Box<Expression>, Box<Expression>),
GreaterOrEq(Box<Expression>, Box<Expression>),
Lower(Box<Expression>, Box<Expression>),
LowerOrEq(Box<Expression>, Box<Expression>),
In(Box<Expression>, Vec<Expression>),
NotIn(Box<Expression>, Vec<Expression>),
Add(Box<Expression>, Box<Expression>),
Sub(Box<Expression>, Box<Expression>),
Mul(Box<Expression>, Box<Expression>),
Div(Box<Expression>, Box<Expression>),
UnaryPlus(Box<Expression>),
UnaryMinus(Box<Expression>),
UnaryNot(Box<Expression>),
StrFunctionCall(Box<Expression>),
LangFunctionCall(Box<Expression>),
LangMatchesFunctionCall(Box<Expression>, Box<Expression>),
@ -480,16 +480,16 @@ pub enum Expression {
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Expression::ConstantExpression(t) => write!(f, "{}", t),
Expression::OrExpression(a, b) => write!(f, "({} || {})", a, b),
Expression::AndExpression(a, b) => write!(f, "({} && {})", a, b),
Expression::EqualExpression(a, b) => write!(f, "({} = {})", a, b),
Expression::NotEqualExpression(a, b) => write!(f, "({} != {})", a, b),
Expression::GreaterExpression(a, b) => write!(f, "({} > {})", a, b),
Expression::GreaterOrEqExpression(a, b) => write!(f, "({} >= {})", a, b),
Expression::LowerExpression(a, b) => write!(f, "({} < {})", a, b),
Expression::LowerOrEqExpression(a, b) => write!(f, "({} <= {})", a, b),
Expression::InExpression(a, b) => write!(
Expression::Constant(t) => write!(f, "{}", t),
Expression::Or(a, b) => write!(f, "({} || {})", a, b),
Expression::And(a, b) => write!(f, "({} && {})", a, b),
Expression::Equal(a, b) => write!(f, "({} = {})", a, b),
Expression::NotEqual(a, b) => write!(f, "({} != {})", a, b),
Expression::Greater(a, b) => write!(f, "({} > {})", a, b),
Expression::GreaterOrEq(a, b) => write!(f, "({} >= {})", a, b),
Expression::Lower(a, b) => write!(f, "({} < {})", a, b),
Expression::LowerOrEq(a, b) => write!(f, "({} <= {})", a, b),
Expression::In(a, b) => write!(
f,
"({} IN ({}))",
a,
@ -498,7 +498,7 @@ impl fmt::Display for Expression {
.collect::<Vec<String>>()
.join(", ")
),
Expression::NotInExpression(a, b) => write!(
Expression::NotIn(a, b) => write!(
f,
"({} NOT IN ({}))",
a,
@ -507,13 +507,13 @@ impl fmt::Display for Expression {
.collect::<Vec<String>>()
.join(", ")
),
Expression::AddExpression(a, b) => write!(f, "{} + {}", a, b),
Expression::SubExpression(a, b) => write!(f, "{} - {}", a, b),
Expression::MulExpression(a, b) => write!(f, "{} * {}", a, b),
Expression::DivExpression(a, b) => write!(f, "{} / {}", a, b),
Expression::UnaryPlusExpression(e) => write!(f, "+{}", e),
Expression::UnaryMinusExpression(e) => write!(f, "-{}", e),
Expression::UnaryNotExpression(e) => write!(f, "!{}", e),
Expression::Add(a, b) => write!(f, "{} + {}", a, b),
Expression::Sub(a, b) => write!(f, "{} - {}", a, b),
Expression::Mul(a, b) => write!(f, "{} * {}", a, b),
Expression::Div(a, b) => write!(f, "{} / {}", a, b),
Expression::UnaryPlus(e) => write!(f, "+{}", e),
Expression::UnaryMinus(e) => write!(f, "-{}", e),
Expression::UnaryNot(e) => write!(f, "!{}", e),
Expression::StrFunctionCall(e) => write!(f, "STR({})", e),
Expression::LangFunctionCall(e) => write!(f, "LANG({})", e),
Expression::LangMatchesFunctionCall(a, b) => write!(f, "LANGMATCHES({}, {})", a, b),
@ -542,10 +542,14 @@ impl fmt::Display for Expression {
.map(|cv| write!(f, "SUBSTR({}, {}, {})", a, b, cv))
.unwrap_or_else(|| write!(f, "SUBSTR({}, {})", a, b)),
Expression::StrLenFunctionCall(e) => write!(f, "STRLEN({})", e),
Expression::ReplaceFunctionCall(a, b, c, d) => d
.as_ref()
.map(|dv| write!(f, "REPLACE({}, {}, {}, {})", a, b, c, dv))
.unwrap_or_else(|| write!(f, "REPLACE({}, {}, {})", a, b, c)),
Expression::ReplaceFunctionCall(arg, pattern, replacement, flags) => match flags {
Some(flags) => write!(
f,
"REPLACE({}, {}, {}, {})",
arg, pattern, replacement, flags
),
None => write!(f, "REPLACE({}, {}, {})", arg, pattern, replacement),
},
Expression::UCaseFunctionCall(e) => write!(f, "UCASE({})", e),
Expression::LCaseFunctionCall(e) => write!(f, "LCASE({})", e),
Expression::EncodeForURIFunctionCall(e) => write!(f, "ENCODE_FOR_URI({})", e),
@ -585,10 +589,10 @@ impl fmt::Display for Expression {
Expression::IsBlankFunctionCall(e) => write!(f, "isBLANK({})", e),
Expression::IsLiteralFunctionCall(e) => write!(f, "isLITERAL({})", e),
Expression::IsNumericFunctionCall(e) => write!(f, "isNUMERIC({})", e),
Expression::RegexFunctionCall(a, b, c) => c
.as_ref()
.map(|cv| write!(f, "REGEX({}, {}, {})", a, b, cv))
.unwrap_or_else(|| write!(f, "REGEX({}, {})", a, b)),
Expression::RegexFunctionCall(text, pattern, flags) => match flags {
Some(flags) => write!(f, "REGEX({}, {}, {})", text, pattern, flags),
None => write!(f, "REGEX({}, {})", text, pattern),
},
Expression::CustomFunctionCall(iri, args) => write!(
f,
"{}({})",
@ -605,19 +609,19 @@ impl fmt::Display for Expression {
impl From<NamedNode> for Expression {
fn from(p: NamedNode) -> Self {
Expression::ConstantExpression(p.into())
Expression::Constant(p.into())
}
}
impl From<Literal> for Expression {
fn from(p: Literal) -> Self {
Expression::ConstantExpression(p.into())
Expression::Constant(p.into())
}
}
impl From<Variable> for Expression {
fn from(v: Variable) -> Self {
Expression::ConstantExpression(v.into())
Expression::Constant(v.into())
}
}
@ -626,47 +630,47 @@ struct SparqlExpression<'a>(&'a Expression);
impl<'a> fmt::Display for SparqlExpression<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Expression::ConstantExpression(t) => write!(f, "{}", t),
Expression::OrExpression(a, b) => write!(
Expression::Constant(t) => write!(f, "{}", t),
Expression::Or(a, b) => write!(
f,
"({} || {})",
SparqlExpression(&*a),
SparqlExpression(&*b)
),
Expression::AndExpression(a, b) => write!(
Expression::And(a, b) => write!(
f,
"({} && {})",
SparqlExpression(&*a),
SparqlExpression(&*b)
),
Expression::EqualExpression(a, b) => {
Expression::Equal(a, b) => {
write!(f, "({} = {})", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::NotEqualExpression(a, b) => write!(
Expression::NotEqual(a, b) => write!(
f,
"({} != {})",
SparqlExpression(&*a),
SparqlExpression(&*b)
),
Expression::GreaterExpression(a, b) => {
Expression::Greater(a, b) => {
write!(f, "({} > {})", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::GreaterOrEqExpression(a, b) => write!(
Expression::GreaterOrEq(a, b) => write!(
f,
"({} >= {})",
SparqlExpression(&*a),
SparqlExpression(&*b)
),
Expression::LowerExpression(a, b) => {
Expression::Lower(a, b) => {
write!(f, "({} < {})", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::LowerOrEqExpression(a, b) => write!(
Expression::LowerOrEq(a, b) => write!(
f,
"({} <= {})",
SparqlExpression(&*a),
SparqlExpression(&*b)
),
Expression::InExpression(a, b) => write!(
Expression::In(a, b) => write!(
f,
"({} IN ({}))",
a,
@ -675,7 +679,7 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
.collect::<Vec<String>>()
.join(", ")
),
Expression::NotInExpression(a, b) => write!(
Expression::NotIn(a, b) => write!(
f,
"({} NOT IN ({}))",
a,
@ -684,21 +688,21 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
.collect::<Vec<String>>()
.join(", ")
),
Expression::AddExpression(a, b) => {
Expression::Add(a, b) => {
write!(f, "{} + {}", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::SubExpression(a, b) => {
Expression::Sub(a, b) => {
write!(f, "{} - {}", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::MulExpression(a, b) => {
Expression::Mul(a, b) => {
write!(f, "{} * {}", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::DivExpression(a, b) => {
Expression::Div(a, b) => {
write!(f, "{} / {}", SparqlExpression(&*a), SparqlExpression(&*b))
}
Expression::UnaryPlusExpression(e) => write!(f, "+{}", SparqlExpression(&*e)),
Expression::UnaryMinusExpression(e) => write!(f, "-{}", SparqlExpression(&*e)),
Expression::UnaryNotExpression(e) => match e.as_ref() {
Expression::UnaryPlus(e) => write!(f, "+{}", SparqlExpression(&*e)),
Expression::UnaryMinus(e) => write!(f, "-{}", SparqlExpression(&*e)),
Expression::UnaryNot(e) => match e.as_ref() {
Expression::ExistsFunctionCall(p) => {
write!(f, "NOT EXISTS {{ {} }}", SparqlGraphPattern(&*p))
}
@ -751,26 +755,23 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
)
}),
Expression::StrLenFunctionCall(e) => write!(f, "STRLEN({})", SparqlExpression(&*e)),
Expression::ReplaceFunctionCall(a, b, c, d) => d
.as_ref()
.map(|dv| {
write!(
f,
"REPLACE({}, {}, {}, {})",
SparqlExpression(&*a),
SparqlExpression(&*b),
SparqlExpression(&*c),
dv
)
}).unwrap_or_else(|| {
write!(
f,
"REPLACE({}, {}, {})",
SparqlExpression(&*a),
SparqlExpression(&*b),
SparqlExpression(&*c)
)
}),
Expression::ReplaceFunctionCall(arg, pattern, replacement, flags) => match flags {
Some(flags) => write!(
f,
"REPLACE({}, {}, {}, {})",
SparqlExpression(&*arg),
SparqlExpression(&*pattern),
SparqlExpression(&*replacement),
flags
),
None => write!(
f,
"REPLACE({}, {}, {})",
SparqlExpression(&*arg),
SparqlExpression(&*pattern),
SparqlExpression(&*replacement)
),
},
Expression::UCaseFunctionCall(e) => write!(f, "UCASE({})", SparqlExpression(&*e)),
Expression::LCaseFunctionCall(e) => write!(f, "LCASE({})", SparqlExpression(&*e)),
Expression::EncodeForURIFunctionCall(e) => {
@ -862,24 +863,21 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
Expression::IsNumericFunctionCall(e) => {
write!(f, "isNUMERIC({})", SparqlExpression(&*e))
}
Expression::RegexFunctionCall(a, b, c) => c
.as_ref()
.map(|cv| {
write!(
f,
"REGEX({}, {}, {})",
SparqlExpression(&*a),
SparqlExpression(&*b),
cv
)
}).unwrap_or_else(|| {
write!(
f,
"REGEX({}, {})",
SparqlExpression(&*a),
SparqlExpression(&*b)
)
}),
Expression::RegexFunctionCall(text, pattern, flags) => match flags {
Some(flags) => write!(
f,
"REGEX({}, {}, {})",
SparqlExpression(&*text),
SparqlExpression(&*pattern),
flags
),
None => write!(
f,
"REGEX({}, {})",
SparqlExpression(&*text),
SparqlExpression(&*pattern)
),
},
Expression::CustomFunctionCall(iri, args) => write!(
f,
"{}({})",
@ -1361,13 +1359,15 @@ impl<'a> fmt::Display for SparqlAggregation<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Aggregation::Count(e, distinct) => if *distinct {
e.as_ref()
.map(|ex| write!(f, "COUNT(DISTINCT {})", SparqlExpression(ex)))
.unwrap_or_else(|| write!(f, "COUNT(DISTINCT *)"))
if let Some(e) = e {
write!(f, "COUNT(DISTINCT {})", SparqlExpression(e))
} else {
write!(f, "COUNT(DISTINCT *)")
}
} else if let Some(e) = e {
write!(f, "COUNT({})", SparqlExpression(e))
} else {
e.as_ref()
.map(|ex| write!(f, "COUNT({})", SparqlExpression(ex)))
.unwrap_or_else(|| write!(f, "COUNT(*)"))
write!(f, "COUNT(*)")
},
Aggregation::Sum(e, distinct) => if *distinct {
write!(f, "SUM(DISTINCT {})", SparqlExpression(e))
@ -1395,26 +1395,25 @@ impl<'a> fmt::Display for SparqlAggregation<'a> {
write!(f, "SAMPLE({})", SparqlExpression(e))
},
Aggregation::GroupConcat(e, distinct, sep) => if *distinct {
sep.as_ref()
.map(|s| {
write!(
f,
"GROUP_CONCAT(DISTINCT {}; SEPARATOR = \"{}\")",
SparqlExpression(e),
s.escape()
)
})
.unwrap_or_else(|| write!(f, "GROUP_CONCAT(DISTINCT {})", SparqlExpression(e)))
if let Some(sep) = sep {
write!(
f,
"GROUP_CONCAT(DISTINCT {}; SEPARATOR = \"{}\")",
SparqlExpression(e),
sep.escape()
)
} else {
write!(f, "GROUP_CONCAT(DISTINCT {})", SparqlExpression(e))
}
} else if let Some(sep) = sep {
write!(
f,
"GROUP_CONCAT({}; SEPARATOR = \"{}\")",
SparqlExpression(e),
sep.escape()
)
} else {
sep.as_ref()
.map(|s| {
write!(
f,
"GROUP_CONCAT({}; SEPARATOR = \"{}\")",
SparqlExpression(e),
s.escape()
)
}).unwrap_or_else(|| write!(f, "GROUP_CONCAT({})", SparqlExpression(e)))
write!(f, "GROUP_CONCAT({})", SparqlExpression(e))
},
}
}
@ -1477,7 +1476,7 @@ impl DatasetSpec {
impl Add for DatasetSpec {
type Output = Self;
fn add(mut self, rhs: DatasetSpec) -> Self {
fn add(mut self, rhs: Self) -> Self {
self.default.extend_from_slice(&rhs.default);
self.named.extend_from_slice(&rhs.named);
self
@ -1502,20 +1501,20 @@ lazy_static! {
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)]
pub enum Query {
SelectQuery {
Select {
dataset: DatasetSpec,
algebra: GraphPattern,
},
ConstructQuery {
Construct {
construct: Vec<TriplePattern>,
dataset: DatasetSpec,
algebra: GraphPattern,
},
DescribeQuery {
Describe {
dataset: DatasetSpec,
algebra: GraphPattern,
},
AskQuery {
Ask {
dataset: DatasetSpec,
algebra: GraphPattern,
},
@ -1524,7 +1523,7 @@ pub enum Query {
impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Query::SelectQuery { dataset, algebra } => write!(
Query::Select { dataset, algebra } => write!(
f,
"{}",
SparqlGraphRootPattern {
@ -1532,7 +1531,7 @@ impl fmt::Display for Query {
dataset: &dataset
}
),
Query::ConstructQuery {
Query::Construct {
construct,
dataset,
algebra,
@ -1550,7 +1549,7 @@ impl fmt::Display for Query {
dataset: &EMPTY_DATASET
}
),
Query::DescribeQuery { dataset, algebra } => write!(
Query::Describe { dataset, algebra } => write!(
f,
"DESCRIBE * {} WHERE {{ {} }}",
dataset,
@ -1559,7 +1558,7 @@ impl fmt::Display for Query {
dataset: &EMPTY_DATASET
}
),
Query::AskQuery { dataset, algebra } => write!(
Query::Ask { dataset, algebra } => write!(
f,
"ASK {} WHERE {{ {} }}",
dataset,

@ -8,8 +8,8 @@ use std::collections::HashSet;
use std::iter::once;
use std::iter::Iterator;
use std::sync::Arc;
use store::encoded::EncodedQuadsStore;
use store::numeric_encoder::*;
use store::store::EncodedQuadsStore;
use Result;
type EncodedTuplesIterator = Box<dyn Iterator<Item = Result<EncodedTuple>>>;
@ -33,7 +33,7 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
pub fn evaluate(&self, query: &Query) -> Result<QueryResult> {
match query {
Query::SelectQuery { algebra, dataset } => {
Query::Select { algebra, dataset } => {
let (plan, variables) = PlanBuilder::build(&*self.store, algebra)?;
let iter = self.eval_plan(plan, vec![None; variables.len()]);
Ok(QueryResult::Bindings(self.decode_bindings(iter, variables)))
@ -300,10 +300,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
PlanExpression::Bound(v) => Some((*v >= tuple.len() && tuple[*v].is_some()).into()),
PlanExpression::IRI(e) => match self.eval_expression(e, tuple)? {
EncodedTerm::NamedNode { iri_id } => Some(EncodedTerm::NamedNode { iri_id }),
EncodedTerm::SimpleLiteral { value_id } => {
Some(EncodedTerm::NamedNode { iri_id: value_id })
}
EncodedTerm::StringLiteral { value_id } => {
EncodedTerm::SimpleLiteral { value_id }
| EncodedTerm::StringLiteral { value_id } => {
Some(EncodedTerm::NamedNode { iri_id: value_id })
}
_ => None,
@ -346,11 +344,10 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
fn to_string_id(&self, term: EncodedTerm) -> Option<u64> {
match term {
EncodedTerm::NamedNode { iri_id } => Some(iri_id),
EncodedTerm::SimpleLiteral { value_id } | EncodedTerm::StringLiteral { value_id } => {
Some(value_id)
}
EncodedTerm::LangStringLiteral { value_id, .. } => Some(value_id),
EncodedTerm::TypedLiteral { value_id, .. } => Some(value_id),
EncodedTerm::SimpleLiteral { value_id }
| EncodedTerm::StringLiteral { value_id }
| EncodedTerm::LangStringLiteral { value_id, .. }
| EncodedTerm::TypedLiteral { value_id, .. } => Some(value_id),
EncodedTerm::BooleanLiteral(value) => self
.store
.insert_bytes(if value { b"true" } else { b"false" })

@ -6,8 +6,8 @@ use sparql::algebra::QueryResult;
use sparql::eval::SimpleEvaluator;
use sparql::parser::read_sparql_query;
use std::io::Read;
use store::store::EncodedQuadsStore;
use store::store::StoreDataset;
use store::encoded::EncodedQuadsStore;
use store::encoded::StoreDataset;
use Result;
pub mod algebra;

@ -1,14 +1,16 @@
mod grammar {
#![allow(unknown_lints)]
#![allow(
suspicious_else_formatting,
len_zero,
single_match,
unit_arg,
naive_bytecount,
cyclomatic_complexity,
many_single_char_names,
type_complexity
#![cfg_attr(
feature = "cargo-clippy",
allow(
suspicious_else_formatting,
len_zero,
single_match,
unit_arg,
naive_bytecount,
cyclomatic_complexity,
many_single_char_names,
type_complexity
)
)]
use model::*;

@ -1,7 +1,7 @@
use model::vocab::xsd;
use sparql::algebra::*;
use store::encoded::EncodedQuadsStore;
use store::numeric_encoder::EncodedTerm;
use store::store::EncodedQuadsStore;
use Result;
pub type EncodedTuple = Vec<Option<EncodedTerm>>;
@ -293,67 +293,67 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
variables: &mut Vec<Variable>,
) -> Result<PlanExpression> {
Ok(match expression {
Expression::ConstantExpression(t) => match t {
Expression::Constant(t) => match t {
TermOrVariable::Term(t) => {
PlanExpression::Constant(self.store.encoder().encode_term(t)?)
}
TermOrVariable::Variable(v) => PlanExpression::Variable(variable_key(variables, v)),
},
Expression::OrExpression(a, b) => PlanExpression::Or(
Expression::Or(a, b) => PlanExpression::Or(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::AndExpression(a, b) => PlanExpression::And(
Expression::And(a, b) => PlanExpression::And(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::EqualExpression(a, b) => PlanExpression::Equal(
Expression::Equal(a, b) => PlanExpression::Equal(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::NotEqualExpression(a, b) => PlanExpression::NotEqual(
Expression::NotEqual(a, b) => PlanExpression::NotEqual(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::GreaterExpression(a, b) => PlanExpression::Greater(
Expression::Greater(a, b) => PlanExpression::Greater(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::GreaterOrEqExpression(a, b) => PlanExpression::GreaterOrEq(
Expression::GreaterOrEq(a, b) => PlanExpression::GreaterOrEq(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::LowerExpression(a, b) => PlanExpression::Lower(
Expression::Lower(a, b) => PlanExpression::Lower(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::LowerOrEqExpression(a, b) => PlanExpression::LowerOrEq(
Expression::LowerOrEq(a, b) => PlanExpression::LowerOrEq(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::AddExpression(a, b) => PlanExpression::Add(
Expression::Add(a, b) => PlanExpression::Add(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::SubExpression(a, b) => PlanExpression::Sub(
Expression::Sub(a, b) => PlanExpression::Sub(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::MulExpression(a, b) => PlanExpression::Mul(
Expression::Mul(a, b) => PlanExpression::Mul(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::DivExpression(a, b) => PlanExpression::Div(
Expression::Div(a, b) => PlanExpression::Div(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
),
Expression::UnaryPlusExpression(e) => {
Expression::UnaryPlus(e) => {
PlanExpression::UnaryPlus(Box::new(self.build_for_expression(e, variables)?))
}
Expression::UnaryMinusExpression(e) => {
Expression::UnaryMinus(e) => {
PlanExpression::UnaryMinus(Box::new(self.build_for_expression(e, variables)?))
}
Expression::UnaryNotExpression(e) => {
Expression::UnaryNot(e) => {
PlanExpression::UnaryNot(Box::new(self.build_for_expression(e, variables)?))
}
Expression::StrFunctionCall(e) => {
@ -393,11 +393,11 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
Expression::IsNumericFunctionCall(e) => {
PlanExpression::IsNumeric(Box::new(self.build_for_expression(e, variables)?))
}
Expression::RegexFunctionCall(a, b, c) => PlanExpression::Regex(
Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?),
match c {
Some(c) => Some(Box::new(self.build_for_expression(c, variables)?)),
Expression::RegexFunctionCall(text, pattern, flags) => PlanExpression::Regex(
Box::new(self.build_for_expression(text, variables)?),
Box::new(self.build_for_expression(pattern, variables)?),
match flags {
Some(flags) => Some(Box::new(self.build_for_expression(flags, variables)?)),
None => None,
},
),
@ -444,7 +444,7 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
fn build_cast(
&self,
parameters: &Vec<Expression>,
parameters: &[Expression],
constructor: impl Fn(Box<PlanExpression>) -> PlanExpression,
variables: &mut Vec<Variable>,
name: &'static str,

@ -38,7 +38,7 @@ PrefixDecl -> () = "PREFIX"i _ ns:PNAME_NS _ i:IRIREF {
//[7]
SelectQuery -> Query = s:SelectClause _ d:DatasetClauses _ w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { //TODO: Modifier
Query::SelectQuery {
Query::Select {
dataset: d,
algebra: build_select(s, w, g, h, o, l, v, state)
}
@ -70,14 +70,14 @@ SelectClause_member -> SelectionMember =
//[10]
ConstructQuery -> Query =
"CONSTRUCT"i _ c:ConstructTemplate _ d:DatasetClauses _ w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::ConstructQuery {
Query::Construct {
construct: c,
dataset: d,
algebra: build_select(Selection::default(), w, g, h, o, l, v, state)
}
} /
"CONSTRUCT"i _ d:DatasetClauses _ "WHERE"i _ '{' _ c:ConstructQuery_optional_triple_template _ '}' _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::ConstructQuery {
Query::Construct {
construct: c.clone(),
dataset: d,
algebra: build_select(
@ -93,13 +93,13 @@ ConstructQuery_optional_triple_template -> Vec<TriplePattern> = TriplesTemplate
//[11]
DescribeQuery -> Query =
"DESCRIBE"i _ '*' _ d:DatasetClauses w:WhereClause? _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::DescribeQuery {
Query::Describe {
dataset: d,
algebra: build_select(Selection::default(), w.unwrap_or_else(GraphPattern::default), g, h, o, l, v, state)
}
} /
"DESCRIBE"i _ p:DescribeQuery_item+ _ d:DatasetClauses w:WhereClause? _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::DescribeQuery {
Query::Describe {
dataset: d,
algebra: build_select(Selection {
option: SelectionOption::Default,
@ -114,7 +114,7 @@ DescribeQuery_item -> NamedNodeOrVariable = i:VarOrIri _ { i }
//[12]
AskQuery -> Query = "ASK"i _ d:DatasetClauses w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::AskQuery {
Query::Ask {
dataset: d,
algebra: build_select(Selection::default(), w, g, h, o, l, v, state)
}
@ -170,7 +170,7 @@ GroupCondition_as -> Variable = "AS"i _ v:Var _ { v }
//[21]
HavingClause -> Expression = "HAVING"i _ e:HavingCondition+ {?
not_empty_fold(e.into_iter(), |a, b| Expression::AndExpression(Box::new(a), Box::new(b)))
not_empty_fold(e.into_iter(), |a, b| Expression::And(Box::new(a), Box::new(b)))
}
//[22]
@ -226,7 +226,7 @@ GroupGraphPattern -> GraphPattern =
//[54]
GroupGraphPatternSub -> GraphPattern = a:TriplesBlock? _ b:GroupGraphPatternSub_item* {
let mut p = a.map(|v| vec![PartialGraphPattern::Other(GraphPattern::BGP(v))]).unwrap_or_else(|| vec![]);
let mut p = a.map_or_else(Vec::default, |v| vec![PartialGraphPattern::Other(GraphPattern::BGP(v))]);
for v in b {
p.extend_from_slice(&v)
}
@ -249,7 +249,7 @@ GroupGraphPatternSub -> GraphPattern = a:TriplesBlock? _ b:GroupGraphPatternSub_
g = GraphPattern::Extend(Box::new(g), var, expr)
}
PartialGraphPattern::Filter(expr) => match filter {
Some(f) => { filter = Some(Expression::AndExpression(Box::new(f), Box::new(expr))) },
Some(f) => { filter = Some(Expression::And(Box::new(f), Box::new(expr))) },
None => { filter = Some(expr) }
},
PartialGraphPattern::Other(e) => g = new_join(g, e),
@ -693,13 +693,13 @@ Expression -> Expression = e:ConditionalOrExpression {e}
//[111]
ConditionalOrExpression -> Expression = e:ConditionalOrExpression_item **<1,> ("||" _) {?
not_empty_fold(e.into_iter(), |a, b| Expression::OrExpression(Box::new(a), Box::new(b)))
not_empty_fold(e.into_iter(), |a, b| Expression::Or(Box::new(a), Box::new(b)))
}
ConditionalOrExpression_item -> Expression = e:ConditionalAndExpression _ { e }
//[112]
ConditionalAndExpression -> Expression = e:ConditionalAndExpression_item **<1,> ("&&" _) {?
not_empty_fold(e.into_iter(), |a, b| Expression::AndExpression(Box::new(a), Box::new(b)))
not_empty_fold(e.into_iter(), |a, b| Expression::And(Box::new(a), Box::new(b)))
}
ConditionalAndExpression_item -> Expression = e:ValueLogical _ { e }
@ -708,14 +708,14 @@ ValueLogical -> Expression = RelationalExpression
//[114]
RelationalExpression -> Expression =
a:NumericExpression _ "=" _ b:NumericExpression { Expression::EqualExpression(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "!=" _ b:NumericExpression { Expression::NotEqualExpression(Box::new(a), Box::new(b)) } /
a:NumericExpression _ ">" _ b:NumericExpression { Expression::GreaterExpression(Box::new(a), Box::new(b)) } /
a:NumericExpression _ ">=" _ b:NumericExpression { Expression::GreaterOrEqExpression(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "<" _ b:NumericExpression { Expression::LowerExpression(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "<=" _ b:NumericExpression { Expression::LowerOrEqExpression(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "IN"i _ b:ExpressionList { Expression::InExpression(Box::new(a), b) } /
a:NumericExpression _ "NOT"i _ "IN"i _ b:ExpressionList { Expression::NotInExpression(Box::new(a), b) } /
a:NumericExpression _ "=" _ b:NumericExpression { Expression::Equal(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "!=" _ b:NumericExpression { Expression::NotEqual(Box::new(a), Box::new(b)) } /
a:NumericExpression _ ">" _ b:NumericExpression { Expression::Greater(Box::new(a), Box::new(b)) } /
a:NumericExpression _ ">=" _ b:NumericExpression { Expression::GreaterOrEq(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "<" _ b:NumericExpression { Expression::Lower(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "<=" _ b:NumericExpression { Expression::LowerOrEq(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "IN"i _ b:ExpressionList { Expression::In(Box::new(a), b) } /
a:NumericExpression _ "NOT"i _ "IN"i _ b:ExpressionList { Expression::NotIn(Box::new(a), b) } /
NumericExpression
//[115]
@ -723,21 +723,21 @@ NumericExpression -> Expression = AdditiveExpression
//[116]
AdditiveExpression -> Expression =
a:MultiplicativeExpression _ '+' _ b:AdditiveExpression { Expression::AddExpression(Box::new(a), Box::new(b)) } /
a:MultiplicativeExpression _ '-' _ b:AdditiveExpression { Expression::SubExpression(Box::new(a), Box::new(b)) } /
a:MultiplicativeExpression _ '+' _ b:AdditiveExpression { Expression::Add(Box::new(a), Box::new(b)) } /
a:MultiplicativeExpression _ '-' _ b:AdditiveExpression { Expression::Sub(Box::new(a), Box::new(b)) } /
MultiplicativeExpression
//[117]
MultiplicativeExpression -> Expression =
a:UnaryExpression _ '*' _ b:MultiplicativeExpression { Expression::MulExpression(Box::new(a), Box::new(b)) } /
a:UnaryExpression _ '/' _ b:MultiplicativeExpression { Expression::DivExpression(Box::new(a), Box::new(b)) } /
a:UnaryExpression _ '*' _ b:MultiplicativeExpression { Expression::Mul(Box::new(a), Box::new(b)) } /
a:UnaryExpression _ '/' _ b:MultiplicativeExpression { Expression::Div(Box::new(a), Box::new(b)) } /
UnaryExpression
//[118]
UnaryExpression -> Expression =
'!' _ e:PrimaryExpression { Expression::UnaryNotExpression(Box::new(e)) } /
'+' _ e:PrimaryExpression { Expression::UnaryPlusExpression(Box::new(e)) } /
'-' _ e:PrimaryExpression { Expression::UnaryMinusExpression(Box::new(e)) } /
'!' _ e:PrimaryExpression { Expression::UnaryNot(Box::new(e)) } /
'+' _ e:PrimaryExpression { Expression::UnaryPlus(Box::new(e)) } /
'-' _ e:PrimaryExpression { Expression::UnaryMinus(Box::new(e)) } /
PrimaryExpression
//[119]
@ -745,10 +745,10 @@ PrimaryExpression -> Expression =
BrackettedExpression /
BuiltInCall /
iriOrFunction /
l:RDFLiteral { Expression::ConstantExpression(l.into()) } /
l:NumericLiteral { Expression::ConstantExpression(l.into()) } /
l:BooleanLiteral { Expression::ConstantExpression(l.into()) } /
v:Var { Expression::ConstantExpression(v.into()) }
l:RDFLiteral { Expression::Constant(l.into()) } /
l:NumericLiteral { Expression::Constant(l.into()) } /
l:BooleanLiteral { Expression::Constant(l.into()) } /
v:Var { Expression::Constant(v.into()) }
//[120]
BrackettedExpression -> Expression = '(' _ e:Expression _ ')' { e }
@ -829,7 +829,7 @@ StrReplaceExpression -> Expression =
ExistsFunc -> Expression = "EXISTS"i _ p:GroupGraphPattern { Expression::ExistsFunctionCall(Box::new(p)) }
//[126]
NotExistsFunc -> Expression = "NOT"i _ "EXISTS"i _ p:GroupGraphPattern { Expression::UnaryNotExpression(Box::new(Expression::ExistsFunctionCall(Box::new(p)))) }
NotExistsFunc -> Expression = "NOT"i _ "EXISTS"i _ p:GroupGraphPattern { Expression::UnaryNot(Box::new(Expression::ExistsFunctionCall(Box::new(p)))) }
//[127]
Aggregate -> Aggregation =
@ -856,7 +856,7 @@ Aggregate -> Aggregation =
iriOrFunction -> Expression = i: iri _ a: ArgList? {
match a {
Some(a) => Expression::CustomFunctionCall(i, a),
None => Expression::ConstantExpression(i.into())
None => Expression::Constant(i.into())
}
}

@ -90,8 +90,7 @@ pub fn read_xml_results(source: impl BufRead + 'static) -> Result<QueryResult> {
State::Head => {
if event.name() == b"variable" {
let name = event.attributes()
.filter(|attr| attr.is_ok())
.map(|attr| attr.unwrap())
.filter_map(|attr| attr.ok())
.find(|attr| attr.key == b"name")
.ok_or("No name attribute found for the <variable> tag");
variables.push(name?.unescape_and_decode_value(&reader)?);
@ -128,11 +127,10 @@ pub fn read_xml_results(source: impl BufRead + 'static) -> Result<QueryResult> {
_ => Err(format!("Unexpected textual value found: {}", reader.decode(&value)).into())
};
},
Event::End(_) => match state {
State::Head => state = State::AfterHead,
_ => {
Event::End(_) => if let State::Head = state {
state = State::AfterHead;
} else {
return Err("Unexpected early file end. All results file should have a <head> and a <result> or <boolean> tag".into());
}
},
Event::Eof => return Err("Unexpected early file end. All results file should have a <head> and a <result> or <boolean> tag".into()),
_ => (),
@ -199,8 +197,7 @@ impl<R: BufRead> Iterator for ResultsIterator<R> {
State::Result => if event.name() == b"binding" {
match event
.attributes()
.filter(|attr| attr.is_ok())
.map(|attr| attr.unwrap())
.filter_map(|attr| attr.ok())
.find(|attr| attr.key == b"name")
{
Some(attr) => match attr.unescaped_value() {

@ -368,7 +368,7 @@ impl<S: EncodedQuadsStore + Default> Default for StoreDataset<S> {
impl<S: EncodedQuadsStore + Default> FromIterator<Quad> for StoreDataset<S> {
fn from_iter<I: IntoIterator<Item = Quad>>(iter: I) -> Self {
let dataset = StoreDataset::default();
let dataset = Self::default();
for quad in iter {
dataset.insert(&quad).unwrap();
}
@ -378,7 +378,7 @@ impl<S: EncodedQuadsStore + Default> FromIterator<Quad> for StoreDataset<S> {
impl<'a, S: EncodedQuadsStore + Default> FromIterator<&'a Quad> for StoreDataset<S> {
fn from_iter<I: IntoIterator<Item = &'a Quad>>(iter: I) -> Self {
let dataset = StoreDataset::default();
let dataset = Self::default();
for quad in iter {
dataset.insert(quad).unwrap();
}
@ -709,7 +709,7 @@ impl<S: EncodedQuadsStore + Default> Default for StoreDefaultGraph<S> {
impl<S: EncodedQuadsStore + Default> FromIterator<Triple> for StoreDefaultGraph<S> {
fn from_iter<I: IntoIterator<Item = Triple>>(iter: I) -> Self {
let graph = StoreDefaultGraph::default();
let graph = Self::default();
for triple in iter {
graph.insert(&triple).unwrap();
}
@ -719,7 +719,7 @@ impl<S: EncodedQuadsStore + Default> FromIterator<Triple> for StoreDefaultGraph<
impl<'a, S: EncodedQuadsStore + Default> FromIterator<&'a Triple> for StoreDefaultGraph<S> {
fn from_iter<I: IntoIterator<Item = &'a Triple>>(iter: I) -> Self {
let graph = StoreDefaultGraph::default();
let graph = Self::default();
for triple in iter {
graph.insert(triple).unwrap();
}

@ -1,8 +1,8 @@
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::RwLock;
use store::encoded::*;
use store::numeric_encoder::*;
use store::store::*;
use Result;
/// Memory based implementation of the `rudf::model::Dataset` trait.
@ -388,16 +388,12 @@ impl EncodedQuadsStore for MemoryStore {
.graph_indexes
.read()?
.get(&quad.graph_name)
.map(|graph| {
graph
.spo
.get(&quad.subject)
.map(|po| {
po.get(&quad.predicate)
.map(|o| o.contains(&quad.object))
.unwrap_or(false)
}).unwrap_or(false)
}).unwrap_or(false))
.map_or(false, |graph| {
graph.spo.get(&quad.subject).map_or(false, |po| {
po.get(&quad.predicate)
.map_or(false, |o| o.contains(&quad.object))
})
}))
}
fn insert(&self, quad: &EncodedQuad) -> Result<()> {

@ -1,10 +1,10 @@
//! Provides implementations of the `rudf::model::Graph` and `rudf::model::Dataset` traits.
pub(crate) mod encoded;
pub mod isomorphism;
mod memory;
pub(crate) mod numeric_encoder;
mod rocksdb;
pub(crate) mod store;
pub use store::memory::MemoryDataset;
pub use store::memory::MemoryGraph;

@ -128,20 +128,20 @@ impl EncodedTerm {
pub fn is_literal(&self) -> bool {
match self {
EncodedTerm::SimpleLiteral { .. } => true,
EncodedTerm::LangStringLiteral { .. } => true,
EncodedTerm::TypedLiteral { .. } => true,
EncodedTerm::StringLiteral { .. } => true,
EncodedTerm::BooleanLiteral(_) => true,
EncodedTerm::FloatLiteral(_) => true,
EncodedTerm::DoubleLiteral(_) => true,
EncodedTerm::IntegerLiteral(_) => true,
EncodedTerm::DecimalLiteral(_) => true,
EncodedTerm::SimpleLiteral { .. }
| EncodedTerm::LangStringLiteral { .. }
| EncodedTerm::TypedLiteral { .. }
| EncodedTerm::StringLiteral { .. }
| EncodedTerm::BooleanLiteral(_)
| EncodedTerm::FloatLiteral(_)
| EncodedTerm::DoubleLiteral(_)
| EncodedTerm::IntegerLiteral(_)
| EncodedTerm::DecimalLiteral(_) => true,
_ => false,
}
}
pub fn datatype(&self) -> Option<EncodedTerm> {
pub fn datatype(&self) -> Option<Self> {
match self {
EncodedTerm::SimpleLiteral { .. } | EncodedTerm::StringLiteral { .. } => {
Some(ENCODED_XSD_STRING_NAMED_NODE)
@ -262,7 +262,7 @@ impl<R: Read> TermReader for R {
datatype_id: self.read_u64::<NetworkEndian>()?,
value_id: self.read_u64::<NetworkEndian>()?,
}),
TYPE_STRING_LITERAL => Ok(EncodedTerm::SimpleLiteral {
TYPE_STRING_LITERAL => Ok(EncodedTerm::StringLiteral {
value_id: self.read_u64::<NetworkEndian>()?,
}),
TYPE_BOOLEAN_LITERAL_TRUE => Ok(EncodedTerm::BooleanLiteral(true)),
@ -339,7 +339,7 @@ impl<R: Write> TermWriter for R {
EncodedTerm::DefaultGraph {} => {}
EncodedTerm::NamedNode { iri_id } => self.write_u64::<NetworkEndian>(iri_id)?,
EncodedTerm::BlankNode(id) => self.write_all(id.as_bytes())?,
EncodedTerm::SimpleLiteral { value_id } => {
EncodedTerm::SimpleLiteral { value_id } | EncodedTerm::StringLiteral { value_id } => {
self.write_u64::<NetworkEndian>(value_id)?;
}
EncodedTerm::LangStringLiteral {
@ -356,10 +356,6 @@ impl<R: Write> TermWriter for R {
self.write_u64::<NetworkEndian>(datatype_id)?;
self.write_u64::<NetworkEndian>(value_id)?;
}
EncodedTerm::StringLiteral { value_id } => {
self.write_u64::<NetworkEndian>(value_id)?;
}
EncodedTerm::BooleanLiteral(_) => {}
EncodedTerm::FloatLiteral(value) => self.write_f32::<NetworkEndian>(*value)?,
EncodedTerm::DoubleLiteral(value) => self.write_f64::<NetworkEndian>(*value)?,

@ -10,9 +10,9 @@ use std::io::Cursor;
use std::path::Path;
use std::str;
use std::sync::Mutex;
use store::encoded::EncodedQuadsStore;
use store::encoded::StoreDataset;
use store::numeric_encoder::*;
use store::store::EncodedQuadsStore;
use store::store::StoreDataset;
use Result;
/// `rudf::model::Dataset` trait implementation based on the [RocksDB](https://rocksdb.org/) key-value store
@ -83,17 +83,16 @@ impl BytesStore for RocksDbStore {
type BytesOutput = DBVector;
fn insert_bytes(&self, value: &[u8]) -> Result<u64> {
Ok(match self.db.get_cf(self.str2id_cf, value)? {
Some(id) => NetworkEndian::read_u64(&id),
None => {
let id = self.str_id_counter.lock()?.get_and_increment(&self.db)? as u64;
let id_bytes = to_bytes(id);
let mut batch = WriteBatch::default();
batch.put_cf(self.id2str_cf, &id_bytes, value)?;
batch.put_cf(self.str2id_cf, value, &id_bytes)?;
self.db.write(batch)?;
id
}
Ok(if let Some(id) = self.db.get_cf(self.str2id_cf, value)? {
NetworkEndian::read_u64(&id)
} else {
let id = self.str_id_counter.lock()?.get_and_increment(&self.db)? as u64;
let id_bytes = to_bytes(id);
let mut batch = WriteBatch::default();
batch.put_cf(self.id2str_cf, &id_bytes, value)?;
batch.put_cf(self.str2id_cf, value, &id_bytes)?;
self.db.write(batch)?;
id
})
}
@ -342,8 +341,7 @@ impl RocksDBCounter {
fn get_and_increment(&self, db: &DB) -> Result<u64> {
let value = db
.get(self.name.as_bytes())?
.map(|b| NetworkEndian::read_u64(&b))
.unwrap_or(0);
.map_or(0, |b| NetworkEndian::read_u64(&b));
db.put(self.name.as_bytes(), &to_bytes(value + 1))?;
Ok(value)
}

@ -26,8 +26,8 @@ enum EscapeRdfState {
}
impl EscapeRDF {
fn new(c: char) -> EscapeRDF {
EscapeRDF {
fn new(c: char) -> Self {
Self {
state: match c {
'\t' => EscapeRdfState::Backslash('t'),
'\u{08}' => EscapeRdfState::Backslash('b'),

@ -1,3 +1,8 @@
#![cfg_attr(
feature = "cargo-clippy",
allow(zero_ptr, transmute_ptr_to_ptr)
)]
#[macro_use]
extern crate cpython;
extern crate rudf;
@ -24,11 +29,11 @@ py_module_initializer!(rudf, initrudf, PyInit_rudf, |py, m| {
Ok(())
});
fn new_value_error(py: Python, error: impl Error) -> PyErr {
fn new_value_error(py: Python, error: &impl Error) -> PyErr {
PyErr::new::<ValueError, _>(py, error.description())
}
fn eq_compare<T: Eq + Ord>(a: T, b: T, op: CompareOp) -> bool {
fn eq_compare<T: Eq + Ord>(a: &T, b: &T, op: &CompareOp) -> bool {
match op {
CompareOp::Lt => a < b,
CompareOp::Le => a <= b,
@ -49,7 +54,7 @@ py_class!(class NamedNode |py| {
data inner: model::NamedNode;
def __new__(_cls, value: &str) -> PyResult<NamedNode> {
NamedNode::create_instance(py, model::NamedNode::from_str(value).map_err(|error| new_value_error(py, error))?)
NamedNode::create_instance(py, model::NamedNode::from_str(value).map_err(|error| new_value_error(py, &error))?)
}
def value(&self) -> PyResult<String> {
@ -61,7 +66,7 @@ py_class!(class NamedNode |py| {
}
def __richcmp__(&self, other: &NamedNode, op: CompareOp) -> PyResult<bool> {
Ok(eq_compare(self.inner(py), other.inner(py), op))
Ok(eq_compare(&self.inner(py), &other.inner(py), &op))
}
def __hash__(&self) -> PyResult<u64> {
@ -81,7 +86,7 @@ py_class!(class BlankNode |py| {
}
def __richcmp__(&self, other: &BlankNode, op: CompareOp) -> PyResult<bool> {
Ok(eq_compare(self.inner(py), other.inner(py), op))
Ok(eq_compare(&self.inner(py), &other.inner(py), &op))
}
def __hash__(&self) -> PyResult<u64> {
@ -119,7 +124,7 @@ py_class!(class Literal |py| {
}
def __richcmp__(&self, other: &Literal, op: CompareOp) -> PyResult<bool> {
Ok(eq_compare(self.inner(py), other.inner(py), op))
Ok(eq_compare(&self.inner(py), &other.inner(py), &op))
}
def __hash__(&self) -> PyResult<u64> {

Loading…
Cancel
Save