Welcome to val
, a C library designed to bring the wonders of NaNboxing to the fingertips of C programmers, enabling the efficient storage of multiple data types in a single variable.
NaNboxing is a technique that leverages the NaN (Not a Number) space in IEEE 754 floating-point numbers to encode and represent various data types, such as integers, pointers, and floating-point numbers, in a single 64-bit float. This approach has been vital for languages like JavaScript, providing them with a way to optimize memory usage and enhance performance. val
aims to bestow these advantages upon C, a language that doesn’t natively offer NaNboxing.
- Versatile Storage: Handle signed/unsigned integers (up to 48 bits), double-precision floats, generic pointers, and string pointers all within a single
val_t
variable. - Type Discovery: Identify stored data types effortlessly.
- Smooth Conversion: Retrieve your original data seamlessly with type conversion functions.
- Helpful Constants: Utilize predefined constants for common values like true, false, and nil.
Store various types of data using the val()
function. Example:
val_t f = val(3.2); // Stores a double
val_t s = val("a string"); // Stores a pointer to a string
Retrieve stored data by converting val_t
variable using the appropriate function:
double num = valtodouble(f);
char * str = valtostring(s);
Check the type of data stored in val_t
using:
int type = valtype(f);
Or utilize the provided helper functions for context-specific checks:
valisinteger(x);
valisdouble(x);
// ... and more
The library defines several handy constants of type val_t
:
valfalse
valtrue
valnil
valnilpointer
valnilstr
Contributions, issues, and feature requests are welcome!
Distributed under the MIT License. See LICENSE for more information.