c3c icon indicating copy to clipboard operation
c3c copied to clipboard

Type suggestion: CBool

Open TheOnlySilverClaw opened this issue 1 year ago • 7 comments

For type-safe interaction with C APIs, it would be helpful to have a CBool type that behaves like an integer that can only be assigned 0 or 1 and be implicitly cast to bool where needed.


fn void test_cbool() @test {

    CBool value;
    value =  true;
    value = false;
    value = 0;
    value = 1;
    value = 2; // compiler error
    value = -1; // compiler error

    bool b = value;

    assert(CBool.sizeof == CInt.sizeof);
}

I know integers can already be used in conditions, but this would also communicate the allowed values and prevent accidental assignment of a wrong one for functions like these:

fn extern void foo(CInt boolFlag) {

}

TheOnlySilverClaw avatar Oct 08 '24 12:10 TheOnlySilverClaw

I want to avoid adding things merely for the convenience of C bindings. Is there some other use for this?

lerno avatar Oct 08 '24 18:10 lerno

I can't think of much. The name was deliberately chosen to reflect that usage.

I know it sounds a little weird, but so far all the C bindings I've used had at least one place where it would have been useful and I've tried emulating it with enums and bitstructs each time.

It almost nearly works this way:

bitstruct CBool : CInt {
    bool flag;
}

fn void test_cbool() @test {

    CBool value = { false };
    assert((CInt) value == 0);

    value = (CBool) 1;
    assert((CInt) value == 1);
    assert(value.flag == true);
}

It's just slightly short of being convenient with all the casts required.

So maybe a more general case could be an inline bitstruct?

TheOnlySilverClaw avatar Oct 08 '24 19:10 TheOnlySilverClaw

You could do:

enum CBool : CInt
{
  FALSE,
  TRUE
}

And now your call becomes:

foo(TRUE);
foo(FALSE);

lerno avatar Oct 08 '24 19:10 lerno

Yes, been there. I guess it works. Would you mind adding that to the standard library types?

TheOnlySilverClaw avatar Oct 08 '24 19:10 TheOnlySilverClaw

Done!

lerno avatar Oct 08 '24 20:10 lerno

See if it works as expected.

lerno avatar Oct 09 '24 11:10 lerno

Looks good:

https://codeberg.org/Silverclaw/glfw.c3l/commit/72061fb010513b281d85aaa7d468ee2b44db3555

TheOnlySilverClaw avatar Oct 09 '24 13:10 TheOnlySilverClaw