summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibC/wchar.cpp
blob: dd7ca983cfcbc042375970cd88ada1efb2187fc8 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Assertions.h>
#include <AK/Format.h>
#include <AK/UnicodeUtils.h>
#include <errno.h>
#include <string.h>
#include <wchar.h>

static unsigned int mbstate_expected_bytes(mbstate_t* state)
{
    if (state->stored_bytes == 0) {
        return 0;
    }

    unsigned char first = state->bytes[0];

    // Single-byte sequences have their first bit unset
    if ((first & 0b10000000) == 0) {
        return 1;
    }

    // Two-byte sequences start with 0b110xxxxx
    if ((first & 0b11100000) == 0b11000000) {
        return 2;
    }

    // Three-byte sequences start with 0b1110xxxx
    if ((first & 0b11110000) == 0b11100000) {
        return 3;
    }

    // Four-byte sequences start with 0b11110xxx
    if ((first & 0b11111000) == 0b11110000) {
        return 4;
    }

    // Everything else is invalid
    return 0;
}

extern "C" {

size_t wcslen(const wchar_t* str)
{
    size_t len = 0;
    while (*(str++))
        ++len;
    return len;
}

wchar_t* wcscpy(wchar_t* dest, const wchar_t* src)
{
    wchar_t* original_dest = dest;
    while ((*dest++ = *src++) != '\0')
        ;
    return original_dest;
}

wchar_t* wcsncpy(wchar_t* dest, const wchar_t* src, size_t num)
{
    wchar_t* original_dest = dest;
    while (((*dest++ = *src++) != '\0') && ((size_t)(dest - original_dest) < num))
        ;
    return original_dest;
}

int wcscmp(const wchar_t* s1, const wchar_t* s2)
{
    while (*s1 == *s2++)
        if (*s1++ == 0)
            return 0;
    return *(const wchar_t*)s1 - *(const wchar_t*)--s2;
}

int wcsncmp(const wchar_t* s1, const wchar_t* s2, size_t n)
{
    if (!n)
        return 0;
    do {
        if (*s1 != *s2++)
            return *(const wchar_t*)s1 - *(const wchar_t*)--s2;
        if (*s1++ == 0)
            break;
    } while (--n);
    return 0;
}

wchar_t* wcschr(const wchar_t* str, int c)
{
    wchar_t ch = c;
    for (;; ++str) {
        if (*str == ch)
            return const_cast<wchar_t*>(str);
        if (!*str)
            return nullptr;
    }
}

const wchar_t* wcsrchr(const wchar_t* str, wchar_t wc)
{
    wchar_t* last = nullptr;
    wchar_t c;
    for (; (c = *str); ++str) {
        if (c == wc)
            last = const_cast<wchar_t*>(str);
    }
    return last;
}

wchar_t* wcscat(wchar_t* dest, const wchar_t* src)
{
    size_t dest_length = wcslen(dest);
    size_t i;
    for (i = 0; src[i] != '\0'; i++)
        dest[dest_length + i] = src[i];
    dest[dest_length + i] = '\0';
    return dest;
}

wchar_t* wcsncat(wchar_t* dest, const wchar_t* src, size_t n)
{
    size_t dest_length = wcslen(dest);
    size_t i;
    for (i = 0; i < n && src[i] != '\0'; i++)
        dest[dest_length + i] = src[i];
    dest[dest_length + i] = '\0';
    return dest;
}

wchar_t* wcstok(wchar_t* str, const wchar_t* delim, wchar_t** ptr)
{
    wchar_t* used_str = str;
    if (!used_str) {
        used_str = *ptr;
    }

    size_t token_start = 0;
    size_t token_end = 0;
    size_t str_len = wcslen(used_str);
    size_t delim_len = wcslen(delim);

    for (size_t i = 0; i < str_len; ++i) {
        bool is_proper_delim = false;

        for (size_t j = 0; j < delim_len; ++j) {
            if (used_str[i] == delim[j]) {
                // Skip beginning delimiters
                if (token_end - token_start == 0) {
                    ++token_start;
                    break;
                }

                is_proper_delim = true;
            }
        }

        ++token_end;
        if (is_proper_delim && token_end > 0) {
            --token_end;
            break;
        }
    }

    if (used_str[token_start] == '\0')
        return nullptr;

    if (token_end == 0) {
        return &used_str[token_start];
    }

    used_str[token_end] = '\0';
    return &used_str[token_start];
}

long wcstol(const wchar_t*, wchar_t**, int)
{
    dbgln("FIXME: Implement wcstol()");
    TODO();
}

long long wcstoll(const wchar_t*, wchar_t**, int)
{
    dbgln("FIXME: Implement wcstoll()");
    TODO();
}

wint_t btowc(int c)
{
    if (c == EOF) {
        return WEOF;
    }

    // Multi-byte sequences in UTF-8 have their highest bit set
    if (c & (1 << 7)) {
        return WEOF;
    }

    return c;
}

size_t mbrtowc(wchar_t* pwc, const char* s, size_t n, mbstate_t* state)
{
    static mbstate_t _anonymous_state = {};

    if (state == nullptr) {
        state = &_anonymous_state;
    }

    // s being a null pointer is a shorthand for reading a single null byte.
    if (s == nullptr) {
        pwc = nullptr;
        s = "";
        n = 1;
    }

    // Stop early if we can't read anything
    if (n == 0) {
        return 0;
    }

    size_t consumed_bytes = 0;

    // Fill the first byte if we haven't done that yet
    if (state->stored_bytes == 0) {
        state->bytes[state->stored_bytes++] = s[0];
        consumed_bytes++;
    }

    size_t expected_bytes = mbstate_expected_bytes(state);

    // Check if the first byte is invalid
    if (expected_bytes == 0) {
        *state = {};
        errno = EILSEQ;
        return -1;
    }

    while (state->stored_bytes < expected_bytes) {
        if (consumed_bytes == n) {
            // No complete multibyte character
            return -2;
        }

        unsigned char c = s[consumed_bytes];

        // Continuation bytes have to start with 0b10xxxxxx
        if ((c & 0b11000000) != 0b10000000) {
            // Invalid multibyte character
            *state = {};
            errno = EILSEQ;
            return -1;
        }

        state->bytes[state->stored_bytes++] = c;
        consumed_bytes++;
    }

    wchar_t codepoint = state->bytes[0];

    // Mask out the "length" bits if necessary
    if (expected_bytes > 1) {
        codepoint &= (1 << (7 - expected_bytes)) - 1;
    }

    for (unsigned int i = 1; i < expected_bytes; i++) {
        // Each continuation byte contains 6 bits of data
        codepoint = codepoint << 6;
        codepoint |= state->bytes[i] & 0b111111;
    }

    if (pwc) {
        *pwc = codepoint;
    }

    // We want to read the next multibyte character, but keep all other properties.
    state->stored_bytes = 0;

    if (codepoint == 0) {
        *state = {};
        return 0;
    }

    return consumed_bytes;
}

size_t mbrlen(const char*, size_t, mbstate_t*)
{
    dbgln("FIXME: Implement mbrlen()");
    TODO();
}

size_t wcrtomb(char* s, wchar_t wc, mbstate_t*)
{
    if (s == nullptr)
        wc = L'\0';

    auto nwritten = AK::UnicodeUtils::code_point_to_utf8(wc, [&s](char byte) {
        if (s != nullptr)
            *s++ = byte;
    });

    if (nwritten < 0) {
        errno = EILSEQ;
        return (size_t)-1;
    } else {
        return nwritten;
    }
}

int wcscoll(const wchar_t* ws1, const wchar_t* ws2)
{
    // TODO: Actually implement a sensible sort order for this,
    // because right now we are doing what LC_COLLATE=C would do.
    return wcscmp(ws1, ws2);
}

int wctob(wint_t)
{
    dbgln("FIXME: Implement wctob()");
    TODO();
}

int mbsinit(const mbstate_t* state)
{
    if (!state) {
        return 1;
    }

    if (state->stored_bytes != 0) {
        return 0;
    }

    return 1;
}

wchar_t* wcspbrk(const wchar_t* wcs, const wchar_t* accept)
{
    for (const wchar_t* cur = accept; *cur; cur++) {
        wchar_t* res = wcschr(wcs, *cur);
        if (res)
            return res;
    }

    return nullptr;
}

wchar_t* wcsstr(const wchar_t* haystack, const wchar_t* needle)
{
    size_t nlen = wcslen(needle);

    if (nlen == 0)
        return const_cast<wchar_t*>(haystack);

    size_t hlen = wcslen(haystack);

    while (hlen >= nlen) {
        if (wcsncmp(haystack, needle, nlen) == 0)
            return const_cast<wchar_t*>(haystack);

        haystack++;
        hlen--;
    }

    return nullptr;
}

wchar_t* wmemchr(const wchar_t* s, wchar_t c, size_t n)
{
    for (size_t i = 0; i < n; i++) {
        if (s[i] == c)
            return const_cast<wchar_t*>(&s[i]);
    }

    return nullptr;
}

wchar_t* wmemcpy(wchar_t* dest, const wchar_t* src, size_t n)
{
    for (size_t i = 0; i < n; i++)
        dest[i] = src[i];

    return dest;
}

wchar_t* wmemset(wchar_t* wcs, wchar_t wc, size_t n)
{
    for (size_t i = 0; i < n; i++) {
        wcs[i] = wc;
    }

    return wcs;
}

wchar_t* wmemmove(wchar_t* dest, const wchar_t* src, size_t n)
{
    if (dest > src) {
        for (size_t i = 1; i <= n; i++) {
            dest[n - i] = src[n - i];
        }
    } else if (dest < src) {
        for (size_t i = 0; i < n; i++) {
            dest[i] = src[i];
        }
    }

    return dest;
}

unsigned long wcstoul(const wchar_t*, wchar_t**, int)
{
    dbgln("TODO: Implement wcstoul()");
    TODO();
}

unsigned long long wcstoull(const wchar_t*, wchar_t**, int)
{
    dbgln("TODO: Implement wcstoull()");
    TODO();
}

float wcstof(const wchar_t*, wchar_t**)
{
    dbgln("TODO: Implement wcstof()");
    TODO();
}

double wcstod(const wchar_t*, wchar_t**)
{
    dbgln("TODO: Implement wcstod()");
    TODO();
}

long double wcstold(const wchar_t*, wchar_t**)
{
    dbgln("TODO: Implement wcstold()");
    TODO();
}

int swprintf(wchar_t*, size_t, const wchar_t*, ...)
{
    dbgln("TODO: Implement swprintf()");
    TODO();
}

int wcwidth(wchar_t wc)
{
    if (wc == L'\0')
        return 0;

    // Printable ASCII.
    if (wc >= 0x20 && wc <= 0x7e)
        return 1;

    // Non-printable ASCII.
    if (wc <= 0x7f)
        return -1;

    // TODO: Implement wcwidth for non-ASCII characters.
    return 1;
}

size_t wcsrtombs(char* dest, const wchar_t** src, size_t len, mbstate_t* ps)
{
    static mbstate_t _anonymous_state = {};

    if (ps == nullptr)
        ps = &_anonymous_state;

    size_t written = 0;
    while (true) {
        size_t ret = 0;
        char buf[MB_LEN_MAX];

        // Convert next wchar to multibyte.
        ret = wcrtomb(buf, **src, ps);

        // wchar can't be represented as multibyte.
        if (ret == (size_t)-1) {
            errno = EILSEQ;
            return (size_t)-1;
        }

        // New bytes don't fit the buffer.
        if (dest && len < written + ret) {
            return written;
        }

        if (dest) {
            memcpy(dest, buf, ret);
            dest += ret;
        }

        // Null character has been reached
        if (**src == L'\0') {
            *src = nullptr;
            return written;
        }

        *src += 1;
        written += ret;
    }
}

size_t mbsrtowcs(wchar_t* dst, const char** src, size_t len, mbstate_t* ps)
{
    static mbstate_t _anonymous_state = {};

    if (ps == nullptr)
        ps = &_anonymous_state;

    size_t written = 0;
    while (written < len || !dst) {
        // Convert next multibyte to wchar.
        size_t ret = mbrtowc(dst, *src, MB_LEN_MAX, ps);

        // Multibyte sequence is invalid.
        if (ret == -1ul) {
            errno = EILSEQ;
            return (size_t)-1;
        }

        // Null byte has been reached.
        if (**src == '\0') {
            *src = nullptr;
            return written;
        }

        *src += ret;
        written += 1;
        if (dst)
            dst += 1;
    }

    // If we are here, we have written `len` wchars, but not reached the null byte.
    return written;
}
}