summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMartin Geisler <mgeisler@google.com>2023-11-16 12:13:22 +0100
committerMartin Geisler <mgeisler@google.com>2023-11-16 15:33:31 +0100
commit063f6edcc280ad62d643a0cd022fccf1cb6a869e (patch)
tree1d048800858fbab4133f7293e262528b225b5bb4
parent5ca6d8052723b3c36f0c1f5aa60514b1448e9e89 (diff)
downloadpredicates-core-063f6edcc280ad62d643a0cd022fccf1cb6a869e.tar.gz
Import 'predicates-core' crateupstream
Request Document: go/android-rust-importing-crates For CL Reviewers: go/android3p#cl-review For Build Team: go/ab-third-party-imports Bug: 310599818 Change-Id: I662dcdb358a1e058a7c2339e5fb9e4b54d2f7650
-rw-r--r--.cargo_vcs_info.json6
-rw-r--r--Android.bp18
-rw-r--r--Cargo.toml78
l---------LICENSE1
-rw-r--r--LICENSE-APACHE176
-rw-r--r--LICENSE-MIT22
-rw-r--r--METADATA20
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--OWNERS2
-rw-r--r--README.md25
-rw-r--r--cargo_embargo.json3
-rw-r--r--src/core.rs32
-rw-r--r--src/lib.rs25
-rw-r--r--src/reflection.rs252
14 files changed, 660 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..07e7fdd
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "7b72b706abbf1509fc74ee18e363d2bc7e8520a6"
+ },
+ "path_in_vcs": "crates/core"
+} \ No newline at end of file
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..2a94e01
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,18 @@
+// This file is generated by cargo_embargo.
+// Do not modify this file as changes will be overridden on upgrade.
+
+rust_library {
+ name: "libpredicates_core",
+ host_supported: true,
+ crate_name: "predicates_core",
+ cargo_env_compat: true,
+ cargo_pkg_version: "1.0.6",
+ srcs: ["src/lib.rs"],
+ edition: "2021",
+ apex_available: [
+ "//apex_available:platform",
+ "//apex_available:anyapex",
+ ],
+ product_available: true,
+ vendor_available: true,
+}
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..a1de8f1
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,78 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.64.0"
+name = "predicates-core"
+version = "1.0.6"
+authors = ["Nick Stevens <nick@bitcurry.com>"]
+include = [
+ "build.rs",
+ "src/**/*",
+ "Cargo.toml",
+ "LICENSE*",
+ "README.md",
+ "benches/**/*",
+ "examples/**/*",
+]
+description = "An API for boolean-valued predicate functions."
+homepage = "https://github.com/assert-rs/predicates-rs/tree/master/crates/core"
+documentation = "https://docs.rs/predicates-core"
+readme = "README.md"
+keywords = [
+ "predicate",
+ "boolean",
+ "combinatorial",
+ "match",
+ "logic",
+]
+categories = [
+ "data-structures",
+ "rust-patterns",
+]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/assert-rs/predicates-rs/tree/master/crates/core"
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "Unreleased"
+replace = "{{version}}"
+min = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = '\.\.\.HEAD'
+replace = "...{{tag_name}}"
+exactly = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "ReleaseDate"
+replace = "{{date}}"
+min = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "<!-- next-header -->"
+replace = """
+<!-- next-header -->
+## [Unreleased] - ReleaseDate
+"""
+exactly = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "<!-- next-url -->"
+replace = """
+<!-- next-url -->
+[Unreleased]: https://github.com/assert-rs/predicates-rs/compare/{{tag_name}}...HEAD"""
+exactly = 1
diff --git a/LICENSE b/LICENSE
new file mode 120000
index 0000000..6b579aa
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1 @@
+LICENSE-APACHE \ No newline at end of file
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..d9a10c0
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..51e7743
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2017 Nick Stevens
+
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..cd32702
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,20 @@
+name: "predicates-core"
+description: "An API for boolean-valued predicate functions."
+third_party {
+ identifier {
+ type: "crates.io"
+ value: "https://crates.io/crates/predicates-core"
+ }
+ identifier {
+ type: "Archive"
+ value: "https://static.crates.io/crates/predicates-core/predicates-core-1.0.6.crate"
+ }
+ version: "1.0.6"
+ # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same.
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2023
+ month: 11
+ day: 6
+ }
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..48bea6e
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1,2 @@
+# Bug component: 688011
+include platform/prebuilts/rust:main:/OWNERS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..57ec3ac
--- /dev/null
+++ b/README.md
@@ -0,0 +1,25 @@
+# predicates-core
+
+> Traits for **boolean-valued predicate functions** in Rust.
+
+[![Build Status](https://dev.azure.com/assert-rs/assert-rs/_apis/build/status/predicates-rs?branchName=master)](https://dev.azure.com/assert-rs/assert-rs/_build/latest?definitionId=1&branchName=master)
+[![Documentation](https://img.shields.io/badge/docs-master-blue.svg)](https://docs.rs/predicates-core)
+![License](https://img.shields.io/crates/l/predicates-core.svg)
+[![Crates.io](https://img.shields.io/crates/v/predicates-core.svg?maxAge=2592000)](https://crates.io/crates/predicates-core)
+
+[Changelog](https://github.com/assert-rs/predicates-rs/blob/master/crates/core/CHANGELOG.md)
+
+
+## License
+
+`predicates-core` is distributed under the terms of both the MIT license and the
+Apache License (Version 2.0).
+
+See LICENSE-APACHE, and LICENSE-MIT for details.
+
+
+## Credits
+
+Big thanks to [futures-rs](https://github.com/alexcrichton/futures-rs), whose
+slick API design informed a lot of decisions made on the API design of this
+library.
diff --git a/cargo_embargo.json b/cargo_embargo.json
new file mode 100644
index 0000000..9a0a579
--- /dev/null
+++ b/cargo_embargo.json
@@ -0,0 +1,3 @@
+{
+ "tests": true
+}
diff --git a/src/core.rs b/src/core.rs
new file mode 100644
index 0000000..b5aaa7b
--- /dev/null
+++ b/src/core.rs
@@ -0,0 +1,32 @@
+// 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 crate::reflection;
+
+/// Trait for generically evaluating a type against a dynamically created
+/// predicate function.
+///
+/// The exact meaning of `eval` depends on the situation, but will usually
+/// mean that the evaluated item is in some sort of pre-defined set. This is
+/// different from `Ord` and `Eq` in that an `item` will almost never be the
+/// same type as the implementing `Predicate` type.
+pub trait Predicate<Item: ?Sized>: reflection::PredicateReflection {
+ /// Execute this `Predicate` against `variable`, returning the resulting
+ /// boolean.
+ fn eval(&self, variable: &Item) -> bool;
+
+ /// Find a case that proves this predicate as `expected` when run against `variable`.
+ fn find_case<'a>(&'a self, expected: bool, variable: &Item) -> Option<reflection::Case<'a>> {
+ let actual = self.eval(variable);
+ if expected == actual {
+ Some(reflection::Case::new(None, actual))
+ } else {
+ None
+ }
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..e0c9ace
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,25 @@
+// Copyright (c) 2018 The predicates-rs Project Developers.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/license/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.
+
+//! Composable first-order predicate trait.
+//!
+//! This library implements an interface to "predicates" - boolean-valued
+//! functions of one argument. This allows combinatorial logic to be created and
+//! assembled at runtime and then used one or more times for evaluating values.
+//! This sort of object is really useful when creating filters and checks that
+//! can be changed at runtime with user interaction - it allows a clean
+//! separation of concerns where the configuration code can be used to build up
+//! a predicate, and then that predicate can be given to the code that does the
+//! actual filtering without the filtering code knowing anything about user
+//! configuration. See the examples for how this can work.
+
+#![warn(missing_docs, missing_debug_implementations)]
+
+mod core;
+pub use crate::core::*;
+pub mod reflection;
diff --git a/src/reflection.rs b/src/reflection.rs
new file mode 100644
index 0000000..120d1bd
--- /dev/null
+++ b/src/reflection.rs
@@ -0,0 +1,252 @@
+// 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.
+
+//! Introspect into the state of a `Predicate`.
+
+use std::borrow;
+use std::fmt;
+use std::slice;
+
+/// Introspect the state of a `Predicate`.
+pub trait PredicateReflection: fmt::Display {
+ /// Parameters of the current `Predicate`.
+ fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = Parameter<'a>> + 'a> {
+ let params = vec![];
+ Box::new(params.into_iter())
+ }
+
+ /// Nested `Predicate`s of the current `Predicate`.
+ fn children<'a>(&'a self) -> Box<dyn Iterator<Item = Child<'a>> + 'a> {
+ let params = vec![];
+ Box::new(params.into_iter())
+ }
+}
+
+/// A view of a `Predicate` parameter, provided by reflection.
+///
+/// ```rust
+/// use predicates_core;
+///
+/// let param = predicates_core::reflection::Parameter::new("key", &10);
+/// println!("{}", param);
+/// ```
+pub struct Parameter<'a>(&'a str, &'a dyn fmt::Display);
+
+impl<'a> Parameter<'a> {
+ /// Create a new `Parameter`.
+ pub fn new(key: &'a str, value: &'a dyn fmt::Display) -> Self {
+ Self(key, value)
+ }
+
+ /// Access the `Parameter` name.
+ pub fn name(&self) -> &str {
+ self.0
+ }
+
+ /// Access the `Parameter` value.
+ pub fn value(&self) -> &dyn fmt::Display {
+ self.1
+ }
+}
+
+impl<'a> fmt::Display for Parameter<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}: {}", self.0, self.1)
+ }
+}
+
+impl<'a> fmt::Debug for Parameter<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "({:?}, {})", self.0, self.1)
+ }
+}
+
+/// A view of a `Predicate` child, provided by reflection.
+pub struct Child<'a>(&'a str, &'a dyn PredicateReflection);
+
+impl<'a> Child<'a> {
+ /// Create a new `Predicate` child.
+ pub fn new(key: &'a str, value: &'a dyn PredicateReflection) -> Self {
+ Self(key, value)
+ }
+
+ /// Access the `Child`'s name.
+ pub fn name(&self) -> &str {
+ self.0
+ }
+
+ /// Access the `Child` `Predicate`.
+ pub fn value(&self) -> &dyn PredicateReflection {
+ self.1
+ }
+}
+
+impl<'a> fmt::Display for Child<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}: {}", self.0, self.1)
+ }
+}
+
+impl<'a> fmt::Debug for Child<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "({:?}, {})", self.0, self.1)
+ }
+}
+
+/// A descriptive explanation for why a predicate failed.
+pub struct Case<'a> {
+ predicate: Option<&'a dyn PredicateReflection>,
+ result: bool,
+ products: Vec<Product>,
+ children: Vec<Case<'a>>,
+}
+
+impl<'a> Case<'a> {
+ /// Create a new `Case` describing the result of a `Predicate`.
+ pub fn new(predicate: Option<&'a dyn PredicateReflection>, result: bool) -> Self {
+ Self {
+ predicate,
+ result,
+ products: Default::default(),
+ children: Default::default(),
+ }
+ }
+
+ /// Add an additional by product to a `Case`.
+ pub fn add_product(mut self, product: Product) -> Self {
+ self.products.push(product);
+ self
+ }
+
+ /// Add an additional by product to a `Case`.
+ pub fn add_child(mut self, child: Case<'a>) -> Self {
+ self.children.push(child);
+ self
+ }
+
+ /// The `Predicate` that produced this case.
+ pub fn predicate(&self) -> Option<&dyn PredicateReflection> {
+ self.predicate
+ }
+
+ /// The result of this case.
+ pub fn result(&self) -> bool {
+ self.result
+ }
+
+ /// Access the by-products from determining this case.
+ pub fn products(&self) -> CaseProducts<'_> {
+ CaseProducts(self.products.iter())
+ }
+
+ /// Access the sub-cases.
+ pub fn children(&self) -> CaseChildren<'_> {
+ CaseChildren(self.children.iter())
+ }
+}
+
+impl<'a> fmt::Debug for Case<'a> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let predicate = if let Some(ref predicate) = self.predicate {
+ format!("Some({})", predicate)
+ } else {
+ "None".to_owned()
+ };
+ f.debug_struct("Case")
+ .field("predicate", &predicate)
+ .field("result", &self.result)
+ .field("products", &self.products)
+ .field("children", &self.children)
+ .finish()
+ }
+}
+
+/// Iterator over a `Case`s by-products.
+#[derive(Debug, Clone)]
+pub struct CaseProducts<'a>(slice::Iter<'a, Product>);
+
+impl<'a> Iterator for CaseProducts<'a> {
+ type Item = &'a Product;
+
+ fn next(&mut self) -> Option<&'a Product> {
+ self.0.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.0.size_hint()
+ }
+
+ fn count(self) -> usize {
+ self.0.count()
+ }
+}
+
+/// Iterator over a `Case`s sub-cases.
+#[derive(Debug, Clone)]
+pub struct CaseChildren<'a>(slice::Iter<'a, Case<'a>>);
+
+impl<'a> Iterator for CaseChildren<'a> {
+ type Item = &'a Case<'a>;
+
+ fn next(&mut self) -> Option<&'a Case<'a>> {
+ self.0.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.0.size_hint()
+ }
+
+ fn count(self) -> usize {
+ self.0.count()
+ }
+}
+
+/// A by-product of a predicate evaluation.
+///
+/// ```rust
+/// use predicates_core;
+///
+/// let product = predicates_core::reflection::Product::new("key", "value");
+/// println!("{}", product);
+/// let product = predicates_core::reflection::Product::new(format!("key-{}", 5), 30);
+/// println!("{}", product);
+/// ```
+pub struct Product(borrow::Cow<'static, str>, Box<dyn fmt::Display>);
+
+impl Product {
+ /// Create a new `Product`.
+ pub fn new<S, D>(key: S, value: D) -> Self
+ where
+ S: Into<borrow::Cow<'static, str>>,
+ D: fmt::Display + 'static,
+ {
+ Self(key.into(), Box::new(value))
+ }
+
+ /// Access the `Product` name.
+ pub fn name(&self) -> &str {
+ self.0.as_ref()
+ }
+
+ /// Access the `Product` value.
+ pub fn value(&self) -> &dyn fmt::Display {
+ &self.1
+ }
+}
+
+impl fmt::Display for Product {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}: {}", self.0, self.1)
+ }
+}
+
+impl fmt::Debug for Product {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "({:?}, {})", self.0, self.1)
+ }
+}