Fix clippy warnings

This commit is contained in:
gwenn 2016-02-14 16:11:59 +01:00
parent 2cb6c59b3d
commit 0fe1990d34
6 changed files with 80 additions and 77 deletions

View File

@ -23,6 +23,7 @@ trace = []
time = "~0.1.0" time = "~0.1.0"
bitflags = "~0.1" bitflags = "~0.1"
libc = "~0.2" libc = "~0.2"
clippy = {version = "~0.0.41", optional = true}
[dev-dependencies] [dev-dependencies]
tempdir = "~0.3.4" tempdir = "~0.3.4"

View File

@ -82,84 +82,84 @@ impl From<::std::ffi::NulError> for Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match *self {
&Error::SqliteFailure(ref err, None) => err.fmt(f), Error::SqliteFailure(ref err, None) => err.fmt(f),
&Error::SqliteFailure(_, Some(ref s)) => write!(f, "{}", s), Error::SqliteFailure(_, Some(ref s)) => write!(f, "{}", s),
&Error::SqliteSingleThreadedMode => { Error::SqliteSingleThreadedMode => {
write!(f, write!(f,
"SQLite was compiled or configured for single-threaded use only") "SQLite was compiled or configured for single-threaded use only")
} }
&Error::FromSqlConversionFailure(ref err) => err.fmt(f), Error::FromSqlConversionFailure(ref err) => err.fmt(f),
&Error::Utf8Error(ref err) => err.fmt(f), Error::Utf8Error(ref err) => err.fmt(f),
&Error::NulError(ref err) => err.fmt(f), Error::NulError(ref err) => err.fmt(f),
&Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name), Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name),
&Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()), Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
&Error::ExecuteReturnedResults => { Error::ExecuteReturnedResults => {
write!(f, "Execute returned results - did you mean to call query?") write!(f, "Execute returned results - did you mean to call query?")
} }
&Error::QueryReturnedNoRows => write!(f, "Query returned no rows"), Error::QueryReturnedNoRows => write!(f, "Query returned no rows"),
&Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"), Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"),
&Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i), Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i),
&Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name), Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name),
&Error::InvalidColumnType => write!(f, "Invalid column type"), Error::InvalidColumnType => write!(f, "Invalid column type"),
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"), Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"),
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::UserFunctionError(ref err) => err.fmt(f), Error::UserFunctionError(ref err) => err.fmt(f),
} }
} }
} }
impl error::Error for Error { impl error::Error for Error {
fn description(&self) -> &str { fn description(&self) -> &str {
match self { match *self {
&Error::SqliteFailure(ref err, None) => err.description(), Error::SqliteFailure(ref err, None) => err.description(),
&Error::SqliteFailure(_, Some(ref s)) => s, Error::SqliteFailure(_, Some(ref s)) => s,
&Error::SqliteSingleThreadedMode => { Error::SqliteSingleThreadedMode => {
"SQLite was compiled or configured for single-threaded use only" "SQLite was compiled or configured for single-threaded use only"
} }
&Error::FromSqlConversionFailure(ref err) => err.description(), Error::FromSqlConversionFailure(ref err) => err.description(),
&Error::Utf8Error(ref err) => err.description(), Error::Utf8Error(ref err) => err.description(),
&Error::InvalidParameterName(_) => "invalid parameter name", Error::InvalidParameterName(_) => "invalid parameter name",
&Error::NulError(ref err) => err.description(), Error::NulError(ref err) => err.description(),
&Error::InvalidPath(_) => "invalid path", Error::InvalidPath(_) => "invalid path",
&Error::ExecuteReturnedResults => { Error::ExecuteReturnedResults => {
"execute returned results - did you mean to call query?" "execute returned results - did you mean to call query?"
} }
&Error::QueryReturnedNoRows => "query returned no rows", Error::QueryReturnedNoRows => "query returned no rows",
&Error::GetFromStaleRow => "attempted to get a value from a stale row", Error::GetFromStaleRow => "attempted to get a value from a stale row",
&Error::InvalidColumnIndex(_) => "invalid column index", Error::InvalidColumnIndex(_) => "invalid column index",
&Error::InvalidColumnName(_) => "invalid column name", Error::InvalidColumnName(_) => "invalid column name",
&Error::InvalidColumnType => "invalid column type", Error::InvalidColumnType => "invalid column type",
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::InvalidFunctionParameterType => "invalid function parameter type", Error::InvalidFunctionParameterType => "invalid function parameter type",
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::UserFunctionError(ref err) => err.description(), Error::UserFunctionError(ref err) => err.description(),
} }
} }
fn cause(&self) -> Option<&error::Error> { fn cause(&self) -> Option<&error::Error> {
match self { match *self {
&Error::SqliteFailure(ref err, _) => Some(err), Error::SqliteFailure(ref err, _) => Some(err),
&Error::SqliteSingleThreadedMode => None, Error::SqliteSingleThreadedMode => None,
&Error::FromSqlConversionFailure(ref err) => Some(&**err), Error::FromSqlConversionFailure(ref err) => Some(&**err),
&Error::Utf8Error(ref err) => Some(err), Error::Utf8Error(ref err) => Some(err),
&Error::NulError(ref err) => Some(err), Error::NulError(ref err) => Some(err),
&Error::InvalidParameterName(_) => None, Error::InvalidParameterName(_) => None,
&Error::InvalidPath(_) => None, Error::InvalidPath(_) => None,
&Error::ExecuteReturnedResults => None, Error::ExecuteReturnedResults => None,
&Error::QueryReturnedNoRows => None, Error::QueryReturnedNoRows => None,
&Error::GetFromStaleRow => None, Error::GetFromStaleRow => None,
&Error::InvalidColumnIndex(_) => None, Error::InvalidColumnIndex(_) => None,
&Error::InvalidColumnName(_) => None, Error::InvalidColumnName(_) => None,
&Error::InvalidColumnType => None, Error::InvalidColumnType => None,
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::InvalidFunctionParameterType => None, Error::InvalidFunctionParameterType => None,
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::UserFunctionError(ref err) => Some(&**err), Error::UserFunctionError(ref err) => Some(&**err),
} }
} }
} }

