Skip to content
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

impl TryFrom<T::Type> for BitFlags<T> #14

Merged
merged 5 commits into from
Oct 4, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions enumflags/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ documentation = "https://docs.rs/enumflags2"
[dependencies]
enumflags2_derive = { version = "0.6.0", path = "../enumflags_derive" }
serde = { version = "^1.0.0", default-features = false, optional = true }

[features]
std = []
27 changes: 27 additions & 0 deletions enumflags/src/fallible.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use core::convert::TryFrom;
use super::{BitFlags, FromBitsError};
use super::_internal::RawBitFlags;

macro_rules! impl_try_from {
() => { };
($ty:ty, $($tt:tt)*) => {
impl_try_from! { $ty }
impl_try_from! { $($tt)* }
};
($ty:ty) => {
Copy link
Owner

Choose a reason for hiding this comment

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

It's not necessary to use 3 rules here. I've pushed a commit onto your branch that shows how this can be done, though ideally it would be squashed into this one.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Makes sense, will make sure to get it all get squashed/cleaned up once it's ready.

impl<T> TryFrom<$ty> for BitFlags<T>
where
T: RawBitFlags<Type=$ty>,
{
type Error = FromBitsError<T>;

fn try_from(bits: T::Type) -> Result<Self, Self::Error> {
Self::try_from_bits(bits)
}
}
};
}

impl_try_from! {
u8, u16, u32, u64, usize
}
2 changes: 1 addition & 1 deletion enumflags/src/formatting.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::fmt::{self, Debug, Binary};
use crate::{BitFlags, _internal::RawBitFlags};
use crate::{BitFlags, FromBitsError, _internal::RawBitFlags};
arcnmx marked this conversation as resolved.
Show resolved Hide resolved

impl<T> fmt::Debug for BitFlags<T>
where
Expand Down
49 changes: 46 additions & 3 deletions enumflags/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,11 @@
//! ## Optional Feature Flags
//!
//! - [`serde`](https://serde.rs/) implements `Serialize` and `Deserialize` for `BitFlags<T>`.
//! - `std` implements `std::error::Error` for `FromBitsError`.
#![warn(missing_docs)]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(all(not(test), not(feature = "std")), no_std)]

#[cfg(test)]
#[cfg(all(test, not(feature = "std")))]
arcnmx marked this conversation as resolved.
Show resolved Hide resolved
extern crate core;
use core::{cmp, ops};
use core::iter::FromIterator;
Expand Down Expand Up @@ -119,6 +120,9 @@ pub mod _internal {
// Internal debug formatting implementations
mod formatting;

// impl TryFrom<T::Type> for BitFlags<T>
mod fallible;

use _internal::RawBitFlags;

/// Represents a set of flags of some type `T`.
Expand Down Expand Up @@ -151,7 +155,7 @@ where

impl<T: RawBitFlags> From<T> for BitFlags<T> {
fn from(t: T) -> BitFlags<T> {
BitFlags { val: t.bits() }
Self::from_flag(t)
}
}

Expand Down Expand Up @@ -204,6 +208,22 @@ where
}
}

pub fn from_flag(t: T) -> Self {
BitFlags { val: t.bits() }
}

pub fn try_from_bits(bits: T::Type) -> Result<Self, FromBitsError<T>> {
let flags = Self::from_bits_truncate(bits);
if flags.bits() == bits {
Ok(flags)
} else {
Err(FromBitsError {
flags,
invalid: bits & !flags.bits(),
})
}
}

Copy link
Owner

Choose a reason for hiding this comment

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

I don't think these should be also exposed as a method. A trait would be enough. In fact, I'm considering #[deprecating] from_bits once this lands.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Huh, I disagree with that philosophy in that I find generic conversion traits often unwieldy to use explicitly when you need them, because type inference often needs help via extra type hints/ascriptions when using something(BitFlags::from) - whereas BitFlags::from_bits assists inference and improves readability. I guess I'm not personally a fan of using conversion traits outside of generic arguments when there's a better explicit option (usually that's ::new I guess).

/// Truncates flags that are illegal
pub fn from_bits_truncate(bits: T::Type) -> Self {
unsafe { BitFlags::new(bits & T::all()) }
Expand Down Expand Up @@ -361,3 +381,26 @@ mod impl_serde {
}
}
}

#[derive(Debug, Copy, Clone)]
pub struct FromBitsError<T: RawBitFlags> {
flags: BitFlags<T>,
invalid: T::Type,
}
meithecatte marked this conversation as resolved.
Show resolved Hide resolved

impl<T: RawBitFlags> FromBitsError<T> {
pub fn truncate(self) -> BitFlags<T> {
self.flags
}

pub fn invalid_bits(self) -> T::Type {
self.invalid
}
}

#[cfg(feature = "std")]
impl<T: RawBitFlags> std::error::Error for FromBitsError<T> {
fn description(&self) -> &str {
"invalid bit representation"
}
}