6 * cast - routines for safer casting.
8 * Often you want to cast in a limited way, such as removing a const or
9 * switching between integer types. However, normal casts will work on
10 * almost any type, making them dangerous when the code changes.
12 * These C++-inspired macros serve two purposes: they make it clear the
13 * exact reason for the cast, and they also (with some compilers) cause
14 * errors when misused.
16 * Based on Jan Engelhardt's libHX macros: http://libhx.sourceforge.net/
18 * Author: Jan Engelhardt
19 * Maintainer: Rusty Russell <rusty@rustcorp.com.au>
20 * License: LGPL (v2.1 or any later version)
23 * // Given "test" output contains "3 t's in 'test string'"
24 * #include <ccan/cast/cast.h>
28 * // Find char @orig in @str, if @repl, replace them. Return number.
29 * static size_t find_chars(char *str, char orig, char repl)
31 * size_t i, count = 0;
32 * for (i = 0; str[i]; i++) {
33 * if (str[i] == orig) {
42 * // Terrible hash function.
43 * static uint64_t hash_string(const unsigned char *str)
47 * for (i = 0; str[i]; i++)
52 * int main(int argc, char *argv[])
56 * // find_chars wants a non-const string, but doesn't
57 * // need it if repl == 0.
58 * printf("%zu %c's in 'test string'\n",
59 * find_chars(cast_const(char *, "test string"),
63 * // hash_string wants an unsigned char.
64 * hash = hash_string(cast_signed(unsigned char *, argv[1]));
66 * // Need a long long to hand to printf.
67 * printf("Hash of '%s' = %llu\n", argv[1],
68 * cast_static(unsigned long long, hash));
73 int main(int argc, char *argv[])
75 /* Expect exactly one argument */
79 if (strcmp(argv[1], "depends") == 0) {
80 printf("ccan/build_assert\n");