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
//! UTF-8 <> UTF-16 conversion support.

// Since Rust haven't stable support of UTF-16, I've ported this code
// from Sciter SDK (aux-cvt.h)

// (C) 2003-2015, Andrew Fedoniouk (andrew@terrainformatica.com)


#![allow(dead_code)]

use std::ffi::{CStr, CString};
use capi::sctypes::{LPCSTR, LPCWSTR, LPCBYTE};


/// UTF-8 to UTF-16* converter.
#[allow(unused_parens)]
fn towcs(utf: &[u8], outbuf: &mut Vec<u16>) -> bool
{
	let errc = 0x003F; // '?'
	let mut num_errors = 0;

	let last = utf.len();
	let mut pc = 0;
	while (pc < last) {
		let mut b: u32 = utf[pc] as u32; pc += 1;
		if (b == 0) { break; }

		if ((b & 0x80) == 0) {
			// 1-BYTE sequence: 000000000xxxxxxx = 0xxxxxxx

		} else if ((b & 0xE0) == 0xC0) {
			// 2-BYTE sequence: 00000yyyyyxxxxxx = 110yyyyy 10xxxxxx
			if (pc == last) {
				outbuf.push(errc);
				num_errors += 1;
				break;
			}

			b = (b & 0x1f) << 6;
			b |= (utf[pc] as u32 & 0x3f); pc += 1;

		} else if ((b & 0xf0) == 0xe0) {
			// 3-BYTE sequence: zzzzyyyyyyxxxxxx = 1110zzzz 10yyyyyy 10xxxxxx
			if (pc >= last - 1) {
				outbuf.push(errc);
				num_errors += 1;
				break;
			}

			b = (b & 0x0f) << 12;
			b |= (utf[pc] as u32 & 0x3f) << 6; pc += 1;
			b |= (utf[pc] as u32 & 0x3f); pc += 1;

			if (b == 0xFEFF && outbuf.len() == 0) { // bom at start
				continue; // skip it
			}

		} else if ((b & 0xf8) == 0xf0) {
			// 4-BYTE sequence: 11101110wwwwzzzzyy + 110111yyyyxxxxxx = 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
			if(pc >= last - 2) { outbuf.push(errc); break; }

			b = (b & 0x07) << 18;
			b |= (utf[pc] as u32 & 0x3f) << 12; pc += 1;
			b |= (utf[pc] as u32 & 0x3f) << 6; pc += 1;
			b |= (utf[pc] as u32 & 0x3f); pc += 1;

			// b shall contain now full 21-bit unicode code point.
			assert!((b & 0x1fffff) == b);
			if((b & 0x1fffff) != b) {
				outbuf.push(errc);
				num_errors += 1;
				continue;
			}

			outbuf.push( (0xd7c0 + (b >> 10)) as u16 );
			outbuf.push( (0xdc00 | (b & 0x3ff)) as u16 );

		} else {
			num_errors += 1;
			b = errc as u32;
		}

		outbuf.push(b as u16);
	}
	return num_errors == 0;
}


/// UTF-16 to UTF-8 converter.
#[allow(unused_parens)]
fn fromwcs(wcs: &[u16], outbuf: &mut Vec<u8>) -> bool
{
	let mut num_errors = 0;

	let last = wcs.len();
	let mut pc = 0;
	while (pc < last) {
		let c: u32 = wcs[pc] as u32;
		if (c < (1 << 7)) {
			outbuf.push(c as u8);

		} else if (c < (1 << 11)) {
			outbuf.push(((c >> 6) | 0xc0) as u8);
			outbuf.push(((c & 0x3f) | 0x80) as u8);

		} else if (c < (1 << 16)) {
			outbuf.push(((c >> 12) | 0xe0) as u8);
			outbuf.push((((c >> 6) & 0x3f) | 0x80) as u8);
			outbuf.push(((c & 0x3f) | 0x80) as u8);

		} else if (c < (1 << 21)) {
			outbuf.push(((c >> 18) | 0xf0) as u8);
			outbuf.push((((c >> 12) & 0x3f) | 0x80) as u8);
			outbuf.push((((c >> 6) & 0x3f) | 0x80) as u8);
			outbuf.push(((c & 0x3f) | 0x80) as u8);

		} else {
			num_errors += 1;
		}
		pc += 1;
	}
	return num_errors == 0;
}


