gstr
A single-header UTF-8 and grapheme-cluster string library for C23. Drop include/gstr.h into your project—no build system, no separate compilation unit, and no dependencies beyond standard libc.
Standard C string functions operate on bytes, not perceived characters:
#include <string.h>
#include "gstr.h"
strlen("Hello"); // 5 bytes | gstrlen("Hello", 5) -> 5 graphemes
strlen("你好"); // 6 bytes | gstrlen("你好", 6) -> 2 graphemes (4 cols)
strlen("👨👩👧"); // 18 bytes | gstrlen("👨👩👧", 18) -> 1 grapheme (2 cols)
gstr implements Unicode 17.0.0 extended grapheme cluster segmentation (UAX #29), terminal display-width calculation, and a <string.h>-style API where every length, slice, search, truncation, and pad respects grapheme boundaries.
Features & Scope
| Feature |
gstr.h |
libgrapheme |
utf8proc |
libunistring |
ICU |
| Integration |
Single #include |
Build + link |
Build + link |
Build + link |
Build + link |
| Files |
1 (~118 KB) |
~15 |
~10 |
~100+ |
1000+ |
| Library binary |
None (header-only)* |
~30 KB |
~300 KB |
~2 MB |
~38 MB |
| Unicode version |
17.0.0 |
15.0 |
16.0 |
16.0 |
16.0 |
| Language |
C23 (extern "C" C++17) |
C99 |
C99 |
C99 |
C/C++ |
| Grapheme segmentation |
✅ (UAX #29) |
✅ |
✅ |
✅ |
✅ |
| High-level string API |
✅ |
❌ |
❌ |
Partial |
✅ |
| Terminal display width |
✅ |
❌ |
✅ |
✅ |
✅ |
| Column-width pad/trunc |
✅ |
❌ |
❌ |
❌ |
❌ |
| Dependencies |
libc |
None |
None |
libc |
libc++ |
*All functions are static inline. Unused functions are eliminated by the compiler; a minimal gstrlen + gstrwidth caller emits ~18 KB at -O2 (~13 KB static const Unicode lookup tables).
Handled:
- UAX #29 extended grapheme clusters (GB3–GB13, GB999): ZWJ emoji sequences (GB11), Indic conjuncts with explicit-halant ZWNJ (GB9c), Regional Indicator flag pairs of arbitrary length (GB12/GB13), Hangul syllables/jamo, combining marks, CRLF
- Terminal display width: East Asian Wide/Fullwidth, ZWJ emoji, flags, keycap sequences, VS15/VS16 presentation, conjoining Hangul jamo, standalone vs. attached skin-tone modifiers
- Unicode
White_Space (25 codepoints) and CommonMark 0.31.2 punctuation/symbol classification (P* + S*)
Out of scope (by design):
- Unicode normalization (NFC/NFD) — use ICU or utf8proc
- Complex script shaping (Arabic cursive, Indic ligature rendering) — use HarfBuzz
- Bidirectional layout (BiDi) — use FriBidi
- Full Unicode case folding — case functions currently fold ASCII letters only (
a-z/A-Z)
Quick Start
Copy include/gstr.h into your include path and include it directly—no GSTR_IMPLEMENTATION macro is needed:
#include "gstr.h"
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *text = "Hello 世界! 👋";
size_t len = strlen(text); /* 18 bytes */
printf("Bytes: %zu\n", len); /* 18 */
printf("Graphemes: %zu\n", gstrlen(text, len)); /* 11 */
printf("Columns: %zu\n", gstrwidth(text, len)); /* 14 */
char col[32];
gstrwtrunc(col, sizeof(col), text, len, 9);
printf("Clipped: [%s]\n", col); /* [Hello 世] (8 cols) */
return 0;
}
Compile with any C23 compiler:
cc -std=c23 -Iinclude -o hello hello.c
Option 2: Install system-wide (with pkg-config)
make install # Installs gstr.h and gstr.pc under /usr/local
cc -std=c23 $(pkg-config --cflags gstr) -o hello hello.c
Core Concepts & API Contracts
| Unit |
Meaning |
Example |
| Byte |
Single 8-bit char |
'A' = 1 byte, '中' = 3 bytes, '😀' = 4 bytes |
| Codepoint |
Unicode scalar value (U+0000–U+10FFFF) |
'é' = 1 (U+00E9) or 2 (e + U+0301); 👨👩👧 = 5 codepoints |
| Grapheme |
User-perceived character (UAX #29 cluster) |
👨👩👧 = 1 grapheme (5 codepoints, 18 bytes, 2 terminal cols) |
Key contracts across the entire header:
- Explicit byte lengths everywhere. Every function takes
(ptr, byte_len) as size_t—supporting non-terminated slices, embedded NUL bytes, and strings past INT_MAX without hidden strlen() scans.
- Buffer-safe writers. Every function writing to
dst takes dst_size, always NUL-terminates (when dst_size > 0), returns bytes written (excluding NUL), and never splits a UTF-8 sequence or grapheme cluster.
utf8_decode() vs. utf8_valid(). utf8_decode() returns 0 only when the input buffer is empty or NULL. On malformed UTF-8 (overlongs, surrogates, truncated sequences, stray continuations), it writes UTF8_REPLACEMENT_CHAR (U+FFFD) to *codepoint (if non-NULL) and returns the number of bytes skipped (>= 1). Use utf8_valid() to validate input.
- Linear iteration (
O(n) vs. O(n²)). gstroff() and gstrat() scan from the start of the string on each call. To iterate over every cluster, advance incrementally with utf8_next_grapheme():for (size_t off = 0; off < len; ) {
size_t next = utf8_next_grapheme(s, len, off);
/* cluster is s[off..next), byte length = next - off */
off = next;
}
- Important edge cases:
gstroff() clamping: If grapheme_n >= gstrlen(s, byte_len), gstroff() returns byte_len. Use gstrat() when you need to detect out-of-range indices (NULL).
- CRLF in delimiter/set strings:
gstrsep(), gstrspn(), gstrcspn(), and gstrpbrk() segment the delimiter/set string into grapheme clusters. Because CR+LF is one cluster (GB3), "\r\n" matches only CRLF while "\n\r" matches lone LF or lone CR. Pass "\r\n\n\r" to match all newline forms.
- Control-character width:
utf8_cpwidth() returns -1 for C0/DEL/C1 controls (including \t and \n), whereas gstrwidth() and gstr_grapheme_width() count them as 0 columns.
- Multi-unit padding: Both
gstr*pad() (grapheme count) and gstrw*pad() (column width) repeat whole copies of pad using floor division so they never overshoot the target. When gstrw*pad() truncates a wide source and stops short of target_cols (e.g., clipping a 2-column ideograph at an odd column), it pads the remaining gap.
Common Recipes
Terminal UI Column Layout
char buf[64];
/* Align CJK/emoji to exact terminal columns (not grapheme count) */
const char *label = "日本"; /* 2 graphemes, 4 columns, 6 bytes */
gstrwrpad(buf, sizeof(buf), label, 6, 10, " ", 1); /* "日本 " (10 cols) */
const char *emoji = "👋"; /* 1 grapheme, 2 columns, 4 bytes */
gstrwpad(buf, sizeof(buf), emoji, 4, 10, "-", 1); /* "----👋----" (10 cols) */
/* Clip without splitting a wide cluster */
const char *line = "Hello世界!"; /* 10 columns, 12 bytes */
gstrwtrunc(buf, sizeof(buf), line, 12, 8); /* "Hello世" (7 cols) */
Cursor Movement (Forward & Backward)
const char *s = "e\xCC\x81 👨👩👧"; /* 22 bytes, 3 graphemes */
size_t len = 22;
size_t pos = 0;
pos = utf8_next_grapheme(s, len, pos); /* -> 3 (after "é") */
pos = utf8_next_grapheme(s, len, pos); /* -> 4 (after " ") */
pos = utf8_next_grapheme(s, len, pos); /* -> 22 (after "👨👩👧") */
pos = utf8_prev_grapheme(s, len, pos); /* -> 4 (back over whole family emoji) */
Search, Replace, Trim & Tokenize
char out[64];
/* Trim Unicode whitespace (ASCII + NBSP + ideographic space, etc.) */
const char *ws = "\xC2\xA0 hello \xE3\x80\x80";
gstrtrim(out, sizeof(out), ws, strlen(ws)); /* "hello" */
/* Replace all occurrences */
gstrreplace(out, sizeof(out), "one two one", 11, "one", 3, "1", 1); /* "1 two 1" */
/* Split on any newline form (CRLF, LF, or CR) */
const char *p = "a\r\nb\nc";
size_t rem = 6, tlen;
const char *tok;
while ((tok = gstrsep(&p, &rem, "\r\n\n\r", 4, &tlen)) != NULL) {
printf("[%.*s]\n", (int)tlen, tok); /* [a], [b], [c] */
}
Low-Level UTF-8 Validation, Decode & Encode
size_t err_off;
if (!utf8_valid(buf, len, &err_off)) {
fprintf(stderr, "invalid UTF-8 at byte %zu\n", err_off);
}
uint32_t cp;
size_t n = utf8_decode("中", 3, &cp); /* n = 3, cp = 0x4E2D */
char enc[UTF8_MAX_BYTES];
size_t w = utf8_encode(0x1F600, enc); /* w = 4 (😀) */
API Reference
Version & Constant Macros
GSTR_VERSION /* Library version string, e.g. "4.0.0" */
GSTR_BUILD_ID /* Build identifier (overridable via -D) */
GSTR_UNICODE_VERSION /* "17.0.0" (+ _MAJOR, _MINOR, _UPDATE) */
UTF8_REPLACEMENT_CHAR /* 0xFFFD */
UTF8_MAX_BYTES /* 4 */
UTF-8 & Navigation Layer
| Function |
Returns / Behavior |
utf8_decode(bytes, length, *cp) |
Decodes one codepoint (1–4 bytes); 0 only if empty/NULL. Malformed input writes U+FFFD to *cp (if non-NULL) and returns bytes skipped (>= 1). |
utf8_encode(cp, buffer) |
Encodes scalar value to 1–4 UTF-8 bytes; 0 on surrogate, > 0x10FFFF, or NULL buffer. |
utf8_valid(text, length, *err_off) |
1 if well-formed UTF-8, 0 otherwise (sets *err_off if non-NULL). |
utf8_cpcount(text, length) |
Counts Unicode codepoints (not grapheme clusters). |
utf8_next(text, length, offset) |
Byte offset of next codepoint. |
utf8_prev(text, length, offset) |
Byte offset of previous codepoint (resyncs with utf8_decode on malformed UTF-8). |
utf8_next_grapheme(text, length, offset) |
Byte offset of next UAX #29 grapheme cluster boundary. |
utf8_prev_grapheme(text, length, offset) |
Byte offset of previous UAX #29 grapheme boundary (exact across RI flag runs of any length; single clusters >128 codepoints unspecified). |
utf8_cpwidth(cp) |
-1 (C0/DEL/C1 control), 0 (NUL, combining/format marks except U+00AD), 1 (normal + U+00AD), 2 (East Asian Wide/Fullwidth). |
utf8_charwidth(text, length, offset) |
utf8_cpwidth() of the codepoint decoded at offset. |
utf8_is_zerowidth(cp) |
1 if in ZERO_WIDTH_RANGES (Mn, Me, Cf excluding U+00AD, plus conjoining jamo & attached skin tones). |
utf8_is_wide(cp) |
1 if East Asian Width W or F. |
utf8_truncate(text, length, max_cols) |
Byte offset truncating to max_cols at a codepoint boundary. |
Character Classification
| Function |
Returns / Behavior |
gstr_is_unicode_punct_or_symbol(cp) |
1 for General_Category P* or S* (CommonMark 0.31.2; matches ispunct() in POSIX/C locale for ASCII). (Renamed from gstr_is_unicode_punctuation in v4.0.0.) |
gstr_is_whitespace_cp(cp) |
1 for all 25 Unicode White_Space codepoints. |
gstr_is_whitespace(g, g_len) |
1 if grapheme is a single Unicode White_Space codepoint or CR+LF. |
gstr_is_whitespace_ascii(g, g_len) |
1 if grapheme is ASCII whitespace ( , \t, \n, \r, \v, \f, or CR+LF). |
Grapheme String Layer
Length, Width & Indexing
| Function |
Behavior |
gstrlen(s, byte_len) |
Count grapheme clusters. |
gstrnlen(s, byte_len, max_graphemes) |
Count up to max_graphemes clusters. |
gstrwidth(s, byte_len) |
Total terminal display width in columns (controls = 0). |
gstr_grapheme_width(s, byte_len, offset, next) |
Display width of single cluster s[offset..next). |
gstroff(s, byte_len, grapheme_n) |
Byte offset of grapheme_n (O(n)); clamps to byte_len if out of range. |
gstrat(s, byte_len, grapheme_n, *out_len) |
Pointer to grapheme_n (O(n)), or NULL if out of range (*out_len untouched on NULL). |
Comparison & Prefix/Suffix
| Function |
Behavior |
gstrcmp(a, a_len, b, b_len) |
Lexicographical grapheme-by-grapheme comparison (<0, 0, >0). |
gstrncmp(a, a_len, b, b_len, n) |
Compare up to n graphemes. |
gstrcasecmp(a, a_len, b, b_len) |
Case-insensitive comparison (ASCII letters only). |
gstrncasecmp(a, a_len, b, b_len, n) |
Case-insensitive comparison of up to n graphemes (ASCII only). |
gstrstartswith(s, s_len, prefix, prefix_len) |
1 if s starts with prefix on grapheme boundaries, else 0. |
gstrendswith(s, s_len, suffix, suffix_len) |
1 if s ends with suffix on grapheme boundaries, else 0. |
Search & Span
| Function |
Behavior |
gstrchr(s, len, grapheme, g_len) |
Pointer to first occurrence of a single grapheme, or NULL. |
gstrrchr(s, len, grapheme, g_len) |
Pointer to last occurrence of a single grapheme, or NULL. |
gstrstr(haystack, h_len, needle, n_len) |
Pointer to first substring match on grapheme boundaries, or NULL. |
gstrrstr(haystack, h_len, needle, n_len) |
Pointer to last substring match, or NULL. |
gstrcasestr(haystack, h_len, needle, n_len) |
Case-insensitive substring search (ASCII only), or NULL. |
gstrcount(s, len, needle, n_len) |
Count non-overlapping occurrences of needle. |
gstrspn(s, len, accept, a_len) |
Count leading graphemes present in accept. |
gstrcspn(s, len, reject, r_len) |
Count leading graphemes not present in reject. |
gstrpbrk(s, len, accept, a_len) |
Pointer to first grapheme in accept, or NULL. |
| Function |
Behavior |
gstrsub(dst, dst_size, src, src_len, start, count) |
Extract count graphemes starting at start. |
gstrcpy(dst, dst_size, src, src_len) |
Copy src, truncating cleanly on a grapheme boundary. |
gstrncpy(dst, dst_size, src, src_len, n) |
Copy up to n graphemes. |
gstrcat(dst, dst_size, src, src_len) |
Append src to dst (bounded scan of dst up to dst_size). |
gstrncat(dst, dst_size, src, src_len, n) |
Append up to n graphemes to dst. |
gstrdup(s, len) |
malloc’d NUL-terminated copy (NULL on NULL input, SIZE_MAX, or OOM); caller frees. |
gstrndup(s, len, n) |
malloc’d copy of up to n graphemes; caller frees. |
| Function |
Behavior |
gstrsep(&stringp, &lenp, delim, d_len, *tok_len) |
Extract next token separated by any grapheme in delim; updates *stringp/*lenp. |
gstrltrim(dst, dst_size, src, src_len) |
Copy src with leading Unicode whitespace removed. |
gstrrtrim(dst, dst_size, src, src_len) |
Copy src with trailing Unicode whitespace removed. |
gstrtrim(dst, dst_size, src, src_len) |
Copy src with leading and trailing Unicode whitespace removed. |
gstrrev(dst, dst_size, src, src_len) |
Reverse grapheme order into dst. |
gstrreplace(dst, dst_size, src, src_len, old, old_len, new_s, new_len) |
Replace all occurrences of old with new_s. |
gstrlower(dst, dst_size, src, src_len) |
Lowercase ASCII letters (A-Z → a-z); non-ASCII unchanged. |
gstrupper(dst, dst_size, src, src_len) |
Uppercase ASCII letters (a-z → A-Z); non-ASCII unchanged. |
Ellipsis, Fill, Grapheme Padding & Column-Width Layout
| Function |
Behavior |
gstrellipsis(dst, dst_size, src, src_len, max_g, ell, ell_len) |
Truncate to max_g graphemes with ell (defaults to "..."). |
gstrfill(dst, dst_size, grapheme, g_len, count) |
Repeat grapheme[0..g_len) count times without overflowing dst_size. |
gstrlpad(dst, dst_size, src, src_len, width, pad, pad_len) |
Left-pad to width graphemes (floor division on multi-grapheme pad). |
gstrrpad(dst, dst_size, src, src_len, width, pad, pad_len) |
Right-pad to width graphemes. |
gstrpad(dst, dst_size, src, src_len, width, pad, pad_len) |
Center-pad to width graphemes. |
gstrwtrunc(dst, dst_size, src, src_len, max_cols) |
Truncate to fit within max_cols terminal columns. |
gstrwlpad(dst, dst_size, src, src_len, cols, pad, pad_len) |
Left-pad to cols columns (clips wide src and pads any remaining gap; zero-width pad falls back to " "). |
gstrwrpad(dst, dst_size, src, src_len, cols, pad, pad_len) |
Right-pad to cols columns. |
gstrwpad(dst, dst_size, src, src_len, cols, pad, pad_len) |
Center-pad to cols columns. |
make # Build all test suites and tools/cursor_walk
make test # Run all gates & suites twice (-O0 debug + -O2 ASan/UBSan):
# - check-compat (instantiated C23/C++17/-Wconversion)
# - check-version (VERSION file vs header fallback / git tag)
# - ~950 checks across 10 suites (incl. headless editor tests)
# - 134 walk-fixture lines + 38 cursor_walk verifications
# - 766/766 official Unicode GraphemeBreakTest.txt vectors
make test-conformance # Run only the Unicode 17.0.0 GraphemeBreakTest gate
make run-test-san # Run only the -O2 + ASan/UBSan pass
make test-boundary-full # Run >2 GB / past-INT_MAX regression tests (needs >2 GB RAM)
make check-tables # Regenerate Unicode tables from UCD & assert byte-identity
make coverage # Merged gcov line coverage of include/gstr.h across all suites
make format-check # Verify clang-format (22.1.5) and comment indentation
make install # Install header + gstr.pc (supports PREFIX= and DESTDIR=)
make clean # Remove build, test, cache, and coverage artifacts
Updating Unicode Tables
Tables in include/gstr.h are generated directly from Unicode Consortium UCD files (version-cached under scripts/.unicode_cache/<version>/):
python3 scripts/gen_unicode_tables.py | python3 scripts/splice_tables.py
make check-tables test format-check
See RELEASING.md for the full release and Unicode-bump checklist.
- Footprint:
~118 KB single header (no .a/.so library binary). At -O2, a minimal gstrlen + gstrwidth caller emits ~18 KB (~13 KB static const Unicode lookup tables); calling every public function emits ~24–27 KB (~41–47 KB if every static inline function is forced out-of-line). Zero dynamic allocations except gstrdup() / gstrndup().
- Thread safety: Reentrant with zero mutable global state (all tables are
static const). Concurrent calls reading shared const inputs with caller-owned output buffers are race-free (verified under ThreadSanitizer).
- Platforms: C23 (
-std=c23) and C++17+ (extern "C"), libc-only (<stddef.h>, <stdint.h>, <stdlib.h>, <string.h>), endian-agnostic, and locale-independent (no <ctype.h> or <locale.h>). Byte lengths and offsets use size_t throughout, supporting 16-bit, 32-bit, and 64-bit int targets (requires sizeof(size_t) >= sizeof(int) and 32-bit uint32_t). CI tests Linux (gcc/clang), macOS (clang), and Windows (msvc).
License
MIT License — see LICENSE.
评论