OXYGENHUB
◆ main x16-emulator / src / utf8_encode.h
1.3 KiB · Objective-C · last changed chore(): initial commit 15 days ago source blame history raw
1
#pragma once
2
3
#include <stdint.h>
4
5
/**
6
 * Encode a code point using UTF-8
7
 *
8
 * @author Ondřej Hruška <[email protected]>
9
 * @license MIT
10
 *
11
 * @param out - output buffer (min 5 characters), will be 0-terminated
12
 * @param utf - code point 0-0x10FFFF
13
 * @return number of bytes on success, 0 on failure (also produces U+FFFD, which uses 3 bytes)
14
 */
15
static int utf8_encode(char *out, uint32_t utf)
16
{
17
	if (utf <= 0x7F) {
18
		// Plain ASCII
19
		out[0] = (char) utf;
20
		out[1] = 0;
21
		return 1;
22
	}
23
	else if (utf <= 0x07FF) {
24
		// 2-byte unicode
25
		out[0] = (char) (((utf >> 6) & 0x1F) | 0xC0);
26
		out[1] = (char) (((utf >> 0) & 0x3F) | 0x80);
27
		out[2] = 0;
28
		return 2;
29
	}
30
	else if (utf <= 0xFFFF) {
31
		// 3-byte unicode
32
		out[0] = (char) (((utf >> 12) & 0x0F) | 0xE0);
33
		out[1] = (char) (((utf >>  6) & 0x3F) | 0x80);
34
		out[2] = (char) (((utf >>  0) & 0x3F) | 0x80);
35
		out[3] = 0;
36
		return 3;
37
	}
38
	else if (utf <= 0x10FFFF) {
39
		// 4-byte unicode
40
		out[0] = (char) (((utf >> 18) & 0x07) | 0xF0);
41
		out[1] = (char) (((utf >> 12) & 0x3F) | 0x80);
42
		out[2] = (char) (((utf >>  6) & 0x3F) | 0x80);
43
		out[3] = (char) (((utf >>  0) & 0x3F) | 0x80);
44
		out[4] = 0;
45
		return 4;
46
	}
47
	else {
48
		// error - use replacement character
49
		out[0] = (char) 0xEF;
50
		out[1] = (char) 0xBF;
51
		out[2] = (char) 0xBD;
52
		out[3] = 0;
53
		return 0;
54
	}
55
}