/* header->fragment generator in ISO C99 * Uses nytpu's proposed algorithm: * * This IS NOT Unicode-aware! It should be pretty trivial to modify it to * use libunistring and become Unicode-aware though. * * Written in 2021 by nytpu * SPDX-License-Identifier: CC0-1.0 */ #define _ISOC99_SOURCE #include // isalnum(), isspace(), tolower() #include // bool, true, false #include // size_t #include // calloc, free #include // strlen char * header_to_anchor(const char *header) { if (header == NULL) return NULL; size_t header_len = strlen(header); // calloc to ensure that the string is always automatically NUL-terminated char *anchor = calloc(header_len + 1, sizeof(*anchor)); if (anchor == NULL) return NULL; bool prev_is_dash = false; for (size_t hi = 0, ai = 0; hi < header_len; hi++) { if (isalnum(header[hi])) { anchor[ai++] = tolower(header[hi]); prev_is_dash = false; } else if (!prev_is_dash && (isspace(header[hi]) || header[hi] == '-')) { anchor[ai++] = '-'; prev_is_dash = true; } } return anchor; }