odin-lang/odin-lang.org

Correct the example for Bit Field assignment (w/truncation) in the Overview and add the example that errors with constants

Closed this issue · 0 comments

The new Bit Field feature in Odin is fantastic. Please consider updating the Overview example to reflect the compiler responses.

The main example for Bit Fields has a mistake in it. When assigning a constant or literal value that is greater than the bit field field's max size it will not truncate, but will throw a compiler error. It truncates when you assign a value that is variable during runtime.

This is the section that might be updated https://odin-lang.org/docs/overview/#bit-fields

This code would show the truncation example accurately when assigning to a non-constant value:

main :: proc() {
    Foo :: bit_field u8 {
        x: u8 | 3,
    }
    f := Foo{}
    a: u8 = 15 
    f.x = a // note if you assign f.x from a literal/constant 15 it will error
    fmt.println(f.x) // 7, since it truncates 15 == 0b1111 to 0b111 == 7 (the left most digit is truncated)
}

You could also change the current example (so you have the one above and this one) to show the compiler error for assignments to constants that are too large for the bit field max size, something like this maybe:

package main
import "core:fmt"
main :: proc() {
    Foo :: bit_field i32 {
        x: i32 | 3,
    }
    f := Foo{}
    f.x = 4 // Throws compiler error: Cannot convert numeric value '4' from '4' to 'i32' from 'untyped integer'.
            //  The maximum value that can be represented with that bit_field's field of 'i32 | 3' is '3'
}