summaryrefslogtreecommitdiff
path: root/zap/source/any/str/utf8enc.c
blob: a6b31c6a40858f3b7e84e95433f8b99a81e8b76f (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
/*
	Copyright 2022-2023 Gabriel Jensen.
	This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
	If a copy of the MPL was not distributed with this file, You can obtain one at <https://mozilla.org/MPL/2.0>.
*/

#include <zap/str.h>

void zap_utf8enc(zap_i8 * dest,zap_i02 const * src) {
	for (;;++src) {
		zap_i02 const chr = *src;
		if (chr > 0xFFFFu) { /* Four octets. */
			*dest = 0xF0u + (chr >> 0x12u);
			++dest;
			*dest = 0x80u + (chr >> 0xCu & 0x3Fu);
			++dest;
			*dest = 0x80u + (chr >> 0x6u & 0x3Fu);
			++dest;
			*dest = 0x80u + (chr & 0x3Fu);
			++dest;
			continue;
		}
		if (chr >= 0x7FFu) { /* Three octets. */
			*dest = 0xE0u + (zap_i8)(chr >> 0xCu);
			++dest;
			*dest = 0x80u + (zap_i8)(chr >> 0x6u & 0x3Fu);
			++dest;
			*dest = 0x80u + (zap_i8)(chr & 0x3Fu);
			++dest;
			continue;
		}
		if (chr >= 0x7Fu) { /* Two octets. */
			*dest = 0xC0u + (zap_i8)(chr >> 0x6u);
			++dest;
			*dest = 0x80u + (zap_i8)(chr & 0x3Fu);
			++dest;
			continue;
		}
		/* One octet. */
		*dest = chr;
		++dest;
		if (chr == 0x0u) break;
	}
}