navid/haze / 48ef02229ff0b40a4849e26fc1a9f371991f791d48bb426ffeb35dad068eb87d / samples/baseline_3/externs.hz

externs.hz

← samples/baseline_3 · 1304 bytes · raw · download

// C externs, C-layout structs, cstr, and pointer helpers.

extern (C) abs(x i32) i32 = "abs"
extern (C) puts(text cstr) i32 = "puts"

type DivResult extern {
    quot i32
    rem i32
}

extern (C) div(num i32, den i32) DivResult = "div"

fn make_div() DivResult => DivResult{ quot = 5, rem = 2 }

fn sum_div(value DivResult) i32 => value.quot + value.rem

fn mutate_div(value DivResult) i32 {
    var local = value
    local.quot = 100
    return local.quot
}

fn main() {
    print(abs(-7))
    puts(cstr::from_str("hello from C"))

    const result = div(7, 3)
    print(result.quot)
    print(result.rem)

    var local = DivResult{ quot = 9, rem = 1 }
    local.quot = 4
    print(local.quot)

    const made = make_div()
    print(made.quot)
    print(sum_div(made))
    print(mutate_div(made))
    print(made.quot)

    print(cstr::is_null(cstr::null()))
    print(ptr::null() == ptr::null())

    const text = cstr::to_str(cstr::from_str("world"))
    match text {
        OK(value) => print(value)
        Error(err) => match err {
            CStrError.NullPointer => print(-1)
            CStrError.InvalidUtf8 => print(-2)
        }
    }

    const bytes = cstr::to_bytes(cstr::from_str("abc"))
    match bytes {
        OK(value) => print(value.len)
        Error(err) => print(-3)
    }
}