From 57b38b82a174604938843ad57031d6d8a06fc3b5 Mon Sep 17 00:00:00 2001 From: ozaner <56015962+ozaner@users.noreply.github.com> Date: Tue, 12 Mar 2024 03:30:10 -0400 Subject: [PATCH] Add Flagged struct Requires enumflags2 as a dependency. Can't reexport it since the bitflags macro is not hygienic (see meithecatte/enumflags2#48). --- Cargo.toml | 1 + src/lib.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 39b2f8a..14d67ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +enumflags2 = "0.7.9" diff --git a/src/lib.rs b/src/lib.rs index 7d12d9a..647de43 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,53 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right +use enumflags2::{BitFlag, BitFlags}; + +#[derive(Debug, Clone, Copy)] +pub struct Flagged { + pub value: T, + pub flags: BitFlags +} + +impl Flagged { + pub fn and_then(self, f: impl FnOnce(T) -> Flagged) -> Flagged { + let inner = f(self.value); + Flagged { + value: inner.value, + flags: self.flags | inner.flags, //merge flags + } + } + + pub fn into_result(self) -> Result> { + if self.flags != BitFlags::EMPTY { + Err(self.flags) + } + else { + Ok(self.value) + } + } + + pub fn into_result_against(self, flags: BitFlags) -> Result> { + if self.flags.intersects(flags) { + Err(self.flags & flags) //only include error flags + } + else { + Ok(self.value) + } + } } -#[cfg(test)] -mod tests { - use super::*; +impl From for Flagged { + fn from(value: T) -> Self { + Self { value, flags: BitFlags::EMPTY } + } +} - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); +impl FromIterator> for Flagged, F> { + fn from_iter>>(iter: I) -> Self { + let mut value = vec![]; + let mut flags = BitFlags::EMPTY; + for flagged in iter { + value.push(flagged.value); + flags |= flagged.flags; + } + Self { value, flags } } }