Skip to content

Commit

Permalink
Add Flagged struct
Browse files Browse the repository at this point in the history
Requires enumflags2 as a dependency. Can't reexport it since the
bitflags macro is not hygienic (see meithecatte/enumflags2#48).
  • Loading branch information
ozaner committed Mar 12, 2024
1 parent 37d8389 commit 57b38b8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 9 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
57 changes: 48 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<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 }
}
}

0 comments on commit 57b38b8

Please sign in to comment.