/// UTF-16 string length like `libc::wcslen`.
fn wcslen(sz: LPCWSTR) -> usize
{
	if sz.is_null() {
		return 0;
	}
	let mut i: isize = 0;
	loop {
		let c = unsafe { *sz.offset(i) };
		if c == 0 {
			break;
		}
		i += 1;
	}
	return i as usize;
}

/// UTF8 to rust string conversion. See also `s2u!`.
pub fn u2s(sz: LPCSTR) -> String
{
	if sz.is_null() {
		return String::new();
	}
	let cs = unsafe { CStr::from_ptr(sz) };
	let cow = cs.to_string_lossy();
	return cow.into_owned();
}

/// UTF8 to rust string conversion. See also `s2u!`.
pub fn u2sn(sz: LPCSTR, len: usize) -> String
{
	let chars = unsafe { ::std::slice::from_raw_parts(sz as LPCBYTE, len) };
	let s = String::from_utf8_lossy(chars).into_owned();
	return s;
}

/// UTF-16 to rust string conversion. See also `s2w!`.
pub fn w2s(sz: LPCWSTR) -> String
{
	return w2sn(sz, wcslen(sz));
}

/// UTF-16 to rust string conversion. See also `s2w!`.
pub fn w2sn(sz: LPCWSTR, len: usize) -> String
{
	if sz.is_null() {
		return String::new();
	}
	let chars = unsafe { ::std::slice::from_raw_parts(sz, len) };
	let s = String::from_utf16_lossy(chars);
	return s;
}

/// Rust string to UTF-8 conversion.
pub fn s2un(s: &str) -> (CString, u32) {
	let cs = CString::new(s).unwrap();
	let n = cs.as_bytes().len() as u32;
	return (cs, n);
}

/// Rust string to UTF-16 conversion.
pub fn s2vec(s: &str) -> Vec<u16> {
	let cs = CString::new(s).unwrap();
	let mut out = Vec::with_capacity(s.len() * 2);
	towcs(cs.to_bytes(), &mut out);
	if out.len() > 0 {
		out.push(0);
	}
	return out;
}

/// Rust string to UTF-16 conversion.
pub fn s2vecn(s: &str) -> (Vec<u16>, u32) {
	let cs = CString::new(s).unwrap();
	let mut out = Vec::with_capacity(s.len() * 2);
	towcs(cs.to_bytes(), &mut out);
	let n = out.len() as u32;
	if n > 0 {
		out.push(0);
	}
	return (out, n);
}



mod tests {
	#![allow(unused_imports)]

	use std::ffi::{CStr, CString};
	use capi::sctypes::{LPCWSTR, LPCSTR};
	use super::{wcslen, u2s, w2s, s2vec};

	#[test]
	fn test_wcslen() {
		let nullptr: LPCWSTR = ::std::ptr::null();
		assert_eq!(wcslen(nullptr), 0);

		let v = vec![0 as u16];
		assert_eq!(wcslen(v.as_ptr()), 0);

		let v = vec![32, 32, 0];
		assert_eq!(wcslen(v.as_ptr()), 2);
	}

	#[test]
	fn test_u2s() {
		let nullptr: LPCSTR = ::std::ptr::null();
		assert_eq!(u2s(nullptr), String::new());

		let s = "hi, there";
		assert_eq!(u2s(CString::new(s).unwrap().as_ptr()), s);
	}

	#[test]
	fn test_w2s() {
		let nullptr: LPCWSTR = ::std::ptr::null();
		assert_eq!(w2s(nullptr), String::new());

		let v = vec![32, 32, 0];	// SP
		assert_eq!(w2s(v.as_ptr()), "  ");
	}

	#[test]
	fn s2w_test() {
		let v = s2vec("");
		assert_eq!(v, []);

		assert_eq!(s2vec(""), []);

		assert_eq!(s2vec("A"), ['A' as u16, 0]);

		assert_eq!(s2vec("AB"), ['A' as u16, 'B' as u16, 0]);

		let (cs, n) = s2w!("");
		assert_eq!(n, 0);
		assert_eq!(cs, []);
	}
}