aboutsummaryrefslogtreecommitdiffstats
path: root/src/utf8.c
blob: 07b751e4e3653cb64bbc51d8be5dd9d6cfc9a171 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "utf8.h"
#include <unicode/ustring.h>
#include <unicode/uchar.h>
#include <unicode/ubrk.h>
#include <string.h>
#include <stdlib.h>

size_t utf8_display_width(const char *str) {
    if (str == NULL) {
        return 0;
    }

    UErrorCode status = U_ZERO_ERROR;
    int32_t utf8_len = (int32_t)strlen(str);

    // Convert UTF-8 to UTF-16 for ICU processing
    UChar *utf16 = NULL;
    int32_t utf16_len = 0;

    // First call to get required length
    u_strFromUTF8(NULL, 0, &utf16_len, str, utf8_len, &status);
    if (status != U_BUFFER_OVERFLOW_ERROR && U_FAILURE(status)) {
        return 0;
    }

    status = U_ZERO_ERROR;
    utf16 = (UChar *)malloc((utf16_len + 1) * sizeof(UChar));
    if (utf16 == NULL) {
        return 0;
    }

    u_strFromUTF8(utf16, utf16_len + 1, NULL, str, utf8_len, &status);
    if (U_FAILURE(status)) {
        free(utf16);
        return 0;
    }

    // Use break iterator to count grapheme clusters
    UBreakIterator *bi = ubrk_open(UBRK_CHARACTER, NULL, utf16, utf16_len, &status);
    if (U_FAILURE(status)) {
        free(utf16);
        return 0;
    }

    size_t width = 0;
    int32_t start = ubrk_first(bi);
    int32_t end = ubrk_next(bi);

    while (end != UBRK_DONE) {
        // Get the first code point of this grapheme cluster
        UChar32 ch;
        int32_t idx = start;
        U16_NEXT(utf16, idx, utf16_len, ch);

        // Determine display width based on East Asian Width property
        int32_t ea_width = u_getIntPropertyValue(ch, UCHAR_EAST_ASIAN_WIDTH);

        // Full-width and Wide characters take 2 columns
        if (ea_width == U_EA_FULLWIDTH || ea_width == U_EA_WIDE) {
            width += 2;
        } else {
            // All others (Narrow, Halfwidth, Neutral, Ambiguous) take 1 column
            width += 1;
        }

        start = end;
        end = ubrk_next(bi);
    }

    ubrk_close(bi);
    free(utf16);

    return width;
}