blob: 8999623dfd2d87bd813855900713d5d114c7355d (
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
|
// Copyright (c) 2013-2021 Jean-Philippe Bruyère <jp_bruyere@hotmail.com>
//
// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
using System;
namespace Drawing2D
{
public static class Extensions
{
public static int ToUtf8 (this ReadOnlySpan<char> source, Span<byte> buff, int tabWidth = 4) {
int c = 0;
int encodedBytes = 0;
int encodedChar = 0;
while (c < source.Length) {
if (source[c] < 0xD800) {
if (source[c] == '\t') {
int encTabWidth = tabWidth - encodedChar % tabWidth;
for (int i = 0; i < encTabWidth; i++) {
buff[encodedBytes++] = 0x20;
encodedChar++;
}
c++;
continue;
}
if (source[c] < 0x80) { //1 byte
buff[encodedBytes++] = (byte)source[c++];
}else if (source[c] < 0x7FF) { //2 bytes
buff[encodedBytes++] = (byte)((source[c] >> 6) + 0xC0);
buff[encodedBytes++] = (byte)((source[c] & 0x3F) + 0x80);
c++;
} else { //3 bytes
//ushort ch = (ushort)(source[c] - 0x10000u);
buff[encodedBytes++] = (byte)((source[c] >> 12) + 0xE0);
buff[encodedBytes++] = (byte)((source[c] >> 6) & 0x00BF);
buff[encodedBytes++] = (byte)((source[c] & 0x3F) + 0x80);
c++;
}
encodedChar++;
continue;
}
throw new NotImplementedException();
}
buff[encodedBytes] = 0;
return encodedBytes;
}
/*unsafe static int Utf16toUtf8 (byte* cptr, byte* buff, int tabWidth) {
}*/
}
}
|