GRAPHEME_ENCODE_UTF8(3)

πŸ“¦ version 3.0.0, in nixos 26.05, nixpkgs unstable

πŸ’– NAME πŸ’–

grapheme_encode_utf8 β€” encode codepoint into UTF-8 string

okay bestie, welcome to the Library Functions Manual tea on grapheme_encode_utf8(3) β€” it's giving β€œturn one codepoint into a UTF-8 string” energy, and honestly? iconic. ✨


🌸 SYNOPSIS 🌸

#include <grapheme.h>

size_t
grapheme_encode_utf8(uint_least32_t cp, char *str, size_t len);

πŸ¦‹ DESCRIPTION πŸ¦‹

So the grapheme_encode_utf8() function encodes the codepoint cp into a UTF-8-string. no cap, that's the whole main character move.

If str is not NULL and len is large enough, it writes the UTF-8-string to the memory pointed to by str. Otherwise no data is written. 🫢

bestie, clock this: if str is NULL or len isn't big enough, this function does not write any data. it's just out here doing byte math. periodt. πŸ’…

πŸŽ€ RETURN VALUES πŸŽ€

The grapheme_encode_utf8() function returns the length (in bytes) of the UTF-8-string resulting from encoding cp, even if len is not large enough or str is NULL.

so yes, it tells you how many bytes the encoded result would take, regardless of whether it actually had room to write it. lowkey helpful. ✨


🌈 EXAMPLES 🌈

/* cc (-static) -o example example.c -lgrapheme */
#include <grapheme.h>
#include <stddef.h>
#include <stdlib.h>

size_t
cps_to_utf8(const uint_least32_t *cp, size_t cplen, char *str, size_t len)
{
        size_t i, off, ret;

        for (i = 0, off = 0; i < cplen; i++, off += ret) {
                if ((ret = grapheme_encode_utf8(cp[i], str + off,
                                                len - off)) > (len - off)) {
                        /* buffer too small */
                        break;
                }
        }

        return off;
}

size_t
cps_bytelen(const uint_least32_t *cp, size_t cplen)
{
        size_t i, len;

        for (i = 0, len = 0; i < cplen; i++) {
                len += grapheme_encode_utf8(cp[i], NULL, 0);
        }

        return len;
}

char *
cps_to_utf8_alloc(const uint_least32_t *cp, size_t cplen)
{
        char *str;
        size_t len, i, ret, off;

        len = cps_bytelen(cp, cplen);

        if (!(str = malloc(len))) {
                return NULL;
        }

        for (i = 0, off = 0; i < cplen; i++, off += ret) {
                if ((ret = grapheme_encode_utf8(cp[i], str + off,
                                                len - off)) > (len - off)) {
                        /* buffer too small */
                        break;
                }
        }
        str[off] = '\0';

        return str;
}

πŸ‘‘ SEE ALSO πŸ‘‘


πŸ’œ AUTHORS πŸ’œ

Laslo Hunhold <dev@frign.de>


mwah πŸ’‹ β€” source/version: suckless.org, dated 2022-10-06. that's the cute little footer sign-off, bestie, and we are so done here. πŸ’…βœ¨

πŸ“¦ where this page comes from