Created
September 27, 2021 01:13
-
-
Save leok7v/830988a40992dc2ba95440b90e773372 to your computer and use it in GitHub Desktop.
better assert() with optional format and varadic args
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once /* Copyright (c) Dmitry "Leo" Kuznetsov 2021 see LICENSE for details */ | |
#include <assert.h> // to prevent further redefinition of assert | |
// better assert(0 <= i && i < n, "index i=%d out of [0..%d( range", i, n); | |
// also available as 'swear' and 'implore' instead of assert() | |
// see: https://github.com/munificent/vigil | |
#undef assert | |
#if defined(_DEBUG) || defined(DEBUG) || defined(ASSERT_IN_NDEBUG) | |
#define assert(b, ...) do { \ | |
if (!(b)) { assertion_failed(__FILE__, __LINE__, __FUNCTION__, #b, "" __VA_ARGS__); } \ | |
} while (0) | |
#define swear(condition, ...) assert(condition, ##__VA_ARGS__); | |
#define implore(condition, ...) assert(condition, ##__VA_ARGS__); | |
#else | |
#define assert(condition, ...) do { } while (0) | |
#define swear(condition, ...) do { } while (0) | |
#define implore(condition, ...) do { } while (0) | |
#endif | |
void assertion_failed(const char* file, int line, const char* function, | |
const char* condition, const char* format, ...) __printflike(5, 6); | |
// implement your own assertion_failed, or define: | |
#ifdef VIGIL_IMPLEMENTATION | |
#include <stdarg.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
static const char* assertion_failed_filename(const char* file) { | |
char* fn = strrchr(file, '/'); | |
if (fn == (void*)0) { fn = strrchr(file, '\\'); } | |
return fn != (void*)0 ? fn + 1 : file; | |
} | |
void assertion_failed(const char* file, int line, const char* function, | |
const char* condition, const char* format, ...) { | |
const char* fn = assertion_failed_filename(file); | |
const int n = (int)strlen(format); | |
if (n == 0) { | |
fprintf(stderr, "%s:%d %s() assertion failed: \"%s\"", fn, line, function, condition); | |
} else { | |
fprintf(stderr, "%s:%d %s() assertion failed: \"%s\" ", fn, line, function, condition); | |
va_list va; | |
va_start(va, format); | |
vfprintf(stderr, format, va); | |
va_end(va); | |
} | |
if (n == 0 || format[n - 1] != '\n') { fprintf(stderr, "\n"); } | |
abort(); | |
} | |
#endif // VIGIL_IMPLEMENTATION |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment