www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - BitFlags usage

reply Alex <sascha.orlov gmail.com> writes:
I have a question on usage of BitFlags, described here:
https://dlang.org/library/std/typecons/bit_flags.html

and/or on bitop
https://dlang.org/phobos/core_bitop.html#.bsf

A similar example to the bit flags example is given here:

[code]
import std.typecons;
enum Rs : ubyte
{
	None,
	s_f = 1 << 0,
	s_s = 1 << 1,
	s_p = 1 << 2,
	t_f = 1 << 3,
	t_s = 1 << 4,
	t_p = 1 << 5
}

struct R
{
	import core.bitop : popcnt;
	invariant {/* some useful asserts here */}
	this(ubyte val)
	{
		assert(popcnt(cast(uint)val) == 2); // separate asserts...
		r |= cast(BitFlags!Rs)val; // line 20 ... from asignment
	}
	BitFlags!Rs r; 	
	alias r this;
}

void main(){}
[/code]

ok, now: the idea is that if I use the functionality of bit 
flags, then I can take advantage of bit operations. And I'm 
looking for the inverse operation of converting a bit flag to its 
raw value, like the line before last in the example on the bit 
flags documentation site.

How should my line 20 looks like to achieve an assignment of a 
raw value to a BitFlags variable in a single step?
Jan 25 2018
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 01/25/2018 03:50 AM, Alex wrote:

          r |= cast(BitFlags!Rs)val; // line 20 ... from asignment
r |= BitFlags!Rs(cast(Rs)val); Ali
Jan 25 2018
parent Alex <sascha.orlov gmail.com> writes:
On Thursday, 25 January 2018 at 13:05:07 UTC, Ali Çehreli wrote:
 On 01/25/2018 03:50 AM, Alex wrote:

          r |= cast(BitFlags!Rs)val; // line 20 ... from 
 asignment
r |= BitFlags!Rs(cast(Rs)val); Ali
Thanks :)
Jan 25 2018