Removed return value of assertf. assertf now correctly responds to -disable-assert. Added log.assert and log.assertf. All asserts now do the @cold trick, first added to builtin.assert

This commit is contained in:
Dragos Popescu
2024-01-23 20:56:13 +02:00
parent 98b539ac5c
commit 90d1f9ab27
2 changed files with 51 additions and 9 deletions

View File

@@ -253,18 +253,24 @@ bprintf :: proc(buf: []byte, fmt: string, args: ..any) -> string {
// - args: A variadic list of arguments to be formatted
// - loc: The location of the caller
//
// Returns: True if the condition is met, otherwise triggers a runtime assertion with a formatted message
//
assertf :: proc(condition: bool, fmt: string, args: ..any, loc := #caller_location) -> bool {
@(disabled=ODIN_DISABLE_ASSERT)
assertf :: proc(condition: bool, fmt: string, args: ..any, loc := #caller_location) {
if !condition {
p := context.assertion_failure_proc
if p == nil {
p = runtime.default_assertion_failure_proc
// NOTE(dragos): We are using the same trick as in builtin.assert
// to improve performance to make the CPU not
// execute speculatively, making it about an order of
// magnitude faster
@(cold)
internal :: proc(loc: runtime.Source_Code_Location, fmt: string, args: ..any) {
p := context.assertion_failure_proc
if p == nil {
p = runtime.default_assertion_failure_proc
}
message := tprintf(fmt, ..args)
p("Runtime assertion", message, loc)
}
message := tprintf(fmt, ..args)
p("Runtime assertion", message, loc)
internal(loc, fmt, ..args)
}
return condition
}
// Runtime panic with a formatted message
//

View File

@@ -116,6 +116,42 @@ panicf :: proc(fmt_str: string, args: ..any, location := #caller_location) -> !
runtime.panic("log.panicf", location)
}
@(disabled=ODIN_DISABLE_ASSERT)
assert :: proc(condition: bool, message := "", loc := #caller_location) {
if !condition {
@(cold)
internal :: proc(message: string, loc: runtime.Source_Code_Location) {
p := context.assertion_failure_proc
if p == nil {
p = runtime.default_assertion_failure_proc
}
log(.Fatal, message, location=loc)
p("runtime assertion", message, loc)
}
internal(message, loc)
}
}
@(disabled=ODIN_DISABLE_ASSERT)
assertf :: proc(condition: bool, fmt_str: string, args: ..any, loc := #caller_location) {
if !condition {
// NOTE(dragos): We are using the same trick as in builtin.assert
// to improve performance to make the CPU not
// execute speculatively, making it about an order of
// magnitude faster
@(cold)
internal :: proc(loc: runtime.Source_Code_Location, fmt_str: string, args: ..any) {
p := context.assertion_failure_proc
if p == nil {
p = runtime.default_assertion_failure_proc
}
message := fmt.tprintf(fmt_str, ..args)
log(.Fatal, message, location=loc)
p("Runtime assertion", message, loc)
}
internal(loc, fmt_str, ..args)
}
}