Skip to content

Add specialized predicates #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ install:
- cargo -V

script:
- cargo check --verbose --no-default-features
- cargo check --verbose
- cargo test --verbose
- cargo doc --no-deps
Expand Down
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ travis-ci = { repository = "assert-rs/predicates-rs" }
appveyor = { repository = "assert-rs/predicates-rs" }

[dependencies]
difference = { version = "2.0", optional = true }
regex = { version="0.2", optional = true }
float-cmp = { version="0.4", optional = true }

[features]
default = []
default = ["difference", "regex", "float-cmp"]
unstable = []
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@

#![deny(missing_docs, missing_debug_implementations)]

#[cfg(feature = "difference")]
extern crate difference;
#[cfg(feature = "float-cmp")]
extern crate float_cmp;
#[cfg(feature = "regex")]
extern crate regex;

// core `Predicate` trait
pub mod predicate;
pub use self::predicate::{BoxPredicate, Predicate};
109 changes: 109 additions & 0 deletions src/predicate/float/close.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use float_cmp::ApproxEq;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New files need a copyright notice - I recommend the following:

// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

I will also plan to go back and modify the notices that list me as the copyright holder and replace with the statement above.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally rely on the project-wide license rather than per file.

If you prefer pre-file, we should make sure to get a CONTRIBUTING that mentions that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The recommendation of the FSF (via the GPLv3) is to include the license statement in all source files, and having dealt with way more FOSS licensing BS than I care to think about, I just feel better having the license in all files to avoid any confusion.

I've opened #22 and #23 to track the other changes needed so the whole project is licensed to the "predicates-rs Project Developers" and to make sure we get a CONTRIBUTING document. For this PR I think just adding the statement above is sufficient.

use float_cmp::Ulps;

use Predicate;

/// Predicate that ensures two numbers are "close" enough, understanding that rounding errors
/// occur.
///
/// This is created by the `predicate::float::is_close`.
#[derive(Clone, Debug)]
pub struct IsClosePredicate {
target: f64,
epsilon: f64,
ulps: <f64 as Ulps>::U,
}

impl IsClosePredicate {
/// Set the amount of error allowed.
///
/// Values `1`-`5` should work in most cases. Sometimes more control is needed and you will
/// need to set `IsClosePredicate::epsilon` separately from `IsClosePredicate::ulps`.
///
/// # Examples
///
/// ```
/// use predicates::predicate::*;
///
/// let a = 0.15_f64 + 0.15_f64 + 0.15_f64;
/// let predicate_fn = float::is_close(a).distance(5);
/// ```
pub fn distance(mut self, distance: <f64 as Ulps>::U) -> Self {
self.epsilon = (distance as f64) * ::std::f64::EPSILON;
self.ulps = distance;
self
}

/// Set the absolute deviation allowed.
///
/// This is meant to handle problems near `0`. Values `1.`-`5.` epislons should work in most
/// cases.
///
/// # Examples
///
/// ```
/// use predicates::predicate::*;
///
/// let a = 0.15_f64 + 0.15_f64 + 0.15_f64;
/// let predicate_fn = float::is_close(a).epsilon(5.0 * ::std::f64::EPSILON);
/// ```
pub fn epsilon(mut self, epsilon: f64) -> Self {
self.epsilon = epsilon;
self
}

/// Set the relative deviation allowed.
///
/// This is meant to handle large numbers. Values `1`-`5` should work in most cases.
///
/// # Examples
///
/// ```
/// use predicates::predicate::*;
///
/// let a = 0.15_f64 + 0.15_f64 + 0.15_f64;
/// let predicate_fn = float::is_close(a).ulps(5);
/// ```
pub fn ulps(mut self, ulps: <f64 as Ulps>::U) -> Self {
self.ulps = ulps;
self
}
}

impl Predicate for IsClosePredicate {
type Item = f64;

fn eval(&self, variable: &f64) -> bool {
variable.approx_eq(&self.target, self.epsilon, self.ulps)
}
}

/// Create a new `Predicate` that ensures two numbers are "close" enough, understanding that
/// rounding errors occur.
///
/// # Examples
///
/// ```
/// use predicates::predicate::*;
///
/// let a = 0.15_f64 + 0.15_f64 + 0.15_f64;
/// let b = 0.1_f64 + 0.1_f64 + 0.25_f64;
/// let predicate_fn = float::is_close(a);
/// assert_eq!(true, predicate_fn.eval(&b));
/// assert_eq!(false, predicate_fn.distance(0).eval(&b));
/// ```
pub fn is_close(target: f64) -> IsClosePredicate {
IsClosePredicate {
target,
epsilon: 2.0 * ::std::f64::EPSILON,
ulps: 2,
}
}
16 changes: 16 additions & 0 deletions src/predicate/float/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Float Predicates
//!
//! This module contains predicates specific to string handling.

