2020-12-15 09:17:46 +01:00
|
|
|
module builtin
|
|
|
|
|
2020-12-15 10:01:51 +01:00
|
|
|
const (
|
|
|
|
cp_utf8 = 65001
|
|
|
|
)
|
|
|
|
|
2020-12-15 09:17:46 +01:00
|
|
|
pub fn (_str string) to_wide() &u16 {
|
|
|
|
$if windows {
|
2021-02-14 19:31:42 +01:00
|
|
|
unsafe {
|
2021-04-04 16:43:32 +02:00
|
|
|
num_chars := (C.MultiByteToWideChar(cp_utf8, 0, &char(_str.str), _str.len,
|
2021-03-24 19:39:59 +01:00
|
|
|
0, 0))
|
2021-06-15 13:47:11 +02:00
|
|
|
mut wstr := &u16(malloc_noscan((num_chars + 1) * 2)) // sizeof(wchar_t)
|
2021-02-14 19:31:42 +01:00
|
|
|
if wstr != 0 {
|
2021-04-04 16:43:32 +02:00
|
|
|
C.MultiByteToWideChar(cp_utf8, 0, &char(_str.str), _str.len, wstr, num_chars)
|
2021-02-14 19:31:42 +01:00
|
|
|
C.memset(&byte(wstr) + num_chars * 2, 0, 2)
|
|
|
|
}
|
|
|
|
return wstr
|
2020-12-15 09:17:46 +01:00
|
|
|
}
|
|
|
|
} $else {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-15 16:15:52 +01:00
|
|
|
[unsafe]
|
2020-12-15 09:17:46 +01:00
|
|
|
pub fn string_from_wide(_wstr &u16) string {
|
|
|
|
$if windows {
|
2021-02-14 19:31:42 +01:00
|
|
|
unsafe {
|
|
|
|
wstr_len := C.wcslen(_wstr)
|
|
|
|
return string_from_wide2(_wstr, wstr_len)
|
|
|
|
}
|
2020-12-15 09:17:46 +01:00
|
|
|
} $else {
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-15 16:15:52 +01:00
|
|
|
[unsafe]
|
2020-12-15 09:17:46 +01:00
|
|
|
pub fn string_from_wide2(_wstr &u16, len int) string {
|
|
|
|
$if windows {
|
2021-02-14 19:31:42 +01:00
|
|
|
unsafe {
|
|
|
|
num_chars := C.WideCharToMultiByte(cp_utf8, 0, _wstr, len, 0, 0, 0, 0)
|
2021-06-15 13:47:11 +02:00
|
|
|
mut str_to := malloc_noscan(num_chars + 1)
|
2021-02-14 19:31:42 +01:00
|
|
|
if str_to != 0 {
|
2021-04-04 16:43:32 +02:00
|
|
|
C.WideCharToMultiByte(cp_utf8, 0, _wstr, len, &char(str_to), num_chars,
|
2021-02-14 19:31:42 +01:00
|
|
|
0, 0)
|
|
|
|
C.memset(str_to + num_chars, 0, 1)
|
|
|
|
}
|
|
|
|
return tos2(str_to)
|
2020-12-15 09:17:46 +01:00
|
|
|
}
|
|
|
|
} $else {
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reads an utf8 character from standard input
|
|
|
|
pub fn utf8_getchar() int {
|
|
|
|
c := C.getchar()
|
|
|
|
len := utf8_len(byte(~c))
|
|
|
|
if c < 0 {
|
|
|
|
return 0
|
2020-12-15 10:01:51 +01:00
|
|
|
} else if len == 0 {
|
2020-12-15 09:17:46 +01:00
|
|
|
return c
|
2020-12-15 10:01:51 +01:00
|
|
|
} else if len == 1 {
|
2020-12-15 09:17:46 +01:00
|
|
|
return -1
|
2020-12-15 10:01:51 +01:00
|
|
|
} else {
|
|
|
|
mut uc := c & ((1 << (7 - len)) - 1)
|
2020-12-15 09:17:46 +01:00
|
|
|
for i := 0; i + 1 < len; i++ {
|
|
|
|
c2 := C.getchar()
|
2020-12-15 10:01:51 +01:00
|
|
|
if c2 != -1 && (c2 >> 6) == 2 {
|
2020-12-15 09:17:46 +01:00
|
|
|
uc <<= 6
|
|
|
|
uc |= (c2 & 63)
|
2020-12-15 10:01:51 +01:00
|
|
|
} else if c2 == -1 {
|
2020-12-15 09:17:46 +01:00
|
|
|
return 0
|
2020-12-15 10:01:51 +01:00
|
|
|
} else {
|
2020-12-15 09:17:46 +01:00
|
|
|
return -1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return uc
|
|
|
|
}
|
|
|
|
}
|