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 all commits
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 = []
62 changes: 62 additions & 0 deletions enumflags/src/fallible.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use core::convert::TryFrom;
use core::fmt;
use super::BitFlags;
use super::_internal::RawBitFlags;

macro_rules! impl_try_from {
($($ty:ty),*) => {
$(
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> {
let flags = Self::from_bits_truncate(bits);
if flags.bits() == bits {
Ok(flags)
} else {
Err(FromBitsError {
flags,
invalid: bits & !flags.bits(),
})
}
}
}
)*
};
}

impl_try_from! {
u8, u16, u32, u64, usize
}

#[derive(Debug, Copy, Clone)]
pub struct FromBitsError<T: RawBitFlags> {
flags: BitFlags<T>,
invalid: T::Type,
}

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

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

Choose a reason for hiding this comment

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

Since this is a public API, it'd be nice to have a sentence or two of documentation here. You could even write a doctest which tries to convert a number with some invalid flags and then asserts about the results of truncate and invalid_bits. This would kill two birds with one stone, since there aren't really any tests for this functionality right now.


impl<T: RawBitFlags + fmt::Debug> fmt::Display for FromBitsError<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Invalid bits for {:?}: {:#b}", self.flags, self.invalid)
}
}

#[cfg(feature = "std")]
impl<T: RawBitFlags + fmt::Debug> std::error::Error for FromBitsError<T> {
fn description(&self) -> &str {
"invalid bitflags representation"
}
}
1 change: 0 additions & 1 deletion enumflags/src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::{BitFlags, _internal::RawBitFlags};
impl<T> fmt::Debug for BitFlags<T>
where
T: RawBitFlags + fmt::Debug,
T::Type: fmt::Binary + fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let name = T::bitflags_type_name();
Expand Down
18 changes: 15 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(any(test, feature = "std"))]
extern crate core;
use core::{cmp, ops};
use core::iter::FromIterator;
Expand Down Expand Up @@ -89,6 +90,7 @@ pub mod _internal {

use core::ops::{BitAnd, BitOr, BitXor, Not};
use core::cmp::PartialOrd;
use core::fmt;

pub trait BitFlagNum
: Default
Expand All @@ -97,6 +99,8 @@ pub mod _internal {
+ BitXor<Self, Output = Self>
+ Not<Output = Self>
+ PartialOrd<Self>
+ fmt::Debug
+ fmt::Binary
+ Copy
+ Clone {
}
Expand All @@ -116,6 +120,10 @@ pub mod _internal {
// Internal debug formatting implementations
mod formatting;

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

use _internal::RawBitFlags;

/// Represents a set of flags of some type `T`.
Expand Down Expand Up @@ -148,7 +156,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 @@ -201,6 +209,10 @@ where
}
}

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

/// Truncates flags that are illegal
pub fn from_bits_truncate(bits: T::Type) -> Self {
unsafe { BitFlags::new(bits & T::all()) }
Expand Down
10 changes: 10 additions & 0 deletions test_suite/tests/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,13 @@ fn format() {
"0x0F"
);
}

#[test]
fn debug_generic() {
use enumflags2::{BitFlags, _internal::RawBitFlags};

#[derive(Debug)]
struct Debug<T: RawBitFlags>(BitFlags<T>);

let _ = format!("{:?}", Debug(BitFlags::<Test>::all()));
}