#[cfg(feature = "float-cmp")]
mod close;
#[cfg(feature = "float-cmp")]
pub use self::close::{is_close, IsClosePredicate};
5 changes: 5 additions & 0 deletions src/predicate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ pub use self::ord::{eq, ge, gt, le, lt, ne, EqPredicate, OrdPredicate};
pub use self::set::{contains, contains_hashable, contains_ord, ContainsPredicate,
HashableContainsPredicate, OrdContainsPredicate};

// specialized primitive `Predicate` types
pub mod str;
pub mod path;
pub mod float;

// combinators
mod boolean;
mod boxed;
Expand Down
57 changes: 57 additions & 0 deletions src/predicate/path/existence.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::path;

use Predicate;

/// Predicate that checks if a file is present
///
/// This is created by the `predicate::path::exists` and `predicate::path::missing`.
#[derive(Debug)]
pub struct ExistencePredicate {
exists: bool,
}

impl Predicate for ExistencePredicate {
type Item = path::Path;

fn eval(&self, path: &path::Path) -> bool {
path.exists() == self.exists
}
}

/// Creates a new `Predicate` that ensures the path exists.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::predicate::*;
///
/// let predicate_fn = path::exists();
/// assert_eq!(true, predicate_fn.eval(Path::new("Cargo.toml")));
/// ```
pub fn exists() -> ExistencePredicate {
ExistencePredicate { exists: true }
}

/// Creates a new `Predicate` that ensures the path doesn't exist.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::predicate::*;
///
/// let predicate_fn = path::missing();
/// assert_eq!(true, predicate_fn.eval(Path::new("non-existent-file.foo")));
/// ```
pub fn missing() -> ExistencePredicate {
ExistencePredicate { exists: false }
}
125 changes: 125 additions & 0 deletions src/predicate/path/ft.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::path;
use std::fs;

use Predicate;

#[derive(Clone, Copy, Debug)]
enum FileType {
File,
Dir,
Symlink,
}

impl FileType {
fn eval(self, ft: &fs::FileType) -> bool {
match self {
FileType::File => ft.is_file(),
FileType::Dir => ft.is_dir(),
FileType::Symlink => ft.is_symlink(),
}
}
}

/// Predicate that checks the `std::fs::FileType`.
///
/// This is created by the `predicate::path::is_file`, `predicate::path::is_dir`, and `predicate::path::is_symlink`.
#[derive(Debug)]
pub struct FileTypePredicate {
ft: FileType,
follow: bool,
}

impl FileTypePredicate {
/// Follow symbolic links.
///
/// When yes is true, symbolic links are followed as if they were normal directories and files.
///
/// Default: disabled.
pub fn follow_links(mut self, yes: bool) -> Self {
self.follow = yes;
self
}
}

impl Predicate for FileTypePredicate {
type Item = path::Path;

fn eval(&self, path: &path::Path) -> bool {
let metadata = if self.follow {
path.metadata()
} else {
path.symlink_metadata()
};
metadata
.map(|m| self.ft.eval(&m.file_type()))
.unwrap_or(false)
}
}

/// Creates a new `Predicate` that ensures the path points to a file.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::predicate::*;
///
/// let predicate_fn = path::is_file();
/// assert_eq!(true, predicate_fn.eval(Path::new("Cargo.toml")));
/// assert_eq!(false, predicate_fn.eval(Path::new("src")));
/// assert_eq!(false, predicate_fn.eval(Path::new("non-existent-file.foo")));
/// ```
pub fn is_file() -> FileTypePredicate {
FileTypePredicate {
ft: FileType::File,
follow: false,
}
}

/// Creates a new `Predicate` that ensures the path points to a directory.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::predicate::*;
///
/// let predicate_fn = path::is_dir();
/// assert_eq!(false, predicate_fn.eval(Path::new("Cargo.toml")));
/// assert_eq!(true, predicate_fn.eval(Path::new("src")));
/// assert_eq!(false, predicate_fn.eval(Path::new("non-existent-file.foo")));
/// ```
pub fn is_dir() -> FileTypePredicate {
FileTypePredicate {
ft: FileType::Dir,
follow: false,
}
}

/// Creates a new `Predicate` that ensures the path points to a symlink.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::predicate::*;
///
/// let predicate_fn = path::is_symlink();
/// assert_eq!(false, predicate_fn.eval(Path::new("Cargo.toml")));
/// assert_eq!(false, predicate_fn.eval(Path::new("src")));
/// assert_eq!(false, predicate_fn.eval(Path::new("non-existent-file.foo")));
/// ```
pub fn is_symlink() -> FileTypePredicate {
FileTypePredicate {
ft: FileType::Symlink,
follow: false,
}
}
16 changes: 16 additions & 0 deletions src/predicate/path/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Path Predicates
//!
//! This module contains predicates specific to the file system.

mod existence;
pub use self::existence::{exists, missing, ExistencePredicate};
mod ft;
pub use self::ft::{is_dir, is_file, is_symlink, FileTypePredicate};
Loading