-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Requires enumflags2 as a dependency. Can't reexport it since the bitflags macro is not hygienic (see meithecatte/enumflags2#48).
- Loading branch information
Showing
2 changed files
with
50 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,54 @@ | ||
pub fn add(left: usize, right: usize) -> usize { | ||
left + right | ||
use enumflags2::{BitFlag, BitFlags}; | ||
|
||
#[derive(Debug, Clone, Copy)] | ||
pub struct Flagged<T, F: BitFlag> { | ||
pub value: T, | ||
pub flags: BitFlags<F>, | ||
} | ||
|
||
impl<T, F: BitFlag> Flagged<T, F> { | ||
pub fn and_then<U>(self, f: impl FnOnce(T) -> Flagged<U, F>) -> Flagged<U, F> { | ||
let inner = f(self.value); | ||
Flagged { | ||
value: inner.value, | ||
flags: self.flags | inner.flags, //merge flags | ||
} | ||
} | ||
|
||
pub fn into_result(self) -> Result<T, BitFlags<F>> { | ||
if self.flags != BitFlags::EMPTY { | ||
Err(self.flags) | ||
} else { | ||
Ok(self.value) | ||
} | ||
} | ||
|
||
pub fn into_result_against(self, flags: BitFlags<F>) -> Result<T, BitFlags<F>> { | ||
if self.flags.intersects(flags) { | ||
Err(self.flags & flags) //only include error flags | ||
} else { | ||
Ok(self.value) | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
impl<T, F: BitFlag> From<T> for Flagged<T, F> { | ||
fn from(value: T) -> Self { | ||
Self { | ||
value, | ||
flags: BitFlags::EMPTY, | ||
} | ||
} | ||
} | ||
|
||
#[test] | ||
fn it_works() { | ||
let result = add(2, 2); | ||
assert_eq!(result, 4); | ||
impl<T, F: BitFlag> FromIterator<Flagged<T, F>> for Flagged<Vec<T>, F> { | ||
fn from_iter<I: IntoIterator<Item = Flagged<T, F>>>(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 } | ||
} | ||
} |