View File

@ -88,9 +88,10 @@ raw_to_impl!(c_double, sqlite3_result_double);
impl<'a> ToResult for bool { impl<'a> ToResult for bool {
unsafe fn set_result(&self, ctx: *mut sqlite3_context) { unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
match *self { if *self {
true => ffi::sqlite3_result_int(ctx, 1), ffi::sqlite3_result_int(ctx, 1)
_ => ffi::sqlite3_result_int(ctx, 0), } else {
ffi::sqlite3_result_int(ctx, 0)
} }
} }
} }
@ -214,7 +215,7 @@ impl FromValue for String {
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<String> { unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<String> {
let c_text = ffi::sqlite3_value_text(v); let c_text = ffi::sqlite3_value_text(v);
if c_text.is_null() { if c_text.is_null() {
Ok("".to_string()) Ok("".to_owned())
} else { } else {
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes(); let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
let utf8_str = try!(str::from_utf8(c_slice)); let utf8_str = try!(str::from_utf8(c_slice));
@ -250,7 +251,7 @@ impl<T: FromValue> FromValue for Option<T> {
if sqlite3_value_type(v) == ffi::SQLITE_NULL { if sqlite3_value_type(v) == ffi::SQLITE_NULL {
Ok(None) Ok(None)
} else { } else {
FromValue::parameter_value(v).map(|t| Some(t)) FromValue::parameter_value(v).map(Some)
} }
} }
@ -274,6 +275,10 @@ impl<'a> Context<'a> {
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.args.len() self.args.len()
} }
/// Returns `true` when there is no argument.
pub fn is_empty(&self) -> bool {
self.args.is_empty()
}
/// Returns the `idx`th argument as a `T`. /// Returns the `idx`th argument as a `T`.
/// ///

View File

@ -50,6 +50,9 @@
//! } //! }
//! } //! }
//! ``` //! ```
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate libc; extern crate libc;
extern crate libsqlite3_sys as ffi; extern crate libsqlite3_sys as ffi;
#[macro_use] #[macro_use]
@ -99,7 +102,7 @@ pub type Result<T> = result::Result<T, Error>;
unsafe fn errmsg_to_string(errmsg: *const c_char) -> String { unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
let c_slice = CStr::from_ptr(errmsg).to_bytes(); let c_slice = CStr::from_ptr(errmsg).to_bytes();
let utf8_str = str::from_utf8(c_slice); let utf8_str = str::from_utf8(c_slice);
utf8_str.unwrap_or("Invalid string encoding").to_string() utf8_str.unwrap_or("Invalid string encoding").to_owned()
} }
fn str_to_cstring(s: &str) -> Result<CString> { fn str_to_cstring(s: &str) -> Result<CString> {
@ -127,9 +130,9 @@ pub enum DatabaseName<'a> {
// impl to avoid dead code warnings. // impl to avoid dead code warnings.
#[cfg(any(feature = "backup", feature = "blob"))] #[cfg(any(feature = "backup", feature = "blob"))]
impl<'a> DatabaseName<'a> { impl<'a> DatabaseName<'a> {
fn to_cstring(self) -> Result<CString> { fn to_cstring(&self) -> Result<CString> {
use self::DatabaseName::{Main, Temp, Attached}; use self::DatabaseName::{Main, Temp, Attached};
match self { match *self {
Main => str_to_cstring("main"), Main => str_to_cstring("main"),
Temp => str_to_cstring("temp"), Temp => str_to_cstring("temp"),
Attached(s) => str_to_cstring(s), Attached(s) => str_to_cstring(s),
@ -234,7 +237,7 @@ impl Connection {
/// # Failure /// # Failure
/// ///
/// Will return `Err` if the underlying SQLite call fails. /// Will return `Err` if the underlying SQLite call fails.
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> { pub fn transaction(&self) -> Result<Transaction> {
Transaction::new(self, TransactionBehavior::Deferred) Transaction::new(self, TransactionBehavior::Deferred)
} }
@ -245,9 +248,7 @@ impl Connection {
/// # Failure /// # Failure
/// ///
/// Will return `Err` if the underlying SQLite call fails. /// Will return `Err` if the underlying SQLite call fails.
pub fn transaction_with_behavior<'a>(&'a self, pub fn transaction_with_behavior(&self, behavior: TransactionBehavior) -> Result<Transaction> {
behavior: TransactionBehavior)
-> Result<Transaction<'a>> {
Transaction::new(self, behavior) Transaction::new(self, behavior)
} }
@ -572,11 +573,7 @@ impl InnerConnection {
// https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c). // https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c).
const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8; const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8;
let mutex_ptr = ffi::sqlite3_mutex_alloc(0); let mutex_ptr = ffi::sqlite3_mutex_alloc(0);
let is_singlethreaded = if mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC { let is_singlethreaded = mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC;
true
} else {
false
};
ffi::sqlite3_mutex_free(mutex_ptr); ffi::sqlite3_mutex_free(mutex_ptr);
if is_singlethreaded { if is_singlethreaded {
return Err(Error::SqliteSingleThreadedMode); return Err(Error::SqliteSingleThreadedMode);
@ -1173,7 +1170,6 @@ impl<'a> RowIndex for &'a str {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
extern crate libsqlite3_sys as ffi;
extern crate tempdir; extern crate tempdir;
pub use super::*; pub use super::*;
use self::tempdir::TempDir; use self::tempdir::TempDir;

View File

@ -89,7 +89,7 @@ impl<'conn> Transaction<'conn> {
/// tx.commit() /// tx.commit()
/// } /// }
/// ``` /// ```
pub fn savepoint<'a>(&'a self) -> Result<Transaction<'a>> { pub fn savepoint(&self) -> Result<Transaction> {
self.conn.execute_batch("SAVEPOINT sp").map(|_| { self.conn.execute_batch("SAVEPOINT sp").map(|_| {
Transaction { Transaction {
conn: self.conn, conn: self.conn,

View File

@ -102,9 +102,10 @@ raw_to_impl!(c_double, sqlite3_bind_double);
impl ToSql for bool { impl ToSql for bool {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
match *self { if *self {
true => ffi::sqlite3_bind_int(stmt, col, 1), ffi::sqlite3_bind_int(stmt, col, 1)
_ => ffi::sqlite3_bind_int(stmt, col, 0), } else {
ffi::sqlite3_bind_int(stmt, col, 0)
} }
} }
} }
@ -229,7 +230,7 @@ impl FromSql for String {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> {
let c_text = ffi::sqlite3_column_text(stmt, col); let c_text = ffi::sqlite3_column_text(stmt, col);
if c_text.is_null() { if c_text.is_null() {
Ok("".to_string()) Ok("".to_owned())
} else { } else {
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes(); let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
let utf8_str = try!(str::from_utf8(c_slice)); let utf8_str = try!(str::from_utf8(c_slice));
@ -283,7 +284,7 @@ impl<T: FromSql> FromSql for Option<T> {
if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL { if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL {
Ok(None) Ok(None)
} else { } else {
FromSql::column_result(stmt, col).map(|t| Some(t)) FromSql::column_result(stmt, col).map(Some)
} }
} }
@ -312,11 +313,11 @@ pub enum Value {
impl FromSql for Value { impl FromSql for Value {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
match sqlite3_column_type(stmt, col) { match sqlite3_column_type(stmt, col) {
ffi::SQLITE_TEXT => FromSql::column_result(stmt, col).map(|t| Value::Text(t)), ffi::SQLITE_TEXT => FromSql::column_result(stmt, col).map(Value::Text),
ffi::SQLITE_INTEGER => Ok(Value::Integer(ffi::sqlite3_column_int64(stmt, col))), ffi::SQLITE_INTEGER => Ok(Value::Integer(ffi::sqlite3_column_int64(stmt, col))),
ffi::SQLITE_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))), ffi::SQLITE_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))),
ffi::SQLITE_NULL => Ok(Value::Null), ffi::SQLITE_NULL => Ok(Value::Null),
ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(|t| Value::Blob(t)), ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(Value::Blob),
_ => Err(Error::InvalidColumnType), _ => Err(Error::InvalidColumnType),
} }
} }
@ -355,7 +356,7 @@ mod test {
let db = checked_memory_handle(); let db = checked_memory_handle();
let s = "hello, world!"; let s = "hello, world!";
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_string()]).unwrap(); db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_owned()]).unwrap();
let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(from, s); assert_eq!(from, s);