Biflags requirements

It seems like support bit fields for C interop · Issue #314 · rust-lang/rfcs · GitHub has stalled somewhat.

What exactly are the requirements for people using bitflags? Use cases, etc. I'm looking forward to reviving it.

From what I've seen when doing low level bit twiddling you essentially need named integer

enum Bitflag : byte {
   CompressionGzip = 32,
   CompressionRar = 41
}

var b = (BitFlag) 44; // valid even no such mapping exists

How do you deal with such match?

match Bitflag{
    CompressionGzip=>...,
    CompressionRar=>...,
    _=>...// you must write such match, since that is legal.
}

You may need implementations like:

trait _Bitflag{
    const CompressionGzip=32;
    const CompressionRar=41;
}
struct Bitflag;
impl _Bitflag for Bitflag{}
let enum=Bitflag::CompressionGzip;

Well, that's why I ask. Would such a simple solution work?

My colleague working on some C# low level API, insists that this use case is essential for him. In his case, there can be other compression formats that are available but unsupported.

As to how it would work with match either

  • It wouldn't
  • It would behave as non-exaustible enums.

If you just need something that works like a C# enum, then make a newtype with some associated constants. (bitfields are harder, but that's not what your example is using.)

@Lokathor has a fancy macro to do it in sola_kesto/macros.rs at main · Lokathor/sola_kesto · GitHub

But really, it just boils down to

#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
struct Bitflag(u8);
impl Bitflag {
    const CompressionGzip: Bitflag = Bitflag(32);
    const CompressionRar : Bitflag = Bitflag(41);
}
3 Likes

Hm, maybe I am missing something, some kind of use case. Hence my questions

See:

retep998:

Bitfield support in a library buys me nothing. I need dedicated syntax in the language. Anything less than that is useless for me.

Source

You seem to be confusing bitfields with bitflags. Those are different things.

5 Likes