Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+65
View File
@@ -0,0 +1,65 @@
//! This module shows an example of code generated by the macro. **IT MUST NOT BE USED OUTSIDE THIS
//! CRATE**.
//!
//! Usually, when you call the `bitflags!` macro, only the `Flags` type would be visible. In this
//! example, the `Field0`, `Iter`, and `IterRaw` types are also exposed so that you can explore
//! their APIs. The `Field0` type can be accessed as `self.0` on an instance of `Flags`.
__declare_public_bitflags! {
/// This is the same `Flags` struct defined in the [crate level example](../index.html#example).
/// Note that this struct is just for documentation purposes only, it must not be used outside
/// this crate.
pub struct Flags
}
__declare_internal_bitflags! {
pub struct Field0: u32
}
__impl_internal_bitflags! {
Field0: u32, Flags {
/// Field `A`.
///
/// This flag has the value `0b00000001`.
const A = 0b00000001;
/// Field `B`.
///
/// This flag has the value `0b00000010`.
const B = 0b00000010;
/// Field `C`.
///
/// This flag has the value `0b00000100`.
const C = 0b00000100;
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
}
}
__impl_public_bitflags_forward! {
Flags: u32, Field0
}
__impl_public_bitflags_ops! {
Flags
}
__impl_public_bitflags_iter! {
Flags: u32, Flags
}
__impl_public_bitflags_consts! {
Flags: u32 {
/// Field `A`.
///
/// This flag has the value `0b00000001`.
const A = 0b00000001;
/// Field `B`.
///
/// This flag has the value `0b00000010`.
const B = 0b00000010;
/// Field `C`.
///
/// This flag has the value `0b00000100`.
const C = 0b00000100;
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
}
}
+262
View File
@@ -0,0 +1,262 @@
//! Conditional trait implementations for external libraries.
/*
How do I support a new external library?
Let's say we want to add support for `my_library`.
First, we create a module under `external`, like `serde` with any specialized code.
Ideally, any utilities in here should just work off the `Flags` trait and maybe a
few other assumed bounds.
Next, re-export the library from the `__private` module here.
Next, define a macro like so:
```rust
#[macro_export]
#[doc(hidden)]
#[cfg(feature = "serde")]
macro_rules! __impl_external_bitflags_my_library {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {
// Implementation goes here
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "my_library"))]
macro_rules! __impl_external_bitflags_my_library {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {};
}
```
Note that the macro is actually defined twice; once for when the `my_library` feature
is available, and once for when it's not. This is because the `__impl_external_bitflags_my_library`
macro is called in an end-user's library, not in `bitflags`. In an end-user's library we don't
know whether or not a particular feature of `bitflags` is enabled, so we unconditionally call
the macro, where the body of that macro depends on the feature flag.
Now, we add our macro call to the `__impl_external_bitflags` macro body:
```rust
__impl_external_bitflags_my_library! {
$InternalBitFlags: $T, $PublicBitFlags {
$(
$(#[$inner $($args)*])*
const $Flag;
)*
}
}
```
*/
pub(crate) mod __private {
#[cfg(feature = "serde")]
pub use serde_core as serde;
#[cfg(feature = "arbitrary")]
pub use arbitrary;
#[cfg(feature = "bytemuck")]
pub use bytemuck;
}
/// Implements traits from external libraries for the internal bitflags type.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_external_bitflags {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {
// Any new library traits impls should be added here
// Use `serde` as an example: generate code when the feature is available,
// and a no-op when it isn't
$crate::__impl_external_bitflags_serde! {
$InternalBitFlags: $T, $PublicBitFlags {
$(
$(#[$inner $($args)*])*
const $Flag;
)*
}
}
$crate::__impl_external_bitflags_arbitrary! {
$InternalBitFlags: $T, $PublicBitFlags {
$(
$(#[$inner $($args)*])*
const $Flag;
)*
}
}
$crate::__impl_external_bitflags_bytemuck! {
$InternalBitFlags: $T, $PublicBitFlags {
$(
$(#[$inner $($args)*])*
const $Flag;
)*
}
}
};
}
#[cfg(feature = "serde")]
pub mod serde;
/// Implement `Serialize` and `Deserialize` for the internal bitflags type.
#[macro_export]
#[doc(hidden)]
#[cfg(feature = "serde")]
macro_rules! __impl_external_bitflags_serde {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {
impl $crate::__private::serde::Serialize for $InternalBitFlags {
fn serialize<S: $crate::__private::serde::Serializer>(
&self,
serializer: S,
) -> $crate::__private::core::result::Result<S::Ok, S::Error> {
$crate::serde::serialize(
&$PublicBitFlags::from_bits_retain(self.bits()),
serializer,
)
}
}
impl<'de> $crate::__private::serde::Deserialize<'de> for $InternalBitFlags {
fn deserialize<D: $crate::__private::serde::Deserializer<'de>>(
deserializer: D,
) -> $crate::__private::core::result::Result<Self, D::Error> {
let flags: $PublicBitFlags = $crate::serde::deserialize(deserializer)?;
$crate::__private::core::result::Result::Ok(flags.0)
}
}
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "serde"))]
macro_rules! __impl_external_bitflags_serde {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {};
}
#[cfg(feature = "arbitrary")]
pub mod arbitrary;
#[cfg(feature = "bytemuck")]
mod bytemuck;
/// Implement `Arbitrary` for the internal bitflags type.
#[macro_export]
#[doc(hidden)]
#[cfg(feature = "arbitrary")]
macro_rules! __impl_external_bitflags_arbitrary {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {
impl<'a> $crate::__private::arbitrary::Arbitrary<'a> for $InternalBitFlags {
fn arbitrary(
u: &mut $crate::__private::arbitrary::Unstructured<'a>,
) -> $crate::__private::arbitrary::Result<Self> {
$crate::arbitrary::arbitrary::<$PublicBitFlags>(u).map(|flags| flags.0)
}
}
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "arbitrary"))]
macro_rules! __impl_external_bitflags_arbitrary {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {};
}
/// Implement `Pod` and `Zeroable` for the internal bitflags type.
#[macro_export]
#[doc(hidden)]
#[cfg(feature = "bytemuck")]
macro_rules! __impl_external_bitflags_bytemuck {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {
// SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T,
// and $T implements Pod
unsafe impl $crate::__private::bytemuck::Pod for $InternalBitFlags where
$T: $crate::__private::bytemuck::Pod
{
}
// SAFETY: $InternalBitFlags is guaranteed to have the same ABI as $T,
// and $T implements Zeroable
unsafe impl $crate::__private::bytemuck::Zeroable for $InternalBitFlags where
$T: $crate::__private::bytemuck::Zeroable
{
}
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "bytemuck"))]
macro_rules! __impl_external_bitflags_bytemuck {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt;
)*
}
) => {};
}
+33
View File
@@ -0,0 +1,33 @@
//! Specialized fuzzing for flags types using `arbitrary`.
use crate::Flags;
/**
Generate some arbitrary flags value with only known bits set.
*/
pub fn arbitrary<'a, B: Flags>(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<B>
where
B::Bits: arbitrary::Arbitrary<'a>,
{
B::from_bits(u.arbitrary()?).ok_or(arbitrary::Error::IncorrectFormat)
}
#[cfg(test)]
mod tests {
use arbitrary::Arbitrary;
bitflags! {
#[derive(Arbitrary)]
struct Color: u32 {
const RED = 0x1;
const GREEN = 0x2;
const BLUE = 0x4;
}
}
#[test]
fn test_arbitrary() {
let mut unstructured = arbitrary::Unstructured::new(&[0_u8; 256]);
let _color = Color::arbitrary(&mut unstructured);
}
}
+19
View File
@@ -0,0 +1,19 @@
#[cfg(test)]
mod tests {
use bytemuck::{Pod, Zeroable};
bitflags! {
#[derive(Pod, Zeroable, Clone, Copy)]
#[repr(transparent)]
struct Color: u32 {
const RED = 0x1;
const GREEN = 0x2;
const BLUE = 0x4;
}
}
#[test]
fn test_bytemuck() {
assert_eq!(0x1, bytemuck::cast::<Color, u32>(Color::RED));
}
}
+94
View File
@@ -0,0 +1,94 @@
//! Specialized serialization for flags types using `serde`.
use crate::{
parser::{self, ParseHex, WriteHex},
Flags,
};
use core::{fmt, str};
use serde_core::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
/**
Serialize a set of flags as a human-readable string or their underlying bits.
Any unknown bits will be retained.
*/
pub fn serialize<B: Flags, S: Serializer>(flags: &B, serializer: S) -> Result<S::Ok, S::Error>
where
B::Bits: WriteHex + Serialize,
{
// Serialize human-readable flags as a string like `"A | B"`
if serializer.is_human_readable() {
serializer.collect_str(&parser::AsDisplay(flags))
}
// Serialize non-human-readable flags directly as the underlying bits
else {
flags.bits().serialize(serializer)
}
}
/**
Deserialize a set of flags from a human-readable string or their underlying bits.
Any unknown bits will be retained.
*/
pub fn deserialize<'de, B: Flags, D: Deserializer<'de>>(deserializer: D) -> Result<B, D::Error>
where
B::Bits: ParseHex + Deserialize<'de>,
{
if deserializer.is_human_readable() {
// Deserialize human-readable flags by parsing them from strings like `"A | B"`
struct FlagsVisitor<B>(core::marker::PhantomData<B>);
impl<'de, B: Flags> Visitor<'de> for FlagsVisitor<B>
where
B::Bits: ParseHex,
{
type Value = B;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string value of `|` separated flags")
}
fn visit_str<E: Error>(self, flags: &str) -> Result<Self::Value, E> {
parser::from_str(flags).map_err(|e| E::custom(e))
}
}
deserializer.deserialize_str(FlagsVisitor(Default::default()))
} else {
// Deserialize non-human-readable flags directly from the underlying bits
let bits = B::Bits::deserialize(deserializer)?;
Ok(B::from_bits_retain(bits))
}
}
#[cfg(test)]
mod tests {
use serde_test::{assert_tokens, Configure, Token::*};
bitflags! {
#[derive(serde_lib::Serialize, serde_lib::Deserialize, Debug, PartialEq, Eq)]
#[serde(crate = "serde_lib", transparent)]
struct SerdeFlags: u32 {
const A = 1;
const B = 2;
const C = 4;
const D = 8;
}
}
#[test]
fn test_serde_bitflags_default() {
assert_tokens(&SerdeFlags::empty().readable(), &[Str("")]);
assert_tokens(&SerdeFlags::empty().compact(), &[U32(0)]);
assert_tokens(&(SerdeFlags::A | SerdeFlags::B).readable(), &[Str("A | B")]);
assert_tokens(&(SerdeFlags::A | SerdeFlags::B).compact(), &[U32(1 | 2)]);
}
}
+125
View File
@@ -0,0 +1,125 @@
//! Generate the internal `bitflags`-facing flags type.
//!
//! The code generated here is owned by `bitflags`, but still part of its public API.
//! Changes to the types generated here need to be considered like any other public API change.
/// Declare the `bitflags`-facing bitflags struct.
///
/// This type is part of the `bitflags` crate's public API, but not part of the user's.
#[macro_export]
#[doc(hidden)]
macro_rules! __declare_internal_bitflags {
(
$vis:vis struct $InternalBitFlags:ident: $T:ty
) => {
// NOTE: The ABI of this type is _guaranteed_ to be the same as `T`
// This is relied on by some external libraries like `bytemuck` to make
// its `unsafe` trait impls sound.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
$vis struct $InternalBitFlags($T);
};
}
/// Implement functions on the private (bitflags-facing) bitflags type.
///
/// Methods and trait implementations can be freely added here without breaking end-users.
/// If we want to expose new functionality to `#[derive]`, this is the place to do it.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_internal_bitflags {
(
$InternalBitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt = $value:expr;
)*
}
) => {
// NOTE: This impl is also used to prevent using bits types from non-primitive types
// in the `bitflags` macro. If this approach is changed, this guard will need to be
// retained somehow
impl $crate::__private::PublicFlags for $PublicBitFlags {
type Primitive = $T;
type Internal = $InternalBitFlags;
}
impl $crate::__private::core::default::Default for $InternalBitFlags {
#[inline]
fn default() -> Self {
$InternalBitFlags::empty()
}
}
impl $crate::__private::core::fmt::Debug for $InternalBitFlags {
fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter<'_>) -> $crate::__private::core::fmt::Result {
if self.is_empty() {
// If no flags are set then write an empty hex flag to avoid
// writing an empty string. In some contexts, like serialization,
// an empty string is preferable, but it may be unexpected in
// others for a format not to produce any output.
//
// We can remove this `0x0` and remain compatible with `FromStr`,
// because an empty string will still parse to an empty set of flags,
// just like `0x0` does.
$crate::__private::core::write!(f, "{:#x}", <$T as $crate::Bits>::EMPTY)
} else {
$crate::__private::core::fmt::Display::fmt(self, f)
}
}
}
impl $crate::__private::core::fmt::Display for $InternalBitFlags {
fn fmt(&self, f: &mut $crate::__private::core::fmt::Formatter<'_>) -> $crate::__private::core::fmt::Result {
$crate::parser::to_writer(&$PublicBitFlags(*self), f)
}
}
impl $crate::__private::core::str::FromStr for $InternalBitFlags {
type Err = $crate::parser::ParseError;
fn from_str(s: &str) -> $crate::__private::core::result::Result<Self, Self::Err> {
$crate::parser::from_str::<$PublicBitFlags>(s).map(|flags| flags.0)
}
}
impl $crate::__private::core::convert::AsRef<$T> for $InternalBitFlags {
fn as_ref(&self) -> &$T {
&self.0
}
}
impl $crate::__private::core::convert::From<$T> for $InternalBitFlags {
fn from(bits: $T) -> Self {
Self::from_bits_retain(bits)
}
}
// The internal flags type offers a similar API to the public one
$crate::__impl_public_bitflags! {
$InternalBitFlags: $T, $PublicBitFlags {
$(
$(#[$inner $($args)*])*
const $Flag = $value;
)*
}
}
$crate::__impl_public_bitflags_ops! {
$InternalBitFlags
}
$crate::__impl_public_bitflags_iter! {
$InternalBitFlags: $T, $PublicBitFlags
}
impl $InternalBitFlags {
/// Returns a mutable reference to the raw value of the flags currently stored.
#[inline]
pub fn bits_mut(&mut self) -> &mut $T {
&mut self.0
}
}
};
}
+214
View File
@@ -0,0 +1,214 @@
/*!
Yield the bits of a source flags value in a set of contained flags values.
*/
use crate::{Flag, Flags};
/**
An iterator over flags values.
This iterator will yield flags values for contained, defined flags first, with any remaining bits yielded
as a final flags value.
*/
pub struct Iter<B: 'static> {
inner: IterNames<B>,
done: bool,
}
impl<B: Flags> Iter<B> {
pub(crate) fn new(flags: &B) -> Self {
Iter {
inner: IterNames::new(flags),
done: false,
}
}
}
impl<B: 'static> Iter<B> {
// Used by the `bitflags` macro
#[doc(hidden)]
pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, remaining: B) -> Self {
Iter {
inner: IterNames::__private_const_new(flags, source, remaining),
done: false,
}
}
}
impl<B: Flags> Iterator for Iter<B> {
type Item = B;
fn next(&mut self) -> Option<Self::Item> {
match self.inner.next() {
Some((_, flag)) => Some(flag),
None if !self.done => {
self.done = true;
// After iterating through valid names, if there are any bits left over
// then return one final value that includes them. This makes `into_iter`
// and `from_iter` roundtrip
if !self.inner.remaining().is_empty() {
Some(B::from_bits_retain(self.inner.remaining.bits()))
} else {
None
}
}
None => None,
}
}
}
/**
An iterator over flags values.
This iterator only yields flags values for contained, defined, named flags. Any remaining bits
won't be yielded, but can be found with the [`IterNames::remaining`] method.
*/
pub struct IterNames<B: 'static> {
flags: &'static [Flag<B>],
idx: usize,
source: B,
remaining: B,
}
impl<B: Flags> IterNames<B> {
pub(crate) fn new(flags: &B) -> Self {
IterNames {
flags: B::FLAGS,
idx: 0,
remaining: B::from_bits_retain(flags.bits()),
source: B::from_bits_retain(flags.bits()),
}
}
}
impl<B: 'static> IterNames<B> {
// Used by the bitflags macro
#[doc(hidden)]
pub const fn __private_const_new(flags: &'static [Flag<B>], source: B, remaining: B) -> Self {
IterNames {
flags,
idx: 0,
remaining,
source,
}
}
/// Get a flags value of any remaining bits that haven't been yielded yet.
///
/// Once the iterator has finished, this method can be used to
/// check whether or not there are any bits that didn't correspond
/// to a contained, defined, named flag remaining.
pub fn remaining(&self) -> &B {
&self.remaining
}
}
impl<B: Flags> Iterator for IterNames<B> {
type Item = (&'static str, B);
fn next(&mut self) -> Option<Self::Item> {
while let Some(flag) = self.flags.get(self.idx) {
// Short-circuit if our state is empty
if self.remaining.is_empty() {
return None;
}
self.idx += 1;
// Skip unnamed flags
if flag.name().is_empty() {
continue;
}
let bits = flag.value().bits();
// If the flag is set in the original source _and_ it has bits that haven't
// been covered by a previous flag yet then yield it. These conditions cover
// two cases for multi-bit flags:
//
// 1. When flags partially overlap, such as `0b00000001` and `0b00000101`, we'll
// yield both flags.
// 2. When flags fully overlap, such as in convenience flags that are a shorthand for others,
// we won't yield both flags.
if self.source.contains(B::from_bits_retain(bits))
&& self.remaining.intersects(B::from_bits_retain(bits))
{
self.remaining.remove(B::from_bits_retain(bits));
return Some((flag.name(), B::from_bits_retain(bits)));
}
}
None
}
}
/**
An iterator over all defined named flags.
This iterator will yield flags values for all defined named flags, regardless of
whether they are contained in a particular flags value.
*/
pub struct IterDefinedNames<B: 'static> {
flags: &'static [Flag<B>],
idx: usize,
}
impl<B: Flags> IterDefinedNames<B> {
pub(crate) fn new() -> Self {
IterDefinedNames {
flags: B::FLAGS,
idx: 0,
}
}
}
impl<B: Flags> Iterator for IterDefinedNames<B> {
type Item = (&'static str, B);
fn next(&mut self) -> Option<Self::Item> {
while let Some(flag) = self.flags.get(self.idx) {
self.idx += 1;
// Only yield named flags
if flag.is_named() {
return Some((flag.name(), B::from_bits_retain(flag.value().bits())));
}
}
None
}
}
/**
An iterator over all defined names for a specific flags value.
*/
pub struct IterEqualNames<T: Flags> {
inner: IterDefinedNames<T>,
bits: T::Bits,
}
impl<T: Flags> IterEqualNames<T> {
#[inline]
pub(crate) fn new(value: &T) -> Self {
Self {
inner: <T as Flags>::iter_defined_names(),
bits: value.bits(),
}
}
}
impl<T: Flags> Iterator for IterEqualNames<T> {
type Item = &'static str;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
for (n, f) in self.inner.by_ref() {
if f.bits() == self.bits {
return Some(n);
}
}
None
}
}
+1244
View File
File diff suppressed because it is too large Load Diff
+332
View File
@@ -0,0 +1,332 @@
/*!
Parsing flags from text.
Format and parse a flags value as text using the following grammar:
- _Flags:_ (_Whitespace_ _Flag_ _Whitespace_)`|`*
- _Flag:_ _Name_ | _Hex Number_
- _Name:_ The name of any defined flag
- _Hex Number_: `0x`([0-9a-fA-F])*
- _Whitespace_: (\s)*
As an example, this is how `Flags::A | Flags::B | 0x0c` can be represented as text:
```text
A | B | 0x0c
```
Alternatively, it could be represented without whitespace:
```text
A|B|0x0C
```
Note that identifiers are *case-sensitive*, so the following is *not equivalent*:
```text
a|b|0x0C
```
*/
#![allow(clippy::let_unit_value)]
use core::fmt::{self, Write};
use crate::{Bits, Flags};
/**
Write a flags value as text.
Any bits that aren't part of a contained flag will be formatted as a hex number.
*/
pub fn to_writer<B: Flags>(flags: &B, mut writer: impl Write) -> Result<(), fmt::Error>
where
B::Bits: WriteHex,
{
// A formatter for bitflags that produces text output like:
//
// A | B | 0xf6
//
// The names of set flags are written in a bar-separated-format,
// followed by a hex number of any remaining bits that are set
// but don't correspond to any flags.
// Iterate over known flag values
let mut first = true;
let mut iter = flags.iter_names();
for (name, _) in &mut iter {
if !first {
writer.write_str(" | ")?;
}
first = false;
writer.write_str(name)?;
}
// Append any extra bits that correspond to flags to the end of the format
let remaining = iter.remaining().bits();
if remaining != B::Bits::EMPTY {
if !first {
writer.write_str(" | ")?;
}
writer.write_str("0x")?;
remaining.write_hex(writer)?;
}
fmt::Result::Ok(())
}
#[cfg(feature = "serde")]
pub(crate) struct AsDisplay<'a, B>(pub(crate) &'a B);
#[cfg(feature = "serde")]
impl<'a, B: Flags> fmt::Display for AsDisplay<'a, B>
where
B::Bits: WriteHex,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
to_writer(self.0, f)
}
}
/**
Parse a flags value from text.
This function will fail on any names that don't correspond to defined flags.
Unknown bits will be retained.
*/
pub fn from_str<B: Flags>(input: &str) -> Result<B, ParseError>
where
B::Bits: ParseHex,
{
let mut parsed_flags = B::empty();
// If the input is empty then return an empty set of flags
if input.trim().is_empty() {
return Ok(parsed_flags);
}
for flag in input.split('|') {
let flag = flag.trim();
// If the flag is empty then we've got missing input
if flag.is_empty() {
return Err(ParseError::empty_flag());
}
// If the flag starts with `0x` then it's a hex number
// Parse it directly to the underlying bits type
let parsed_flag = if let Some(flag) = flag.strip_prefix("0x") {
let bits =
<B::Bits>::parse_hex(flag).map_err(|_| ParseError::invalid_hex_flag(flag))?;
B::from_bits_retain(bits)
}
// Otherwise the flag is a name
// The generated flags type will determine whether
// or not it's a valid identifier
else {
B::from_name(flag).ok_or_else(|| ParseError::invalid_named_flag(flag))?
};
parsed_flags.insert(parsed_flag);
}
Ok(parsed_flags)
}
/**
Write a flags value as text, ignoring any unknown bits.
*/
pub fn to_writer_truncate<B: Flags>(flags: &B, writer: impl Write) -> Result<(), fmt::Error>
where
B::Bits: WriteHex,
{
to_writer(&B::from_bits_truncate(flags.bits()), writer)
}
/**
Parse a flags value from text.
This function will fail on any names that don't correspond to defined flags.
Unknown bits will be ignored.
*/
pub fn from_str_truncate<B: Flags>(input: &str) -> Result<B, ParseError>
where
B::Bits: ParseHex,
{
Ok(B::from_bits_truncate(from_str::<B>(input)?.bits()))
}
/**
Write only the contained, defined, named flags in a flags value as text.
*/
pub fn to_writer_strict<B: Flags>(flags: &B, mut writer: impl Write) -> Result<(), fmt::Error> {
// This is a simplified version of `to_writer` that ignores
// any bits not corresponding to a named flag
let mut first = true;
let mut iter = flags.iter_names();
for (name, _) in &mut iter {
if !first {
writer.write_str(" | ")?;
}
first = false;
writer.write_str(name)?;
}
fmt::Result::Ok(())
}
/**
Parse a flags value from text.
This function will fail on any names that don't correspond to defined flags.
This function will fail to parse hex values.
*/
pub fn from_str_strict<B: Flags>(input: &str) -> Result<B, ParseError> {
// This is a simplified version of `from_str` that ignores
// any bits not corresponding to a named flag
let mut parsed_flags = B::empty();
// If the input is empty then return an empty set of flags
if input.trim().is_empty() {
return Ok(parsed_flags);
}
for flag in input.split('|') {
let flag = flag.trim();
// If the flag is empty then we've got missing input
if flag.is_empty() {
return Err(ParseError::empty_flag());
}
// If the flag starts with `0x` then it's a hex number
// These aren't supported in the strict parser
if flag.starts_with("0x") {
return Err(ParseError::invalid_hex_flag("unsupported hex flag value"));
}
let parsed_flag = B::from_name(flag).ok_or_else(|| ParseError::invalid_named_flag(flag))?;
parsed_flags.insert(parsed_flag);
}
Ok(parsed_flags)
}
/**
Encode a value as a hex string.
Implementors of this trait should not write the `0x` prefix.
*/
pub trait WriteHex {
/// Write the value as hex.
fn write_hex<W: fmt::Write>(&self, writer: W) -> fmt::Result;
}
/**
Parse a value from a hex string.
*/
pub trait ParseHex {
/// Parse the value from hex.
fn parse_hex(input: &str) -> Result<Self, ParseError>
where
Self: Sized;
}
/// An error encountered while parsing flags from text.
#[derive(Debug)]
pub struct ParseError(ParseErrorKind);
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum ParseErrorKind {
EmptyFlag,
InvalidNamedFlag {
#[cfg(not(feature = "std"))]
got: (),
#[cfg(feature = "std")]
got: String,
},
InvalidHexFlag {
#[cfg(not(feature = "std"))]
got: (),
#[cfg(feature = "std")]
got: String,
},
}
impl ParseError {
/// An invalid hex flag was encountered.
pub fn invalid_hex_flag(flag: impl fmt::Display) -> Self {
let _flag = flag;
let got = {
#[cfg(feature = "std")]
{
_flag.to_string()
}
};
ParseError(ParseErrorKind::InvalidHexFlag { got })
}
/// A named flag that doesn't correspond to any on the flags type was encountered.
pub fn invalid_named_flag(flag: impl fmt::Display) -> Self {
let _flag = flag;
let got = {
#[cfg(feature = "std")]
{
_flag.to_string()
}
};
ParseError(ParseErrorKind::InvalidNamedFlag { got })
}
/// A hex or named flag wasn't found between separators.
pub const fn empty_flag() -> Self {
ParseError(ParseErrorKind::EmptyFlag)
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
ParseErrorKind::InvalidNamedFlag { got } => {
let _got = got;
write!(f, "unrecognized named flag")?;
#[cfg(feature = "std")]
{
write!(f, " `{}`", _got)?;
}
}
ParseErrorKind::InvalidHexFlag { got } => {
let _got = got;
write!(f, "invalid hex flag")?;
#[cfg(feature = "std")]
{
write!(f, " `{}`", _got)?;
}
}
ParseErrorKind::EmptyFlag => {
write!(f, "encountered empty flag")?;
}
}
Ok(())
}
}
#[cfg(feature = "std")]
impl std::error::Error for ParseError {}
+626
View File
@@ -0,0 +1,626 @@
//! Generate the user-facing flags type.
//!
//! The code here belongs to the end-user, so new trait implementations and methods can't be
//! added without potentially breaking users.
/// Declare the user-facing bitflags struct.
///
/// This type is guaranteed to be a newtype with a `bitflags`-facing type as its single field.
#[macro_export]
#[doc(hidden)]
macro_rules! __declare_public_bitflags {
(
$(#[$outer:meta])*
$vis:vis struct $PublicBitFlags:ident
) => {
$(#[$outer])*
$vis struct $PublicBitFlags(<$PublicBitFlags as $crate::__private::PublicFlags>::Internal);
};
}
/// Implement functions on the public (user-facing) bitflags type.
///
/// We need to be careful about adding new methods and trait implementations here because they
/// could conflict with items added by the end-user.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_public_bitflags_forward {
(
$(#[$outer:meta])*
$PublicBitFlags:ident: $T:ty, $InternalBitFlags:ident
) => {
$crate::__impl_bitflags! {
params: self, bits, name, other, value;
$(#[$outer])*
$PublicBitFlags: $T {
fn empty() {
Self($InternalBitFlags::empty())
}
fn all() {
Self($InternalBitFlags::all())
}
fn bits(&self) {
self.0.bits()
}
fn from_bits(bits) {
match $InternalBitFlags::from_bits(bits) {
$crate::__private::core::option::Option::Some(bits) => $crate::__private::core::option::Option::Some(Self(bits)),
$crate::__private::core::option::Option::None => $crate::__private::core::option::Option::None,
}
}
fn from_bits_truncate(bits) {
Self($InternalBitFlags::from_bits_truncate(bits))
}
fn from_bits_retain(bits) {
Self($InternalBitFlags::from_bits_retain(bits))
}
fn from_name(name) {
match $InternalBitFlags::from_name(name) {
$crate::__private::core::option::Option::Some(bits) => $crate::__private::core::option::Option::Some(Self(bits)),
$crate::__private::core::option::Option::None => $crate::__private::core::option::Option::None,
}
}
fn is_empty(&self) {
self.0.is_empty()
}
fn is_all(&self) {
self.0.is_all()
}
fn intersects(&self, other) {
self.0.intersects(other.0)
}
fn contains(&self, other) {
self.0.contains(other.0)
}
fn insert(&mut self, other) {
self.0.insert(other.0)
}
fn remove(&mut self, other) {
self.0.remove(other.0)
}
fn toggle(&mut self, other) {
self.0.toggle(other.0)
}
fn set(&mut self, other, value) {
self.0.set(other.0, value)
}
fn intersection(self, other) {
Self(self.0.intersection(other.0))
}
fn union(self, other) {
Self(self.0.union(other.0))
}
fn difference(self, other) {
Self(self.0.difference(other.0))
}
fn symmetric_difference(self, other) {
Self(self.0.symmetric_difference(other.0))
}
fn complement(self) {
Self(self.0.complement())
}
}
}
};
}
/// Implement functions on the public (user-facing) bitflags type.
///
/// We need to be careful about adding new methods and trait implementations here because they
/// could conflict with items added by the end-user.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_public_bitflags {
(
$(#[$outer:meta])*
$BitFlags:ident: $T:ty, $PublicBitFlags:ident {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt = $value:expr;
)*
}
) => {
$crate::__impl_bitflags! {
params: self, bits, name, other, value;
$(#[$outer])*
$BitFlags: $T {
fn empty() {
Self(<$T as $crate::Bits>::EMPTY)
}
fn all() {
const ALL: $BitFlags = {
let mut truncated = <$T as $crate::Bits>::EMPTY;
let mut _i = 0;
$(
$crate::__bitflags_expr_safe_attrs!(
$(#[$inner $($args)*])*
{{
truncated |= <$PublicBitFlags as $crate::Flags>::FLAGS[_i]
.value().bits();
_i += 1;
}}
);
)*
$BitFlags(truncated)
};
ALL
}
fn bits(&self) {
self.0
}
fn from_bits(bits) {
let truncated = Self::from_bits_truncate(bits).0;
if truncated == bits {
$crate::__private::core::option::Option::Some(Self(bits))
} else {
$crate::__private::core::option::Option::None
}
}
fn from_bits_truncate(bits) {
Self(bits & Self::all().0)
}
fn from_bits_retain(bits) {
Self(bits)
}
fn from_name(name) {
mod __bitflags_flag_names {
#[allow(unused_imports)]
use super::*;
$(
$crate::__bitflags_flag_name!(
$(#[$inner $($args)*])*
{ pub(super) const $Flag = $Flag }
);
)*
}
$(
$crate::__bitflags_flag!({
name: $Flag,
named: {{
$crate::__bitflags_expr_safe_attrs!(
$(#[$inner $($args)*])*
{
if name == __bitflags_flag_names::$Flag {
return $crate::__private::core::option::Option::Some(Self($PublicBitFlags::$Flag.bits()));
}
}
);
}},
unnamed: {},
});
)*
let _ = name;
$crate::__private::core::option::Option::None
}
fn is_empty(&self) {
self.0 == <$T as $crate::Bits>::EMPTY
}
fn is_all(&self) {
// NOTE: We check against `Self::all` here, not `Self::Bits::ALL`
// because the set of all flags may not use all bits
Self::all().0 | self.0 == self.0
}
fn intersects(&self, other) {
self.0 & other.0 != <$T as $crate::Bits>::EMPTY
}
fn contains(&self, other) {
self.0 & other.0 == other.0
}
fn insert(&mut self, other) {
*self = Self(self.0).union(other);
}
fn remove(&mut self, other) {
*self = Self(self.0).difference(other);
}
fn toggle(&mut self, other) {
*self = Self(self.0).symmetric_difference(other);
}
fn set(&mut self, other, value) {
if value {
self.insert(other);
} else {
self.remove(other);
}
}
fn intersection(self, other) {
Self(self.0 & other.0)
}
fn union(self, other) {
Self(self.0 | other.0)
}
fn difference(self, other) {
Self(self.0 & !other.0)
}
fn symmetric_difference(self, other) {
Self(self.0 ^ other.0)
}
fn complement(self) {
Self::from_bits_truncate(!self.0)
}
}
}
};
}
/// Implement iterators on the public (user-facing) bitflags type.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_public_bitflags_iter {
(
$(#[$outer:meta])*
$BitFlags:ident: $T:ty, $PublicBitFlags:ident
) => {
$(#[$outer])*
impl $BitFlags {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> $crate::iter::Iter<$PublicBitFlags> {
$crate::iter::Iter::__private_const_new(
<$PublicBitFlags as $crate::Flags>::FLAGS,
$PublicBitFlags::from_bits_retain(self.bits()),
$PublicBitFlags::from_bits_retain(self.bits()),
)
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self) -> $crate::iter::IterNames<$PublicBitFlags> {
$crate::iter::IterNames::__private_const_new(
<$PublicBitFlags as $crate::Flags>::FLAGS,
$PublicBitFlags::from_bits_retain(self.bits()),
$PublicBitFlags::from_bits_retain(self.bits()),
)
}
}
$(#[$outer:meta])*
impl $crate::__private::core::iter::IntoIterator for $BitFlags {
type Item = $PublicBitFlags;
type IntoIter = $crate::iter::Iter<$PublicBitFlags>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
};
}
/// Implement traits on the public (user-facing) bitflags type.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_public_bitflags_ops {
(
$(#[$outer:meta])*
$PublicBitFlags:ident
) => {
$(#[$outer])*
impl $crate::__private::core::fmt::Binary for $PublicBitFlags {
fn fmt(
&self,
f: &mut $crate::__private::core::fmt::Formatter,
) -> $crate::__private::core::fmt::Result {
let inner = self.0;
$crate::__private::core::fmt::Binary::fmt(&inner, f)
}
}
$(#[$outer])*
impl $crate::__private::core::fmt::Octal for $PublicBitFlags {
fn fmt(
&self,
f: &mut $crate::__private::core::fmt::Formatter,
) -> $crate::__private::core::fmt::Result {
let inner = self.0;
$crate::__private::core::fmt::Octal::fmt(&inner, f)
}
}
$(#[$outer])*
impl $crate::__private::core::fmt::LowerHex for $PublicBitFlags {
fn fmt(
&self,
f: &mut $crate::__private::core::fmt::Formatter,
) -> $crate::__private::core::fmt::Result {
let inner = self.0;
$crate::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
$(#[$outer])*
impl $crate::__private::core::fmt::UpperHex for $PublicBitFlags {
fn fmt(
&self,
f: &mut $crate::__private::core::fmt::Formatter,
) -> $crate::__private::core::fmt::Result {
let inner = self.0;
$crate::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
$(#[$outer])*
impl $crate::__private::core::ops::BitOr for $PublicBitFlags {
type Output = Self;
/// The bitwise or (`|`) of the bits in `self` and `other`.
#[inline]
fn bitor(self, other: $PublicBitFlags) -> Self {
self.union(other)
}
}
$(#[$outer])*
impl $crate::__private::core::ops::BitOrAssign for $PublicBitFlags {
/// The bitwise or (`|`) of the bits in `self` and `other`.
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.insert(other);
}
}
$(#[$outer])*
impl $crate::__private::core::ops::BitXor for $PublicBitFlags {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
$(#[$outer])*
impl $crate::__private::core::ops::BitXorAssign for $PublicBitFlags {
/// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
#[inline]
fn bitxor_assign(&mut self, other: Self) {
self.toggle(other);
}
}
$(#[$outer])*
impl $crate::__private::core::ops::BitAnd for $PublicBitFlags {
type Output = Self;
/// The bitwise and (`&`) of the bits in `self` and `other`.
#[inline]
fn bitand(self, other: Self) -> Self {
self.intersection(other)
}
}
$(#[$outer])*
impl $crate::__private::core::ops::BitAndAssign for $PublicBitFlags {
/// The bitwise and (`&`) of the bits in `self` and `other`.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self = Self::from_bits_retain(self.bits()).intersection(other);
}
}
$(#[$outer])*
impl $crate::__private::core::ops::Sub for $PublicBitFlags {
type Output = Self;
/// The intersection of `self` with the complement of `other` (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self {
self.difference(other)
}
}
$(#[$outer])*
impl $crate::__private::core::ops::SubAssign for $PublicBitFlags {
/// The intersection of `self` with the complement of `other` (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) {
self.remove(other);
}
}
$(#[$outer])*
impl $crate::__private::core::ops::Not for $PublicBitFlags {
type Output = Self;
/// The bitwise negation (`!`) of the bits in `self`, truncating the result.
#[inline]
fn not(self) -> Self {
self.complement()
}
}
$(#[$outer])*
impl $crate::__private::core::iter::Extend<$PublicBitFlags> for $PublicBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: $crate::__private::core::iter::IntoIterator<Item = Self>>(
&mut self,
iterator: T,
) {
for item in iterator {
self.insert(item)
}
}
}
$(#[$outer])*
impl $crate::__private::core::iter::FromIterator<$PublicBitFlags> for $PublicBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: $crate::__private::core::iter::IntoIterator<Item = Self>>(
iterator: T,
) -> Self {
use $crate::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
};
}
/// Implement constants on the public (user-facing) bitflags type.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_public_bitflags_consts {
(
$(#[$outer:meta])*
$PublicBitFlags:ident: $T:ty {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:tt = $value:expr;
)*
}
) => {
$(#[$outer])*
impl $PublicBitFlags {
$(
$crate::__bitflags_flag!({
name: $Flag,
named: {
$crate::__bitflags_item_safe_attrs!(
$(#[$inner $($args)*])*
{
pub const $Flag: Self = Self::from_bits_retain($value);
}
);
},
unnamed: {},
});
)*
}
$(#[$outer])*
impl $crate::Flags for $PublicBitFlags {
const FLAGS: &'static [$crate::Flag<$PublicBitFlags>] = {
mod __bitflags_flag_names {
#[allow(unused_imports)]
use super::*;
$(
$crate::__bitflags_flag_name!(
$(#[$inner $($args)*])*
{ pub(super) const $Flag = $Flag });
)*
}
&[
$(
$crate::__bitflags_flag!({
name: $Flag,
named: {
$crate::__bitflags_expr_safe_attrs!(
$(#[$inner $($args)*])*
{
$crate::Flag::new(__bitflags_flag_names::$Flag, $PublicBitFlags::$Flag)
}
)
},
unnamed: {
$crate::__bitflags_expr_safe_attrs!(
$(#[$inner $($args)*])*
{
$crate::Flag::new("", $PublicBitFlags::from_bits_retain($value))
}
)
},
}),
)*
]
};
type Bits = $T;
fn bits(&self) -> $T {
$PublicBitFlags::bits(self)
}
fn from_bits_retain(bits: $T) -> $PublicBitFlags {
$PublicBitFlags::from_bits_retain(bits)
}
fn all_named() -> $PublicBitFlags {
const ALL_NAMED: $T = {
let mut truncated = <$T as $crate::Bits>::EMPTY;
let mut i = 0;
$(
$crate::__bitflags_expr_safe_attrs!(
$(#[$inner $($args)*])*
{{
let flag = &<$PublicBitFlags as $crate::Flags>::FLAGS[i];
if flag.is_named() {
truncated = truncated | flag.value().bits();
}
i += 1;
}}
);
)*
let _ = i;
truncated
};
$PublicBitFlags::from_bits_retain(ALL_NAMED)
}
}
};
}
+161
View File
@@ -0,0 +1,161 @@
mod all;
mod all_named;
mod bitflags_match;
mod bits;
mod clear;
mod complement;
mod contains;
mod difference;
mod empty;
mod eq;
mod extend;
mod flag_name;
mod flags;
mod fmt;
mod from_bits;
mod from_bits_retain;
mod from_bits_truncate;
mod from_name;
mod insert;
mod intersection;
mod intersects;
mod is_all;
mod is_empty;
mod iter;
mod iter_equal_names;
mod known_bits;
mod parser;
mod remove;
mod symmetric_difference;
mod truncate;
mod union;
mod unknown;
mod unknown_bits;
mod custom {
pub const NAME: &'static str = "custom";
}
bitflags! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestFlags: u8 {
/// 1
const A = 1;
/// 1 << 1
const B = 1 << 1;
/// 1 << 2
const C = 1 << 2;
/// 1 | (1 << 1) | (1 << 2)
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestFlagsInvert: u8 {
/// 1 | (1 << 1) | (1 << 2)
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
/// 1
const A = 1;
/// 1 << 1
const B = 1 << 1;
/// 1 << 2
const C = 1 << 2;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestZero: u8 {
/// 0
const ZERO = 0;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestZeroOne: u8 {
/// 0
const ZERO = 0;
/// 1
const ONE = 1;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestUnicode: u8 {
/// 1
const 一 = 1;
/// 2
const 二 = 1 << 1;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestEmpty: u8 {}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestOverlapping: u8 {
/// 1 | (1 << 1)
const AB = 1 | (1 << 1);
/// (1 << 1) | (1 << 2)
const BC = (1 << 1) | (1 << 2);
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestOverlappingFull: u8 {
/// 1
const A = 1;
/// 1
const B = 1;
/// 1
const C = 1;
/// 2
const D = 1 << 1;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestExternal: u8 {
/// 1
const A = 1;
/// 1 << 1
const B = 1 << 1;
/// 1 << 2
const C = 1 << 2;
/// 1 | (1 << 1) | (1 << 2)
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
/// External
const _ = !0;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestExternalFull: u8 {
/// External
const _ = !0;
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct TestRenamed: u8 {
/// 1
#[bitflags(flag_name = "a")]
#[bitflags(flag_name = custom::NAME)]
const A = 1;
/// 1 << 1
#[bitflags(flag_name = "custom")]
const B = 1 << 1;
/// 1 << 2
#[bitflags(flag_name = "c")]
const C = 1 << 2;
/// 1 << 3
#[bitflags(flag_name = "custom | e")]
const D = 1 << 3;
}
}
+23
View File
@@ -0,0 +1,23 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(1 | 1 << 1 | 1 << 2, TestFlags::all);
case(0, TestZero::all);
case(0, TestEmpty::all);
case(!0, TestExternal::all);
}
#[track_caller]
fn case<T: Flags>(expected: T::Bits, inherent: impl FnOnce() -> T)
where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent().bits(), "T::all()");
assert_eq!(expected, T::all().bits(), "Flags::all()");
}
+21
View File
@@ -0,0 +1,21 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(1 | 1 << 1 | 1 << 2, TestFlags::all_named);
case(1 | 1 << 1 | 1 << 2, TestExternal::all_named);
case(0, TestExternalFull::all_named);
}
#[track_caller]
fn case<T: Flags>(expected: T::Bits, inherent: impl FnOnce() -> T)
where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent().bits(), "T::all_named()");
assert_eq!(expected, T::all_named().bits(), "Flags::all_named()");
}
+93
View File
@@ -0,0 +1,93 @@
bitflags! {
#[derive(PartialEq)]
struct Flags: u8 {
const A = 1 << 0;
const B = 1 << 1;
const C = 1 << 2;
const D = 1 << 3;
}
}
fn flag_to_string(flag: Flags) -> String {
bitflags_match!(flag, {
Flags::A => "A".to_string(),
Flags::B => { "B".to_string() }
Flags::C => "C".to_string(),
Flags::D => "D".to_string(),
Flags::A | Flags::B => "A or B".to_string(),
Flags::A & Flags::B => { "A and B | empty".to_string() },
Flags::A ^ Flags::B => "A xor B".to_string(),
Flags::A | Flags::B | Flags::C => "A or B or C".to_string(),
Flags::A & Flags::B & Flags::C => "A and B and C".to_string(),
Flags::A ^ Flags::B ^ Flags::C => "A xor B xor C".to_string(),
Flags::A | Flags::B | Flags::C | Flags::D => "All flags".to_string(),
_ => "Unknown combination".to_string()
})
}
#[test]
fn test_single_flags() {
assert_eq!(flag_to_string(Flags::A), "A");
assert_eq!(flag_to_string(Flags::B), "B");
assert_eq!(flag_to_string(Flags::C), "C");
assert_eq!(flag_to_string(Flags::D), "D");
}
#[test]
fn test_or_operations() {
assert_eq!(flag_to_string(Flags::A | Flags::B), "A or B");
assert_eq!(
flag_to_string(Flags::A | Flags::B | Flags::C),
"A or B or C"
);
assert_eq!(
flag_to_string(Flags::A | Flags::B | Flags::C | Flags::D),
"All flags"
);
}
#[test]
fn test_and_operations() {
assert_eq!(flag_to_string(Flags::A & Flags::A), "A");
assert_eq!(flag_to_string(Flags::A & Flags::B), "A and B | empty");
assert_eq!(
flag_to_string(Flags::A & Flags::B & Flags::C),
"A and B | empty"
); // Since A, B, and C are mutually exclusive, the result of A & B & C is 0 ==> A & B & C = 0000 (i.e., empty).
// However, in the bitflags_match! statement (actually is if {..} else if {..} .. else {..}),
// the "A & B = 0000" condition is listed first, so 0000 will match "A & B" first,
// resulting in the output of the "A and B | empty" branch.
assert_eq!(
flag_to_string(Flags::A & Flags::B & Flags::C & Flags::D),
"A and B | empty"
);
}
#[test]
fn test_xor_operations() {
assert_eq!(flag_to_string(Flags::A ^ Flags::B), "A or B"); // A | B = A ^ B == 0011
assert_eq!(flag_to_string(Flags::A ^ Flags::A), "A and B | empty");
assert_eq!(
flag_to_string(Flags::A ^ Flags::B ^ Flags::C),
"A or B or C"
);
}
#[test]
fn test_complex_operations() {
assert_eq!(flag_to_string(Flags::A | (Flags::B & Flags::C)), "A");
assert_eq!(
flag_to_string((Flags::A | Flags::B) & (Flags::B | Flags::C)),
"B"
);
assert_eq!(
flag_to_string(Flags::A ^ (Flags::B | Flags::C)),
"A or B or C"
);
}
#[test]
fn test_empty_and_full_flags() {
assert_eq!(flag_to_string(Flags::empty()), "A and B | empty");
assert_eq!(flag_to_string(Flags::all()), "All flags");
}
+36
View File
@@ -0,0 +1,36 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, TestFlags::empty(), TestFlags::bits);
case(1, TestFlags::A, TestFlags::bits);
case(1 | 1 << 1 | 1 << 2, TestFlags::ABC, TestFlags::bits);
case(!0, TestFlags::from_bits_retain(u8::MAX), TestFlags::bits);
case(1 << 3, TestFlags::from_bits_retain(1 << 3), TestFlags::bits);
case(1 << 3, TestZero::from_bits_retain(1 << 3), TestZero::bits);
case(1 << 3, TestEmpty::from_bits_retain(1 << 3), TestEmpty::bits);
case(
1 << 4 | 1 << 6,
TestExternal::from_bits_retain(1 << 4 | 1 << 6),
TestExternal::bits,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(
expected: T::Bits,
value: T,
inherent: impl FnOnce(&T) -> T::Bits,
) where
T::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent(&value), "{:?}.bits()", value);
assert_eq!(expected, Flags::bits(&value), "Flags::bits({:?})", value);
}
+27
View File
@@ -0,0 +1,27 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(TestFlags::from_bits_retain(0));
case(TestFlags::from_bits_retain(1 << 3));
case(TestFlags::ABC | TestFlags::from_bits_retain(1 << 3));
case(TestZero::empty());
case(TestZero::all());
case(TestFlags::from_bits_retain(1 << 3) | TestFlags::all());
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(mut flags: T)
where
T: std::fmt::Debug + PartialEq + Copy,
{
flags.clear();
assert_eq!(flags, T::empty(), "{:?}.clear()", flags);
}
+53
View File
@@ -0,0 +1,53 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, TestFlags::all(), TestFlags::complement);
case(0, TestFlags::from_bits_retain(!0), TestFlags::complement);
case(1 | 1 << 1, TestFlags::C, TestFlags::complement);
case(
1 | 1 << 1,
TestFlags::C | TestFlags::from_bits_retain(1 << 3),
TestFlags::complement,
);
case(
1 | 1 << 1 | 1 << 2,
TestFlags::empty(),
TestFlags::complement,
);
case(
1 | 1 << 1 | 1 << 2,
TestFlags::from_bits_retain(1 << 3),
TestFlags::complement,
);
case(0, TestZero::empty(), TestZero::complement);
case(0, TestEmpty::empty(), TestEmpty::complement);
case(1 << 2, TestOverlapping::AB, TestOverlapping::complement);
case(!0, TestExternal::empty(), TestExternal::complement);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + std::ops::Not<Output = T> + Copy>(
expected: T::Bits,
value: T,
inherent: impl FnOnce(T) -> T,
) where
T::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent(value).bits(), "{:?}.complement()", value);
assert_eq!(
expected,
Flags::complement(value).bits(),
"Flags::complement({:?})",
value
);
assert_eq!(expected, (!value).bits(), "!{:?}", value);
}
+108
View File
@@ -0,0 +1,108 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[
(TestFlags::empty(), true),
(TestFlags::A, false),
(TestFlags::B, false),
(TestFlags::C, false),
(TestFlags::from_bits_retain(1 << 3), false),
],
TestFlags::contains,
);
case(
TestFlags::A,
&[
(TestFlags::empty(), true),
(TestFlags::A, true),
(TestFlags::B, false),
(TestFlags::C, false),
(TestFlags::ABC, false),
(TestFlags::from_bits_retain(1 << 3), false),
(TestFlags::from_bits_retain(1 | (1 << 3)), false),
],
TestFlags::contains,
);
case(
TestFlags::ABC,
&[
(TestFlags::empty(), true),
(TestFlags::A, true),
(TestFlags::B, true),
(TestFlags::C, true),
(TestFlags::ABC, true),
(TestFlags::from_bits_retain(1 << 3), false),
],
TestFlags::contains,
);
case(
TestFlags::from_bits_retain(1 << 3),
&[
(TestFlags::empty(), true),
(TestFlags::A, false),
(TestFlags::B, false),
(TestFlags::C, false),
(TestFlags::from_bits_retain(1 << 3), true),
],
TestFlags::contains,
);
case(
TestZero::ZERO,
&[(TestZero::ZERO, true)],
TestZero::contains,
);
case(
TestOverlapping::AB,
&[
(TestOverlapping::AB, true),
(TestOverlapping::BC, false),
(TestOverlapping::from_bits_retain(1 << 1), true),
],
TestOverlapping::contains,
);
case(
TestExternal::all(),
&[
(TestExternal::A, true),
(TestExternal::B, true),
(TestExternal::C, true),
(TestExternal::from_bits_retain(1 << 5 | 1 << 7), true),
],
TestExternal::contains,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + Copy>(
value: T,
inputs: &[(T, bool)],
mut inherent: impl FnMut(&T, T) -> bool,
) {
for (input, expected) in inputs {
assert_eq!(
*expected,
inherent(&value, *input),
"{:?}.contains({:?})",
value,
input
);
assert_eq!(
*expected,
Flags::contains(&value, *input),
"Flags::contains({:?}, {:?})",
value,
input
);
}
}
+92
View File
@@ -0,0 +1,92 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::A | TestFlags::B,
&[
(TestFlags::A, 1 << 1),
(TestFlags::B, 1),
(TestFlags::from_bits_retain(1 << 3), 1 | 1 << 1),
],
TestFlags::difference,
);
case(
TestFlags::from_bits_retain(1 | 1 << 3),
&[
(TestFlags::A, 1 << 3),
(TestFlags::from_bits_retain(1 << 3), 1),
],
TestFlags::difference,
);
case(
TestExternal::from_bits_retain(!0),
&[(TestExternal::A, 0b1111_1110)],
TestExternal::difference,
);
assert_eq!(
0b1111_1110,
(TestExternal::from_bits_retain(!0) & !TestExternal::A).bits()
);
assert_eq!(
0b1111_1110,
(TestFlags::from_bits_retain(!0).difference(TestFlags::A)).bits()
);
// The `!` operator unsets bits that don't correspond to known flags
assert_eq!(
1 << 1 | 1 << 2,
(TestFlags::from_bits_retain(!0) & !TestFlags::A).bits()
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + std::ops::Sub<Output = T> + std::ops::SubAssign + Copy>(
value: T,
inputs: &[(T, T::Bits)],
mut inherent: impl FnMut(T, T) -> T,
) where
T::Bits: std::fmt::Debug + PartialEq + Copy,
{
for (input, expected) in inputs {
assert_eq!(
*expected,
inherent(value, *input).bits(),
"{:?}.difference({:?})",
value,
input
);
assert_eq!(
*expected,
Flags::difference(value, *input).bits(),
"Flags::difference({:?}, {:?})",
value,
input
);
assert_eq!(
*expected,
(value - *input).bits(),
"{:?} - {:?}",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
value -= *input;
value
}
.bits(),
"{:?} -= {:?}",
value,
input,
);
}
}
+23
View File
@@ -0,0 +1,23 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, TestFlags::empty);
case(0, TestZero::empty);
case(0, TestEmpty::empty);
case(0, TestExternal::empty);
}
#[track_caller]
fn case<T: Flags>(expected: T::Bits, inherent: impl FnOnce() -> T)
where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent().bits(), "T::empty()");
assert_eq!(expected, T::empty().bits(), "Flags::empty()");
}
+10
View File
@@ -0,0 +1,10 @@
use super::*;
#[test]
fn cases() {
assert_eq!(TestFlags::empty(), TestFlags::empty());
assert_eq!(TestFlags::all(), TestFlags::all());
assert!(TestFlags::from_bits_retain(1) < TestFlags::from_bits_retain(2));
assert!(TestFlags::from_bits_retain(2) > TestFlags::from_bits_retain(1));
}
+42
View File
@@ -0,0 +1,42 @@
use super::*;
#[test]
fn cases() {
let mut flags = TestFlags::empty();
flags.extend(TestFlags::A);
assert_eq!(TestFlags::A, flags);
flags.extend(TestFlags::A | TestFlags::B | TestFlags::C);
assert_eq!(TestFlags::ABC, flags);
flags.extend(TestFlags::from_bits_retain(1 << 5));
assert_eq!(TestFlags::ABC | TestFlags::from_bits_retain(1 << 5), flags);
}
mod external {
use super::*;
#[test]
fn cases() {
let mut flags = TestExternal::empty();
flags.extend(TestExternal::A);
assert_eq!(TestExternal::A, flags);
flags.extend(TestExternal::A | TestExternal::B | TestExternal::C);
assert_eq!(TestExternal::ABC, flags);
flags.extend(TestExternal::from_bits_retain(1 << 5));
assert_eq!(
TestExternal::ABC | TestExternal::from_bits_retain(1 << 5),
flags
);
}
}
+40
View File
@@ -0,0 +1,40 @@
use super::*;
use crate::{parser::*, Flags};
#[test]
fn cases() {
let flags = TestRenamed::FLAGS
.iter()
.map(|flag| (flag.name(), flag.value().bits()))
.collect::<Vec<_>>();
assert_eq!(
vec![
("custom", 1),
("custom", 1 << 1),
("c", 1 << 2),
("custom | e", 1 << 3),
],
flags,
);
// Original names are not recognized
assert!(TestRenamed::from_name("A").is_none());
// Regular renames are recognized
assert_eq!(TestRenamed::C, TestRenamed::from_name("c").unwrap());
// The first duplicate name is recognized
assert_eq!(TestRenamed::A, TestRenamed::from_name("custom").unwrap());
// Exotic names are recognized
assert_eq!(
TestRenamed::D,
TestRenamed::from_name("custom | e").unwrap()
);
// The parser doesn't have defined behavior on exotic names, but we
// make sure it does _something_
assert!(from_str_truncate::<TestRenamed>("custom | e").is_err());
}
+46
View File
@@ -0,0 +1,46 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
let flags = TestFlags::FLAGS
.iter()
.map(|flag| (flag.name(), flag.value().bits()))
.collect::<Vec<_>>();
assert_eq!(
vec![
("A", 1u8),
("B", 1 << 1),
("C", 1 << 2),
("ABC", 1 | 1 << 1 | 1 << 2),
],
flags,
);
assert_eq!(0, TestEmpty::FLAGS.iter().count());
}
mod external {
use super::*;
#[test]
fn cases() {
let flags = TestExternal::FLAGS
.iter()
.map(|flag| (flag.name(), flag.value().bits()))
.collect::<Vec<_>>();
assert_eq!(
vec![
("A", 1u8),
("B", 1 << 1),
("C", 1 << 2),
("ABC", 1 | 1 << 1 | 1 << 2),
("", !0),
],
flags,
);
}
}
+97
View File
@@ -0,0 +1,97 @@
use super::*;
#[test]
fn cases() {
case(TestFlags::empty(), "TestFlags(0x0)", "0", "0", "0", "0");
case(TestFlags::A, "TestFlags(A)", "1", "1", "1", "1");
case(
TestFlags::all(),
"TestFlags(A | B | C)",
"7",
"7",
"7",
"111",
);
case(
TestFlags::from_bits_retain(1 << 3),
"TestFlags(0x8)",
"8",
"8",
"10",
"1000",
);
case(
TestFlags::A | TestFlags::from_bits_retain(1 << 3),
"TestFlags(A | 0x8)",
"9",
"9",
"11",
"1001",
);
case(TestZero::ZERO, "TestZero(0x0)", "0", "0", "0", "0");
case(
TestZero::ZERO | TestZero::from_bits_retain(1),
"TestZero(0x1)",
"1",
"1",
"1",
"1",
);
case(TestZeroOne::ONE, "TestZeroOne(ONE)", "1", "1", "1", "1");
case(
TestOverlapping::from_bits_retain(1 << 1),
"TestOverlapping(0x2)",
"2",
"2",
"2",
"10",
);
case(
TestExternal::from_bits_retain(1 | 1 << 1 | 1 << 3),
"TestExternal(A | B | 0x8)",
"B",
"b",
"13",
"1011",
);
case(
TestExternal::all(),
"TestExternal(A | B | C | 0xf8)",
"FF",
"ff",
"377",
"11111111",
);
case(
TestExternalFull::all(),
"TestExternalFull(0xff)",
"FF",
"ff",
"377",
"11111111",
);
}
#[track_caller]
fn case<
T: std::fmt::Debug + std::fmt::UpperHex + std::fmt::LowerHex + std::fmt::Octal + std::fmt::Binary,
>(
value: T,
debug: &str,
uhex: &str,
lhex: &str,
oct: &str,
bin: &str,
) {
assert_eq!(debug, format!("{:?}", value));
assert_eq!(uhex, format!("{:X}", value));
assert_eq!(lhex, format!("{:x}", value));
assert_eq!(oct, format!("{:o}", value));
assert_eq!(bin, format!("{:b}", value));
}
+45
View File
@@ -0,0 +1,45 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(Some(0), 0, TestFlags::from_bits);
case(Some(1), 1, TestFlags::from_bits);
case(
Some(1 | 1 << 1 | 1 << 2),
1 | 1 << 1 | 1 << 2,
TestFlags::from_bits,
);
case(None, 1 << 3, TestFlags::from_bits);
case(None, 1 | 1 << 3, TestFlags::from_bits);
case(Some(1 | 1 << 1), 1 | 1 << 1, TestOverlapping::from_bits);
case(Some(1 << 1), 1 << 1, TestOverlapping::from_bits);
case(Some(1 << 5), 1 << 5, TestExternal::from_bits);
}
#[track_caller]
fn case<T: Flags>(
expected: Option<T::Bits>,
input: T::Bits,
inherent: impl FnOnce(T::Bits) -> Option<T>,
) where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(
expected,
inherent(input).map(|f| f.bits()),
"T::from_bits({:?})",
input
);
assert_eq!(
expected,
T::from_bits(input).map(|f| f.bits()),
"Flags::from_bits({:?})",
input
);
}
+38
View File
@@ -0,0 +1,38 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, TestFlags::from_bits_retain);
case(1, TestFlags::from_bits_retain);
case(1 | 1 << 1 | 1 << 2, TestFlags::from_bits_retain);
case(1 << 3, TestFlags::from_bits_retain);
case(1 | 1 << 3, TestFlags::from_bits_retain);
case(1 | 1 << 1, TestOverlapping::from_bits_retain);
case(1 << 1, TestOverlapping::from_bits_retain);
case(1 << 5, TestExternal::from_bits_retain);
}
#[track_caller]
fn case<T: Flags>(input: T::Bits, inherent: impl FnOnce(T::Bits) -> T)
where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(
input,
inherent(input).bits(),
"T::from_bits_retain({:?})",
input
);
assert_eq!(
input,
T::from_bits_retain(input).bits(),
"Flags::from_bits_retain({:?})",
input
);
}
+42
View File
@@ -0,0 +1,42 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, 0, TestFlags::from_bits_truncate);
case(1, 1, TestFlags::from_bits_truncate);
case(
1 | 1 << 1 | 1 << 2,
1 | 1 << 1 | 1 << 2,
TestFlags::from_bits_truncate,
);
case(0, 1 << 3, TestFlags::from_bits_truncate);
case(1, 1 | 1 << 3, TestFlags::from_bits_truncate);
case(1 | 1 << 1, 1 | 1 << 1, TestOverlapping::from_bits_truncate);
case(1 << 1, 1 << 1, TestOverlapping::from_bits_truncate);
case(1 << 5, 1 << 5, TestExternal::from_bits_truncate);
}
#[track_caller]
fn case<T: Flags>(expected: T::Bits, input: T::Bits, inherent: impl FnOnce(T::Bits) -> T)
where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(
expected,
inherent(input).bits(),
"T::from_bits_truncate({:?})",
input
);
assert_eq!(
expected,
T::from_bits_truncate(input).bits(),
"Flags::from_bits_truncate({:?})",
input
);
}
+42
View File
@@ -0,0 +1,42 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(Some(1), "A", TestFlags::from_name);
case(Some(1 << 1), "B", TestFlags::from_name);
case(Some(1 | 1 << 1 | 1 << 2), "ABC", TestFlags::from_name);
case(None, "", TestFlags::from_name);
case(None, "a", TestFlags::from_name);
case(None, "0x1", TestFlags::from_name);
case(None, "A | B", TestFlags::from_name);
case(Some(0), "ZERO", TestZero::from_name);
case(Some(2), "二", TestUnicode::from_name);
case(None, "_", TestExternal::from_name);
case(None, "", TestExternal::from_name);
}
#[track_caller]
fn case<T: Flags>(expected: Option<T::Bits>, input: &str, inherent: impl FnOnce(&str) -> Option<T>)
where
<T as Flags>::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(
expected,
inherent(input).map(|f| f.bits()),
"T::from_name({:?})",
input
);
assert_eq!(
expected,
T::from_name(input).map(|f| f.bits()),
"Flags::from_name({:?})",
input
);
}
+91
View File
@@ -0,0 +1,91 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[
(TestFlags::A, 1),
(TestFlags::A | TestFlags::B, 1 | 1 << 1),
(TestFlags::empty(), 0),
(TestFlags::from_bits_retain(1 << 3), 1 << 3),
],
TestFlags::insert,
TestFlags::set,
);
case(
TestFlags::A,
&[
(TestFlags::A, 1),
(TestFlags::empty(), 1),
(TestFlags::B, 1 | 1 << 1),
],
TestFlags::insert,
TestFlags::set,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + Copy>(
value: T,
inputs: &[(T, T::Bits)],
mut inherent_insert: impl FnMut(&mut T, T),
mut inherent_set: impl FnMut(&mut T, T, bool),
) where
T::Bits: std::fmt::Debug + PartialEq + Copy,
{
for (input, expected) in inputs {
assert_eq!(
*expected,
{
let mut value = value;
inherent_insert(&mut value, *input);
value
}
.bits(),
"{:?}.insert({:?})",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
Flags::insert(&mut value, *input);
value
}
.bits(),
"Flags::insert({:?}, {:?})",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
inherent_set(&mut value, *input, true);
value
}
.bits(),
"{:?}.set({:?}, true)",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
Flags::set(&mut value, *input, true);
value
}
.bits(),
"Flags::set({:?}, {:?}, true)",
value,
input
);
}
}
+79
View File
@@ -0,0 +1,79 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[(TestFlags::empty(), 0), (TestFlags::all(), 0)],
TestFlags::intersection,
);
case(
TestFlags::all(),
&[
(TestFlags::all(), 1 | 1 << 1 | 1 << 2),
(TestFlags::A, 1),
(TestFlags::from_bits_retain(1 << 3), 0),
],
TestFlags::intersection,
);
case(
TestFlags::from_bits_retain(1 << 3),
&[(TestFlags::from_bits_retain(1 << 3), 1 << 3)],
TestFlags::intersection,
);
case(
TestOverlapping::AB,
&[(TestOverlapping::BC, 1 << 1)],
TestOverlapping::intersection,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + std::ops::BitAnd<Output = T> + std::ops::BitAndAssign + Copy>(
value: T,
inputs: &[(T, T::Bits)],
mut inherent: impl FnMut(T, T) -> T,
) where
T::Bits: std::fmt::Debug + PartialEq + Copy,
{
for (input, expected) in inputs {
assert_eq!(
*expected,
inherent(value, *input).bits(),
"{:?}.intersection({:?})",
value,
input
);
assert_eq!(
*expected,
Flags::intersection(value, *input).bits(),
"Flags::intersection({:?}, {:?})",
value,
input
);
assert_eq!(
*expected,
(value & *input).bits(),
"{:?} & {:?}",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
value &= *input;
value
}
.bits(),
"{:?} &= {:?}",
value,
input,
);
}
}
+91
View File
@@ -0,0 +1,91 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[
(TestFlags::empty(), false),
(TestFlags::A, false),
(TestFlags::B, false),
(TestFlags::C, false),
(TestFlags::from_bits_retain(1 << 3), false),
],
TestFlags::intersects,
);
case(
TestFlags::A,
&[
(TestFlags::empty(), false),
(TestFlags::A, true),
(TestFlags::B, false),
(TestFlags::C, false),
(TestFlags::ABC, true),
(TestFlags::from_bits_retain(1 << 3), false),
(TestFlags::from_bits_retain(1 | (1 << 3)), true),
],
TestFlags::intersects,
);
case(
TestFlags::ABC,
&[
(TestFlags::empty(), false),
(TestFlags::A, true),
(TestFlags::B, true),
(TestFlags::C, true),
(TestFlags::ABC, true),
(TestFlags::from_bits_retain(1 << 3), false),
],
TestFlags::intersects,
);
case(
TestFlags::from_bits_retain(1 << 3),
&[
(TestFlags::empty(), false),
(TestFlags::A, false),
(TestFlags::B, false),
(TestFlags::C, false),
(TestFlags::from_bits_retain(1 << 3), true),
],
TestFlags::intersects,
);
case(
TestOverlapping::AB,
&[
(TestOverlapping::AB, true),
(TestOverlapping::BC, true),
(TestOverlapping::from_bits_retain(1 << 1), true),
],
TestOverlapping::intersects,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + Copy>(
value: T,
inputs: &[(T, bool)],
mut inherent: impl FnMut(&T, T) -> bool,
) {
for (input, expected) in inputs {
assert_eq!(
*expected,
inherent(&value, *input),
"{:?}.intersects({:?})",
value,
input
);
assert_eq!(
*expected,
Flags::intersects(&value, *input),
"Flags::intersects({:?}, {:?})",
value,
input
);
}
}
+32
View File
@@ -0,0 +1,32 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(false, TestFlags::empty(), TestFlags::is_all);
case(false, TestFlags::A, TestFlags::is_all);
case(true, TestFlags::ABC, TestFlags::is_all);
case(
true,
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::is_all,
);
case(true, TestZero::empty(), TestZero::is_all);
case(true, TestEmpty::empty(), TestEmpty::is_all);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(expected: bool, value: T, inherent: impl FnOnce(&T) -> bool) {
assert_eq!(expected, inherent(&value), "{:?}.is_all()", value);
assert_eq!(
expected,
Flags::is_all(&value),
"Flags::is_all({:?})",
value
);
}
+31
View File
@@ -0,0 +1,31 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(true, TestFlags::empty(), TestFlags::is_empty);
case(false, TestFlags::A, TestFlags::is_empty);
case(false, TestFlags::ABC, TestFlags::is_empty);
case(
false,
TestFlags::from_bits_retain(1 << 3),
TestFlags::is_empty,
);
case(true, TestZero::empty(), TestZero::is_empty);
case(true, TestEmpty::empty(), TestEmpty::is_empty);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(expected: bool, value: T, inherent: impl FnOnce(&T) -> bool) {
assert_eq!(expected, inherent(&value), "{:?}.is_empty()", value);
assert_eq!(
expected,
Flags::is_empty(&value),
"Flags::is_empty({:?})",
value
);
}
+299
View File
@@ -0,0 +1,299 @@
use super::*;
use crate::Flags;
#[test]
#[cfg(not(miri))] // Very slow in miri
fn roundtrip() {
for a in 0u8..=255 {
for b in 0u8..=255 {
let f = TestFlags::from_bits_retain(a | b);
assert_eq!(f, f.iter().collect::<TestFlags>());
assert_eq!(
TestFlags::from_bits_truncate(f.bits()),
f.iter_names().map(|(_, f)| f).collect::<TestFlags>()
);
let f = TestExternal::from_bits_retain(a | b);
assert_eq!(f, f.iter().collect::<TestExternal>());
}
}
}
mod collect {
use super::*;
#[test]
fn cases() {
assert_eq!(0, [].into_iter().collect::<TestFlags>().bits());
assert_eq!(1, [TestFlags::A,].into_iter().collect::<TestFlags>().bits());
assert_eq!(
1 | 1 << 1 | 1 << 2,
[TestFlags::A, TestFlags::B | TestFlags::C,]
.into_iter()
.collect::<TestFlags>()
.bits()
);
assert_eq!(
1 | 1 << 3,
[
TestFlags::from_bits_retain(1 << 3),
TestFlags::empty(),
TestFlags::A,
]
.into_iter()
.collect::<TestFlags>()
.bits()
);
assert_eq!(
1 << 5 | 1 << 7,
[
TestExternal::empty(),
TestExternal::from_bits_retain(1 << 5),
TestExternal::from_bits_retain(1 << 7),
]
.into_iter()
.collect::<TestExternal>()
.bits()
);
}
}
mod iter {
use super::*;
#[test]
fn cases() {
case(&[], TestFlags::empty(), TestFlags::iter);
case(&[1], TestFlags::A, TestFlags::iter);
case(&[1, 1 << 1], TestFlags::A | TestFlags::B, TestFlags::iter);
case(
&[1, 1 << 1, 1 << 3],
TestFlags::A | TestFlags::B | TestFlags::from_bits_retain(1 << 3),
TestFlags::iter,
);
case(&[1, 1 << 1, 1 << 2], TestFlags::ABC, TestFlags::iter);
case(
&[1, 1 << 1, 1 << 2, 1 << 3],
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::iter,
);
case(
&[1 | 1 << 1 | 1 << 2],
TestFlagsInvert::ABC,
TestFlagsInvert::iter,
);
case(&[], TestZero::ZERO, TestZero::iter);
case(
&[1, 1 << 1, 1 << 2, 0b1111_1000],
TestExternal::all(),
TestExternal::iter,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + IntoIterator<Item = T> + Copy>(
expected: &[T::Bits],
value: T,
inherent: impl FnOnce(&T) -> crate::iter::Iter<T>,
) where
T::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(
expected,
inherent(&value).map(|f| f.bits()).collect::<Vec<_>>(),
"{:?}.iter()",
value
);
assert_eq!(
expected,
Flags::iter(&value).map(|f| f.bits()).collect::<Vec<_>>(),
"Flags::iter({:?})",
value
);
assert_eq!(
expected,
value.into_iter().map(|f| f.bits()).collect::<Vec<_>>(),
"{:?}.into_iter()",
value
);
}
}
mod iter_names {
use super::*;
#[test]
fn cases() {
case(&[], TestFlags::empty(), TestFlags::iter_names);
case(&[("A", 1)], TestFlags::A, TestFlags::iter_names);
case(
&[("A", 1), ("B", 1 << 1)],
TestFlags::A | TestFlags::B,
TestFlags::iter_names,
);
case(
&[("A", 1), ("B", 1 << 1)],
TestFlags::A | TestFlags::B | TestFlags::from_bits_retain(1 << 3),
TestFlags::iter_names,
);
case(
&[("A", 1), ("B", 1 << 1), ("C", 1 << 2)],
TestFlags::ABC,
TestFlags::iter_names,
);
case(
&[("A", 1), ("B", 1 << 1), ("C", 1 << 2)],
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::iter_names,
);
case(
&[("ABC", 1 | 1 << 1 | 1 << 2)],
TestFlagsInvert::ABC,
TestFlagsInvert::iter_names,
);
case(&[], TestZero::ZERO, TestZero::iter_names);
case(
&[("A", 1)],
TestOverlappingFull::A,
TestOverlappingFull::iter_names,
);
case(
&[("A", 1), ("D", 1 << 1)],
TestOverlappingFull::A | TestOverlappingFull::D,
TestOverlappingFull::iter_names,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(
expected: &[(&'static str, T::Bits)],
value: T,
inherent: impl FnOnce(&T) -> crate::iter::IterNames<T>,
) where
T::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(
expected,
inherent(&value)
.map(|(n, f)| (n, f.bits()))
.collect::<Vec<_>>(),
"{:?}.iter_names()",
value
);
assert_eq!(
expected,
Flags::iter_names(&value)
.map(|(n, f)| (n, f.bits()))
.collect::<Vec<_>>(),
"Flags::iter_names({:?})",
value
);
}
}
mod iter_defined_names {
use crate::Flags;
#[test]
fn test_defined_names() {
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct TestFlags: u32 {
const A = 0b00000001;
const ZERO = 0;
const B = 0b00000010;
const C = 0b00000100;
const CC = Self::C.bits();
const D = 0b10000100;
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
const AB = Self::A.bits() | Self::B.bits();
const AC = Self::A.bits() | Self::C.bits();
const CB = Self::B.bits() | Self::C.bits();
}
}
// Test all named flags produced by the iterator
let all_named: Vec<(&'static str, TestFlags)> = TestFlags::iter_defined_names().collect();
// Verify all named flags are included
let expected_flags = vec![
("A", TestFlags::A),
("ZERO", TestFlags::ZERO),
("B", TestFlags::B),
("C", TestFlags::C),
// Note: CC and C have the same bit value, but both are named flags
("CC", TestFlags::CC),
("D", TestFlags::D),
("ABC", TestFlags::ABC),
("AB", TestFlags::AB),
("AC", TestFlags::AC),
("CB", TestFlags::CB),
];
assert_eq!(
all_named.len(),
expected_flags.len(),
"Should have 10 named flags"
);
// Verify each expected flag is in the result
for expected_flag in &expected_flags {
assert!(
all_named.contains(expected_flag),
"Missing flag: {:?}",
expected_flag
);
}
// Test if iterator order is consistent with definition order
let flags_in_order: Vec<(&'static str, TestFlags)> =
TestFlags::iter_defined_names().collect();
assert_eq!(
flags_in_order, expected_flags,
"Flag order should match definition order"
);
// Test that iterator can be used multiple times
let first_iteration: Vec<(&'static str, TestFlags)> =
TestFlags::iter_defined_names().collect();
let second_iteration: Vec<(&'static str, TestFlags)> =
TestFlags::iter_defined_names().collect();
assert_eq!(
first_iteration, second_iteration,
"Multiple iterations should produce the same result"
);
// Test consistency with FLAGS constant
let flags_from_iter: std::collections::HashSet<u32> = TestFlags::iter_defined_names()
.map(|(_, f)| f.bits())
.collect();
let flags_from_const: std::collections::HashSet<u32> = TestFlags::FLAGS
.iter()
.filter(|f| f.is_named())
.map(|f| f.value().bits())
.collect();
assert_eq!(
flags_from_iter, flags_from_const,
"iter_defined_names() should be consistent with named flags in FLAGS"
);
}
}
+73
View File
@@ -0,0 +1,73 @@
#[test]
fn test_iter_equal_names() {
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct TestFlags: u32 {
const A = 0b00000001;
const ZERO = 0;
const B = 0b00000010;
const C = 0b00000100;
const CC = Self::C.bits();
const D = 0b10000100;
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
const AB = Self::A.bits() | Self::B.bits();
const AC = Self::A.bits() | Self::C.bits();
const CB = Self::B.bits() | Self::C.bits();
}
}
use crate::Flags;
assert_eq!(
TestFlags::A.iter_equal_names().collect::<Vec<_>>(),
vec!["A"]
);
assert_eq!(
TestFlags::ZERO.iter_equal_names().collect::<Vec<_>>(),
vec!["ZERO"]
);
assert_eq!(
TestFlags::B.iter_equal_names().collect::<Vec<_>>(),
vec!["B"]
);
assert_eq!(
TestFlags::C.iter_equal_names().collect::<Vec<_>>(),
vec!["C", "CC"]
);
assert!(TestFlags::C
.iter_equal_names()
.any(|n| n == "CC" || n == "C"));
assert_eq!(
TestFlags::CC.iter_equal_names().collect::<Vec<_>>(),
vec!["C", "CC"]
);
assert!(TestFlags::CC
.iter_equal_names()
.any(|n| n == "CC" || n == "C"));
assert_eq!(
TestFlags::D.iter_equal_names().collect::<Vec<_>>(),
vec!["D"]
);
assert_eq!(
TestFlags::ABC.iter_equal_names().collect::<Vec<_>>(),
vec!["ABC"]
);
assert_eq!(
TestFlags::AB.iter_equal_names().collect::<Vec<_>>(),
vec!["AB"]
);
assert_eq!(
TestFlags::AC.iter_equal_names().collect::<Vec<_>>(),
vec!["AC"]
);
assert_eq!(
TestFlags::CB.iter_equal_names().collect::<Vec<_>>(),
vec!["CB"]
);
let xyz = TestFlags::from_bits_retain(123456);
assert!(xyz.iter_equal_names().collect::<Vec<_>>().is_empty());
}
+47
View File
@@ -0,0 +1,47 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, TestFlags::empty(), TestFlags::known_bits);
case(1, TestFlags::A, TestFlags::known_bits);
case(1 | 1 << 1 | 1 << 2, TestFlags::all(), TestFlags::known_bits);
case(
1 | 1 << 1 | 1 << 2,
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::known_bits,
);
case(
0,
TestFlags::from_bits_retain(1 << 3),
TestFlags::known_bits,
);
case(0, TestZero::empty(), TestZero::known_bits);
case(
0xFF,
TestExternal::from_bits_retain(0xFF),
TestExternal::known_bits,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(
expected: T::Bits,
value: T,
inherent: impl FnOnce(&T) -> T::Bits,
) where
T::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent(&value), "{:?}.known_bits()", value);
assert_eq!(
expected,
Flags::known_bits(&value),
"Flags::known_bits({:?})",
value,
);
}
+332
View File
@@ -0,0 +1,332 @@
use super::*;
use crate::{parser::*, Flags};
#[test]
#[cfg(not(miri))] // Very slow in miri
fn roundtrip() {
let mut s = String::new();
for a in 0u8..=255 {
for b in 0u8..=255 {
let f = TestFlags::from_bits_retain(a | b);
s.clear();
to_writer(&f, &mut s).unwrap();
assert_eq!(f, from_str::<TestFlags>(&s).unwrap());
}
}
}
#[test]
#[cfg(not(miri))] // Very slow in miri
fn roundtrip_truncate() {
let mut s = String::new();
for a in 0u8..=255 {
for b in 0u8..=255 {
let f = TestFlags::from_bits_retain(a | b);
s.clear();
to_writer_truncate(&f, &mut s).unwrap();
assert_eq!(
TestFlags::from_bits_truncate(f.bits()),
from_str_truncate::<TestFlags>(&s).unwrap()
);
}
}
}
#[test]
#[cfg(not(miri))] // Very slow in miri
fn roundtrip_strict() {
let mut s = String::new();
for a in 0u8..=255 {
for b in 0u8..=255 {
let f = TestFlags::from_bits_retain(a | b);
s.clear();
to_writer_strict(&f, &mut s).unwrap();
let mut strict = TestFlags::empty();
for (_, flag) in f.iter_names() {
strict |= flag;
}
let f = strict;
if let Ok(s) = from_str_strict::<TestFlags>(&s) {
assert_eq!(f, s);
}
}
}
}
mod from_str {
use super::*;
#[test]
fn valid() {
assert_eq!(0, from_str::<TestFlags>("").unwrap().bits());
assert_eq!(1, from_str::<TestFlags>("A").unwrap().bits());
assert_eq!(1, from_str::<TestFlags>(" A ").unwrap().bits());
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str::<TestFlags>("A | B | C").unwrap().bits()
);
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str::<TestFlags>("A\n|\tB\r\n| C ").unwrap().bits()
);
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str::<TestFlags>("A|B|C").unwrap().bits()
);
assert_eq!(1 << 3, from_str::<TestFlags>("0x8").unwrap().bits());
assert_eq!(1 | 1 << 3, from_str::<TestFlags>("A | 0x8").unwrap().bits());
assert_eq!(
1 | 1 << 1 | 1 << 3,
from_str::<TestFlags>("0x1 | 0x8 | B").unwrap().bits()
);
assert_eq!(
1 | 1 << 1,
from_str::<TestUnicode>("一 | 二").unwrap().bits()
);
}
#[test]
fn invalid() {
assert!(from_str::<TestFlags>("a")
.unwrap_err()
.to_string()
.starts_with("unrecognized named flag"));
assert!(from_str::<TestFlags>("A & B")
.unwrap_err()
.to_string()
.starts_with("unrecognized named flag"));
assert!(from_str::<TestFlags>("0xg")
.unwrap_err()
.to_string()
.starts_with("invalid hex flag"));
assert!(from_str::<TestFlags>("0xffffffffffff")
.unwrap_err()
.to_string()
.starts_with("invalid hex flag"));
}
}
mod to_writer {
use super::*;
#[test]
fn cases() {
assert_eq!("", write(TestFlags::empty()));
assert_eq!("A", write(TestFlags::A));
assert_eq!("A | B | C", write(TestFlags::all()));
assert_eq!("0x8", write(TestFlags::from_bits_retain(1 << 3)));
assert_eq!(
"A | 0x8",
write(TestFlags::A | TestFlags::from_bits_retain(1 << 3))
);
assert_eq!("", write(TestZero::ZERO));
assert_eq!("ABC", write(TestFlagsInvert::all()));
assert_eq!("0x1", write(TestOverlapping::from_bits_retain(1)));
assert_eq!("A", write(TestOverlappingFull::C));
assert_eq!(
"A | D",
write(TestOverlappingFull::C | TestOverlappingFull::D)
);
}
fn write<F: Flags>(value: F) -> String
where
F::Bits: crate::parser::WriteHex,
{
let mut s = String::new();
to_writer(&value, &mut s).unwrap();
s
}
}
mod from_str_truncate {
use super::*;
#[test]
fn valid() {
assert_eq!(0, from_str_truncate::<TestFlags>("").unwrap().bits());
assert_eq!(1, from_str_truncate::<TestFlags>("A").unwrap().bits());
assert_eq!(1, from_str_truncate::<TestFlags>(" A ").unwrap().bits());
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str_truncate::<TestFlags>("A | B | C").unwrap().bits()
);
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str_truncate::<TestFlags>("A\n|\tB\r\n| C ")
.unwrap()
.bits()
);
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str_truncate::<TestFlags>("A|B|C").unwrap().bits()
);
assert_eq!(0, from_str_truncate::<TestFlags>("0x8").unwrap().bits());
assert_eq!(1, from_str_truncate::<TestFlags>("A | 0x8").unwrap().bits());
assert_eq!(
1 | 1 << 1,
from_str_truncate::<TestFlags>("0x1 | 0x8 | B")
.unwrap()
.bits()
);
assert_eq!(
1 | 1 << 1,
from_str_truncate::<TestUnicode>("一 | 二").unwrap().bits()
);
}
}
mod to_writer_truncate {
use super::*;
#[test]
fn cases() {
assert_eq!("", write(TestFlags::empty()));
assert_eq!("A", write(TestFlags::A));
assert_eq!("A | B | C", write(TestFlags::all()));
assert_eq!("", write(TestFlags::from_bits_retain(1 << 3)));
assert_eq!(
"A",
write(TestFlags::A | TestFlags::from_bits_retain(1 << 3))
);
assert_eq!("", write(TestZero::ZERO));
assert_eq!("ABC", write(TestFlagsInvert::all()));
assert_eq!("0x1", write(TestOverlapping::from_bits_retain(1)));
assert_eq!("A", write(TestOverlappingFull::C));
assert_eq!(
"A | D",
write(TestOverlappingFull::C | TestOverlappingFull::D)
);
}
fn write<F: Flags>(value: F) -> String
where
F::Bits: crate::parser::WriteHex,
{
let mut s = String::new();
to_writer_truncate(&value, &mut s).unwrap();
s
}
}
mod from_str_strict {
use super::*;
#[test]
fn valid() {
assert_eq!(0, from_str_strict::<TestFlags>("").unwrap().bits());
assert_eq!(1, from_str_strict::<TestFlags>("A").unwrap().bits());
assert_eq!(1, from_str_strict::<TestFlags>(" A ").unwrap().bits());
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str_strict::<TestFlags>("A | B | C").unwrap().bits()
);
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str_strict::<TestFlags>("A\n|\tB\r\n| C ")
.unwrap()
.bits()
);
assert_eq!(
1 | 1 << 1 | 1 << 2,
from_str_strict::<TestFlags>("A|B|C").unwrap().bits()
);
assert_eq!(
1 | 1 << 1,
from_str_strict::<TestUnicode>("一 | 二").unwrap().bits()
);
}
#[test]
fn invalid() {
assert!(from_str_strict::<TestFlags>("a")
.unwrap_err()
.to_string()
.starts_with("unrecognized named flag"));
assert!(from_str_strict::<TestFlags>("A & B")
.unwrap_err()
.to_string()
.starts_with("unrecognized named flag"));
assert!(from_str_strict::<TestFlags>("0x1")
.unwrap_err()
.to_string()
.starts_with("invalid hex flag"));
assert!(from_str_strict::<TestFlags>("0xg")
.unwrap_err()
.to_string()
.starts_with("invalid hex flag"));
assert!(from_str_strict::<TestFlags>("0xffffffffffff")
.unwrap_err()
.to_string()
.starts_with("invalid hex flag"));
}
}
mod to_writer_strict {
use super::*;
#[test]
fn cases() {
assert_eq!("", write(TestFlags::empty()));
assert_eq!("A", write(TestFlags::A));
assert_eq!("A | B | C", write(TestFlags::all()));
assert_eq!("", write(TestFlags::from_bits_retain(1 << 3)));
assert_eq!(
"A",
write(TestFlags::A | TestFlags::from_bits_retain(1 << 3))
);
assert_eq!("", write(TestZero::ZERO));
assert_eq!("ABC", write(TestFlagsInvert::all()));
assert_eq!("", write(TestOverlapping::from_bits_retain(1)));
assert_eq!("A", write(TestOverlappingFull::C));
assert_eq!(
"A | D",
write(TestOverlappingFull::C | TestOverlappingFull::D)
);
}
fn write<F: Flags>(value: F) -> String
where
F::Bits: crate::parser::WriteHex,
{
let mut s = String::new();
to_writer_strict(&value, &mut s).unwrap();
s
}
}
+100
View File
@@ -0,0 +1,100 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[
(TestFlags::A, 0),
(TestFlags::empty(), 0),
(TestFlags::from_bits_retain(1 << 3), 0),
],
TestFlags::remove,
TestFlags::set,
);
case(
TestFlags::A,
&[
(TestFlags::A, 0),
(TestFlags::empty(), 1),
(TestFlags::B, 1),
],
TestFlags::remove,
TestFlags::set,
);
case(
TestFlags::ABC,
&[
(TestFlags::A, 1 << 1 | 1 << 2),
(TestFlags::A | TestFlags::C, 1 << 1),
],
TestFlags::remove,
TestFlags::set,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + Copy>(
value: T,
inputs: &[(T, T::Bits)],
mut inherent_remove: impl FnMut(&mut T, T),
mut inherent_set: impl FnMut(&mut T, T, bool),
) where
T::Bits: std::fmt::Debug + PartialEq + Copy,
{
for (input, expected) in inputs {
assert_eq!(
*expected,
{
let mut value = value;
inherent_remove(&mut value, *input);
value
}
.bits(),
"{:?}.remove({:?})",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
Flags::remove(&mut value, *input);
value
}
.bits(),
"Flags::remove({:?}, {:?})",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
inherent_set(&mut value, *input, false);
value
}
.bits(),
"{:?}.set({:?}, false)",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
Flags::set(&mut value, *input, false);
value
}
.bits(),
"Flags::set({:?}, {:?}, false)",
value,
input
);
}
}
+110
View File
@@ -0,0 +1,110 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[
(TestFlags::empty(), 0),
(TestFlags::all(), 1 | 1 << 1 | 1 << 2),
(TestFlags::from_bits_retain(1 << 3), 1 << 3),
],
TestFlags::symmetric_difference,
TestFlags::toggle,
);
case(
TestFlags::A,
&[
(TestFlags::empty(), 1),
(TestFlags::A, 0),
(TestFlags::all(), 1 << 1 | 1 << 2),
],
TestFlags::symmetric_difference,
TestFlags::toggle,
);
case(
TestFlags::A | TestFlags::B | TestFlags::from_bits_retain(1 << 3),
&[
(TestFlags::ABC, 1 << 2 | 1 << 3),
(TestFlags::from_bits_retain(1 << 3), 1 | 1 << 1),
],
TestFlags::symmetric_difference,
TestFlags::toggle,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + std::ops::BitXor<Output = T> + std::ops::BitXorAssign + Copy>(
value: T,
inputs: &[(T, T::Bits)],
mut inherent_sym_diff: impl FnMut(T, T) -> T,
mut inherent_toggle: impl FnMut(&mut T, T),
) where
T::Bits: std::fmt::Debug + PartialEq + Copy,
{
for (input, expected) in inputs {
assert_eq!(
*expected,
inherent_sym_diff(value, *input).bits(),
"{:?}.symmetric_difference({:?})",
value,
input
);
assert_eq!(
*expected,
Flags::symmetric_difference(value, *input).bits(),
"Flags::symmetric_difference({:?}, {:?})",
value,
input
);
assert_eq!(
*expected,
(value ^ *input).bits(),
"{:?} ^ {:?}",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
value ^= *input;
value
}
.bits(),
"{:?} ^= {:?}",
value,
input,
);
assert_eq!(
*expected,
{
let mut value = value;
inherent_toggle(&mut value, *input);
value
}
.bits(),
"{:?}.toggle({:?})",
value,
input,
);
assert_eq!(
*expected,
{
let mut value = value;
Flags::toggle(&mut value, *input);
value
}
.bits(),
"{:?}.toggle({:?})",
value,
input,
);
}
}
+29
View File
@@ -0,0 +1,29 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::ABC,
);
case(TestZero::empty(), TestZero::empty());
case(TestZero::all(), TestZero::all());
case(
TestFlags::from_bits_retain(1 << 3) | TestFlags::all(),
TestFlags::all(),
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(mut before: T, after: T)
where
T: std::fmt::Debug + PartialEq + Copy,
{
before.truncate();
assert_eq!(before, after, "{:?}.truncate()", before);
}
+71
View File
@@ -0,0 +1,71 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(
TestFlags::empty(),
&[
(TestFlags::A, 1),
(TestFlags::all(), 1 | 1 << 1 | 1 << 2),
(TestFlags::empty(), 0),
(TestFlags::from_bits_retain(1 << 3), 1 << 3),
],
TestFlags::union,
);
case(
TestFlags::A | TestFlags::C,
&[
(TestFlags::A | TestFlags::B, 1 | 1 << 1 | 1 << 2),
(TestFlags::A, 1 | 1 << 2),
],
TestFlags::union,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug + std::ops::BitOr<Output = T> + std::ops::BitOrAssign + Copy>(
value: T,
inputs: &[(T, T::Bits)],
mut inherent: impl FnMut(T, T) -> T,
) where
T::Bits: std::fmt::Debug + PartialEq + Copy,
{
for (input, expected) in inputs {
assert_eq!(
*expected,
inherent(value, *input).bits(),
"{:?}.union({:?})",
value,
input
);
assert_eq!(
*expected,
Flags::union(value, *input).bits(),
"Flags::union({:?}, {:?})",
value,
input
);
assert_eq!(
*expected,
(value | *input).bits(),
"{:?} | {:?}",
value,
input
);
assert_eq!(
*expected,
{
let mut value = value;
value |= *input;
value
}
.bits(),
"{:?} |= {:?}",
value,
input,
);
}
}
+40
View File
@@ -0,0 +1,40 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(false, TestFlags::empty(), TestFlags::contains_unknown_bits);
case(false, TestFlags::A, TestFlags::contains_unknown_bits);
case(
true,
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::contains_unknown_bits,
);
case(
true,
TestFlags::empty() | TestFlags::from_bits_retain(1 << 3),
TestFlags::contains_unknown_bits,
);
case(false, TestFlags::all(), TestFlags::contains_unknown_bits);
case(false, TestZero::empty(), TestZero::contains_unknown_bits);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(expected: bool, value: T, inherent: impl FnOnce(&T) -> bool) {
assert_eq!(
expected,
inherent(&value),
"{:?}.contains_unknown_bits()",
value
);
assert_eq!(
expected,
Flags::contains_unknown_bits(&value),
"Flags::contains_unknown_bits({:?})",
value
);
}
+53
View File
@@ -0,0 +1,53 @@
use super::*;
use crate::Flags;
#[test]
fn cases() {
case(0, TestFlags::empty(), TestFlags::unknown_bits);
case(0, TestFlags::A, TestFlags::unknown_bits);
case(0, TestFlags::all(), TestFlags::unknown_bits);
case(
1 << 3,
TestFlags::ABC | TestFlags::from_bits_retain(1 << 3),
TestFlags::unknown_bits,
);
case(
1 << 3,
TestFlags::from_bits_retain(1 << 3),
TestFlags::unknown_bits,
);
case(
0b11111000,
TestFlags::from_bits_retain(0b11111000),
TestFlags::unknown_bits,
);
case(0, TestZero::empty(), TestZero::unknown_bits);
case(
0,
TestExternal::from_bits_retain(0xFF),
TestExternal::unknown_bits,
);
}
#[track_caller]
fn case<T: Flags + std::fmt::Debug>(
expected: T::Bits,
value: T,
inherent: impl FnOnce(&T) -> T::Bits,
) where
T::Bits: std::fmt::Debug + PartialEq,
{
assert_eq!(expected, inherent(&value), "{:?}.unknown_bits()", value);
assert_eq!(
expected,
Flags::unknown_bits(&value),
"Flags::unknown_bits({:?})",
value,
);
}
+487
View File
@@ -0,0 +1,487 @@
use core::{
fmt,
ops::{BitAnd, BitOr, BitXor, Not},
};
use crate::{
iter,
parser::{ParseError, ParseHex, WriteHex},
};
/**
A defined flags value that may be named or unnamed.
*/
#[derive(Debug)]
pub struct Flag<B> {
name: &'static str,
value: B,
}
impl<B> Flag<B> {
/**
Define a flag.
If `name` is non-empty then the flag is named, otherwise it's unnamed.
*/
pub const fn new(name: &'static str, value: B) -> Self {
Flag { name, value }
}
/**
Get the name of this flag.
If the flag is unnamed then the returned string will be empty.
*/
pub const fn name(&self) -> &'static str {
self.name
}
/**
Get the flags value of this flag.
*/
pub const fn value(&self) -> &B {
&self.value
}
/**
Whether the flag is named.
If [`Flag::name`] returns a non-empty string then this method will return `true`.
*/
pub const fn is_named(&self) -> bool {
!self.name.is_empty()
}
/**
Whether the flag is unnamed.
If [`Flag::name`] returns a non-empty string then this method will return `false`.
*/
pub const fn is_unnamed(&self) -> bool {
self.name.is_empty()
}
}
/**
A set of defined flags using a bits type as storage.
## Implementing `Flags`
This trait is implemented by the [`bitflags`](macro.bitflags.html) macro:
```
use bitflags::bitflags;
bitflags! {
struct MyFlags: u8 {
const A = 1;
const B = 1 << 1;
}
}
```
It can also be implemented manually:
```
use bitflags::{Flag, Flags};
struct MyFlags(u8);
impl Flags for MyFlags {
type Bits = u8;
const FLAGS: &'static [Flag<Self>] = &[
Flag::new("A", MyFlags(1)),
Flag::new("B", MyFlags(1 << 1)),
];
fn bits(&self) -> Self::Bits {
self.0
}
fn from_bits_retain(bits: Self::Bits) -> Self {
MyFlags(bits)
}
}
```
## Using `Flags`
The `Flags` trait can be used generically to work with any flags types. In this example,
we can count the number of defined named flags:
```
# use bitflags::{bitflags, Flags};
fn defined_flags<F: Flags>() -> usize {
F::FLAGS.iter().filter(|f| f.is_named()).count()
}
bitflags! {
struct MyFlags: u8 {
const A = 1;
const B = 1 << 1;
const C = 1 << 2;
const _ = !0;
}
}
assert_eq!(3, defined_flags::<MyFlags>());
```
*/
pub trait Flags: Sized + 'static {
/// The set of defined flags.
const FLAGS: &'static [Flag<Self>];
/// The underlying bits type.
type Bits: Bits;
/// Get a flags value with all bits unset.
fn empty() -> Self {
Self::from_bits_retain(Self::Bits::EMPTY)
}
/// Get a flags value with all known bits set.
fn all() -> Self {
let mut truncated = Self::Bits::EMPTY;
for flag in Self::FLAGS.iter() {
truncated = truncated | flag.value().bits();
}
Self::from_bits_retain(truncated)
}
/// Get a flags value with all bits from named flags set.
///
/// This method is equivalent to [`Flags::all`] unless [`Flags::FLAGS`] contains unnamed flags.
fn all_named() -> Self {
Self::from_bits_retain(
Self::FLAGS
.iter()
.filter(|f| !f.name().is_empty())
.fold(Self::empty().bits(), |acc, f| acc | f.value().bits()),
)
}
/// Get the known bits from a flags value.
fn known_bits(&self) -> Self::Bits {
self.bits() & Self::all().bits()
}
/// Get the unknown bits from a flags value.
fn unknown_bits(&self) -> Self::Bits {
self.bits() & !Self::all().bits()
}
/// This method will return `true` if any unknown bits are set.
fn contains_unknown_bits(&self) -> bool {
self.unknown_bits() != Self::Bits::EMPTY
}
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
fn bits(&self) -> Self::Bits;
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
fn from_bits(bits: Self::Bits) -> Option<Self> {
let truncated = Self::from_bits_truncate(bits);
if truncated.bits() == bits {
Some(truncated)
} else {
None
}
}
/// Convert from a bits value, unsetting any unknown bits.
fn from_bits_truncate(bits: Self::Bits) -> Self {
Self::from_bits_retain(bits & Self::all().bits())
}
/// Convert from a bits value exactly.
fn from_bits_retain(bits: Self::Bits) -> Self;
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
fn from_name(name: &str) -> Option<Self> {
// Don't parse empty names as empty flags
if name.is_empty() {
return None;
}
for flag in Self::FLAGS {
if flag.name() == name {
return Some(Self::from_bits_retain(flag.value().bits()));
}
}
None
}
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
fn iter(&self) -> iter::Iter<Self> {
iter::Iter::new(self)
}
/// Yield a set of contained named flags values.
///
/// This method is like [`Flags::iter`], except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
fn iter_names(&self) -> iter::IterNames<Self> {
iter::IterNames::new(self)
}
/// Yield a set of all named flags defined by [`Self::FLAGS`].
fn iter_defined_names() -> iter::IterDefinedNames<Self> {
iter::IterDefinedNames::new()
}
/// Get an iterator over all defined names for this flags value.
///
/// This iterator will yield all defined names for the flags value, including
/// any convenience flags.
fn iter_equal_names(&self) -> iter::IterEqualNames<Self> {
iter::IterEqualNames::new(self)
}
/// Whether all bits in this flags value are unset.
fn is_empty(&self) -> bool {
self.bits() == Self::Bits::EMPTY
}
/// Whether all known bits in this flags value are set.
fn is_all(&self) -> bool {
// NOTE: We check against `Self::all` here, not `Self::Bits::ALL`
// because the set of all flags may not use all bits
Self::all().bits() | self.bits() == self.bits()
}
/// Whether any set bits in `other` are also set in `self`.
fn intersects(&self, other: Self) -> bool
where
Self: Sized,
{
self.bits() & other.bits() != Self::Bits::EMPTY
}
/// Whether all set bits in `other` are also set in `self`.
fn contains(&self, other: Self) -> bool
where
Self: Sized,
{
self.bits() & other.bits() == other.bits()
}
/// Remove any unknown bits from the flags.
fn truncate(&mut self)
where
Self: Sized,
{
*self = Self::from_bits_truncate(self.bits());
}
/// The bitwise or (`|`) of the bits in `self` and `other`.
fn insert(&mut self, other: Self)
where
Self: Sized,
{
*self = Self::from_bits_retain(self.bits()).union(other);
}
/// The intersection of `self` with the complement of `other` (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
fn remove(&mut self, other: Self)
where
Self: Sized,
{
*self = Self::from_bits_retain(self.bits()).difference(other);
}
/// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
fn toggle(&mut self, other: Self)
where
Self: Sized,
{
*self = Self::from_bits_retain(self.bits()).symmetric_difference(other);
}
/// Call [`Flags::insert`] when `value` is `true` or [`Flags::remove`] when `value` is `false`.
fn set(&mut self, other: Self, value: bool)
where
Self: Sized,
{
if value {
self.insert(other);
} else {
self.remove(other);
}
}
/// Unsets all bits in the flags.
fn clear(&mut self)
where
Self: Sized,
{
*self = Self::empty();
}
/// The bitwise and (`&`) of the bits in `self` and `other`.
#[must_use]
fn intersection(self, other: Self) -> Self {
Self::from_bits_retain(self.bits() & other.bits())
}
/// The bitwise or (`|`) of the bits in `self` and `other`.
#[must_use]
fn union(self, other: Self) -> Self {
Self::from_bits_retain(self.bits() | other.bits())
}
/// The intersection of `self` with the complement of `other` (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[must_use]
fn difference(self, other: Self) -> Self {
Self::from_bits_retain(self.bits() & !other.bits())
}
/// The bitwise exclusive-or (`^`) of the bits in `self` and `other`.
#[must_use]
fn symmetric_difference(self, other: Self) -> Self {
Self::from_bits_retain(self.bits() ^ other.bits())
}
/// The bitwise negation (`!`) of the bits in `self`, truncating the result.
#[must_use]
fn complement(self) -> Self {
Self::from_bits_truncate(!self.bits())
}
}
/**
A bits type that can be used as storage for a flags type.
*/
pub trait Bits:
Clone
+ Copy
+ PartialEq
+ BitAnd<Output = Self>
+ BitOr<Output = Self>
+ BitXor<Output = Self>
+ Not<Output = Self>
+ Sized
+ 'static
{
/// A value with all bits unset.
const EMPTY: Self;
/// A value with all bits set.
const ALL: Self;
}
// Not re-exported: prevent custom `Bits` impls being used in the `bitflags!` macro,
// or they may fail to compile based on crate features
pub trait Primitive {}
macro_rules! impl_bits {
($($u:ty, $i:ty,)*) => {
$(
impl Bits for $u {
const EMPTY: $u = 0;
const ALL: $u = <$u>::MAX;
}
impl Bits for $i {
const EMPTY: $i = 0;
const ALL: $i = <$u>::MAX as $i;
}
impl ParseHex for $u {
fn parse_hex(input: &str) -> Result<Self, ParseError> {
<$u>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
}
}
impl ParseHex for $i {
fn parse_hex(input: &str) -> Result<Self, ParseError> {
<$i>::from_str_radix(input, 16).map_err(|_| ParseError::invalid_hex_flag(input))
}
}
impl WriteHex for $u {
fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
write!(writer, "{:x}", self)
}
}
impl WriteHex for $i {
fn write_hex<W: fmt::Write>(&self, mut writer: W) -> fmt::Result {
write!(writer, "{:x}", self)
}
}
impl Primitive for $i {}
impl Primitive for $u {}
)*
}
}
impl_bits! {
u8, i8,
u16, i16,
u32, i32,
u64, i64,
u128, i128,
usize, isize,
}
/// A trait for referencing the `bitflags`-owned internal type
/// without exposing it publicly.
pub trait PublicFlags {
/// The type of the underlying storage.
type Primitive: Primitive;
/// The type of the internal field on the generated flags type.
type Internal;
}
#[doc(hidden)]
#[deprecated(note = "use the `Flags` trait instead")]
pub trait BitFlags: ImplementedByBitFlagsMacro + Flags {
/// An iterator over enabled flags in an instance of the type.
type Iter: Iterator<Item = Self>;
/// An iterator over the raw names and bits for enabled flags in an instance of the type.
type IterNames: Iterator<Item = (&'static str, Self)>;
}
#[allow(deprecated)]
impl<B: Flags> BitFlags for B {
type Iter = iter::Iter<Self>;
type IterNames = iter::IterNames<Self>;
}
impl<B: Flags> ImplementedByBitFlagsMacro for B {}
/// A marker trait that signals that an implementation of `BitFlags` came from the `bitflags!` macro.
///
/// There's nothing stopping an end-user from implementing this trait, but we don't guarantee their
/// manual implementations won't break between non-breaking releases.
#[doc(hidden)]
pub trait ImplementedByBitFlagsMacro {}
pub(crate) mod __private {
pub use super::{ImplementedByBitFlagsMacro, PublicFlags};
}