Varriount, I'm not sure if it's intended, but you can use ord to convert a bitset of an appropriate size to an int. E.g.
var s: set[0..31]
incl(s, 1)
incl(s, 3)
echo ord(s)
This does fall apart for sets bigger than the bitsize of int (same as with cast), so I don't know how much it can be relied upon.
Maybe I'm not understanding it well, but I'm trying the following test file:
type
flag* = enum
skip_html = (1 shl 0),
use_xhtml = (1 shl 7),
proc test() =
echo int(skip_html)
echo int(use_xhtml)
var a = {skip_html, use_xhtml}
echo "a is ", a
let b = cast[cint](a)
echo "b is ", b
echo "ord a ", ord(a)
when isMainModule: test()
When I run nimrod c -r flag; ./flag, which compiles the source and runs it twice, I get:
1
128
a is {skip_html, use_xhtml}
b is 1605994256
ord a 140734799382288
1
128
a is {skip_html, use_xhtml}
b is 1457628880
ord a 140734651016912
Essentially, every run the casting of the set returns a different value. Is this not how sets are to be casted to integers? For reference, looping over the bits and or'ing the value seems to work as I expect:
type
flag* = enum
skip_html = (1 shl 0),
use_xhtml = (1 shl 7),
proc custom_cast(bits: set[flag]): cint =
for f in bits: result = result or cint(f)
proc test() =
echo int(skip_html)
echo int(use_xhtml)
var a = {skip_html, use_xhtml}
echo "a is ", a
let b = custom_cast(a)
echo "b is ", b # b is 129
when isMainModule: test()
Maybe you should cast to something which is of the same size as your set a.
If I cast with cast[int16](a) I get random values on each run too:
type
flag* = enum
skip_html = (1 shl 0),
use_xhtml = (1 shl 7),
proc custom_cast(bits: set[flag]): int16 =
for f in bits: result = result or int16(f)
proc test() =
var a = {skip_html, use_xhtml}
echo "sizeof a ", a.sizeof
let b = cast[int16](a)
echo "cast is ", b
echo "safe is ", custom_cast(a)
when isMainModule: test()
Running this twice gives me:
sizeof a 16
cast is -10480
safe is 129
sizeof a 16
cast is 30416
safe is 129
Again, what you likely want instead is this:
type
flag* = enum
skip_html = 0,
use_xhtml = 7,
Then in the set representation use_xhtml will become the 7th bit.