From fc703975362888212bf5a8c5d446d06db0ccbb0a Mon Sep 17 00:00:00 2001 From: Avril Date: Wed, 3 Nov 2021 23:23:03 +0000 Subject: [PATCH] C API: Type spec and flags (start) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use bitfields for ty + tyflag in struct for `rng_next()` options. Fortune for rngxx's current commit: Middle blessing − 中吉 --- include/rngxx.h | 20 ++++++++++++++++++++ include/rngxx.hpp | 2 +- src/capi-bridge.cpp | 8 ++++++++ src/capi.c | 13 ++++++++++++- 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/include/rngxx.h b/include/rngxx.h index dbff170..0933d8a 100644 --- a/include/rngxx.h +++ b/include/rngxx.h @@ -24,10 +24,30 @@ enum rng_kind { RNG_KIND_CRAND, }; +enum rng_next_flag { + RNG_TYQ_SIGNED = 0, // Binary with `unsigned`. + RNG_TYQ_UNSIGNED = 1 << 0, + + RNG_TYQ_CHAOS = 1 << 1, +}; // 2 bits + +enum rng_next_type { + RNG_TY_BLOB = 0, + + RNG_TY_INT8, + RNG_TY_INT16, + RNG_TY_INT32, + RNG_TY_INT64, + + RNG_TY_F32, + RNG_TY_F64, +}; // 4 bits + // -- // -- #ifndef _RNGXX_IMPL_ONLY_TYPES // -- C API functions -- (C++ NO compat) rng_t* rng_new(enum rng_kind kind, u64 seed[static restrict 1]); +void rng_free(rng_t* rng); // -- // -- #endif diff --git a/include/rngxx.hpp b/include/rngxx.hpp index 32f2c3b..e396e16 100644 --- a/include/rngxx.hpp +++ b/include/rngxx.hpp @@ -71,7 +71,7 @@ struct Random inline virtual ~iterator(){} protected: - virtual T _sample() { if (rng) return rng->next(); else throw ObjectMoved(); } + virtual T _sample() { if (LIKELY(rng)) return rng->next(); else throw ObjectMoved(); } virtual inline void _init() {} private: inline explicit iterator(Random& rng) : rng(&rng){ _init(); } diff --git a/src/capi-bridge.cpp b/src/capi-bridge.cpp index e94cfdc..1484ead 100644 --- a/src/capi-bridge.cpp +++ b/src/capi-bridge.cpp @@ -6,6 +6,7 @@ #include "capi-bridge.h" extern "C" { + // Internal bridge members _export(internal) rng_t* RNG_IMPL(mkdriver)(rng_kind kind, u64* restrict seed) { @@ -16,4 +17,11 @@ extern "C" { default: return NULL; } } + + + // Direct C interface members + void rng_free(rng_t* rng) + { + delete rng; + } } diff --git a/src/capi.c b/src/capi.c index e52848b..5bc4b3b 100644 --- a/src/capi.c +++ b/src/capi.c @@ -1,11 +1,22 @@ // Contains the library exported C API functions. // Actual work may be done in `capi-bridge.cpp`, `capi-bridge.h` bridges this shim TU with that working one +#include +#include + +#include #include #include "capi-bridge.h" +#define assert_not_null(expr, ...) ({ __auto_type _nn__expr = (expr); \ + if(UNLIKELY(_nn__expr == NULL)) { fprintf(stderr, "fatal (unexpected null pointer): " __VA_ARGS__); abort(); } \ + _nn__expr; }) + rng_t* rng_new(enum rng_kind kind, u64 seed[static restrict 1]) { - return RNG_IMPL(mkdriver) (kind, &seed[0]); + return assert_not_null(RNG_IMPL(mkdriver) (kind, &seed[0]), "invalid kind %d", (int)kind); } +// void rng_free() - direct bridge + +