Skip to content

Instantly share code, notes, and snippets.

@sj-i
Last active April 8, 2022 22:03
Show Gist options
  • Save sj-i/6bacf1bef255c096b3cbb78bfc29aa28 to your computer and use it in GitHub Desktop.
Save sj-i/6bacf1bef255c096b3cbb78bfc29aa28 to your computer and use it in GitHub Desktop.
U+00A5 & U+203E to CP932, with or without 'best fit' mapping
<?php
declare(strict_types=1);
const WC_NO_BEST_FIT_CHARS = 0x00000400;
function test(string $utf8_str, bool $best_fit): void {
$ffi = \FFI::cdef(<<<CDECLS
int WideCharToMultiByte(
unsigned int CodePage,
unsigned long dwFlags,
const char *lpWideCharStr,
int cchWideChar,
char *lpMultiByteStr,
int cbMultiByte,
const char *lpDefaultChar,
int *pfUsedDefaultChar
);
CDECLS,
'Kernel32.dll'
);
$test = mb_convert_encoding($utf8_str, 'UTF-16LE', 'UTF-8') . "\0";
$buffer = \FFI::new('char[2]');
$usedDefault = \FFI::new('int');
$ffi->WideCharToMultiByte(
932,
$best_fit ? 0 : WC_NO_BEST_FIT_CHARS,
$test,
-1,
$buffer,
2,
null,
\FFI::addr($usedDefault)
);
var_dump(
sprintf('%02x', \ord($buffer[0])),
sprintf('%02x', \ord($buffer[1])),
$usedDefault
);
}
test("\u{00A5}", true);
test("\u{00A5}", false);
test("\u{203E}", true);
test("\u{203E}", false);
string(2) "5c"
string(2) "00"
object(FFI\CData:int32_t)#3 (1) {
["cdata"]=>
int(0)
}
string(2) "3f"
string(2) "00"
object(FFI\CData:int32_t)#1 (1) {
["cdata"]=>
int(1)
}
string(2) "3f"
string(2) "00"
object(FFI\CData:int32_t)#3 (1) {
["cdata"]=>
int(1)
}
string(2) "3f"
string(2) "00"
object(FFI\CData:int32_t)#1 (1) {
["cdata"]=>
int(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment