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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
|
{
Most of this code is based on similar functions from Lazarus LCLProc.
}
unit UnicodeUtils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
{en
Retrieves length in bytes of the next UTF-8 character.
@param(P
Pointer to the UTF-8 characters.)
@param(aMaxBytes
States how many bytes from P can be read.)
@param(InvalidCharLen
If an invalid UTF-8 character was found then InvalidCharLen has
the number of bytes this character spans. If the character was valid
InvalidCharLen is zero.)
}
function SafeUTF8NextCharLen(P: PByte; aMaxBytes: Integer; out InvalidCharLen: Integer): Integer;
{en
Retrieves length in bytes of the previous UTF-8 character.
It does not read from P, but rather from memory locations before P.
@param(P
Pointer to the UTF-8 characters.)
@param(aMaxBytes
States how many bytes from P *backwards* can be read.
So, to safely read 3 bytes backwards ([p-1], [p-2], [p-3])
this parameter should be at least 3.)
@param(InvalidCharLen
If an invalid UTF-8 character was found then InvalidCharLen has
the number of bytes this character spans. If the character was valid
InvalidCharLen is zero.)
}
function SafeUTF8PrevCharLen(P: PByte; aMaxBytes: Integer; out InvalidCharLen: Integer): Integer;
function SafeUTF8NextCharStart(UTF8Str: PByte; Len: PtrInt): PByte;
function SafeUTF8PrevCharEnd(UTF8Str: PByte; Len: PtrInt): PByte;
{en
Returns UTF-16 character length, which is either 1 or 2.
@param(utf16char
Any UTF-16 char or one of the surrogate pairs.)
}
function UTF16CharLen(utf16char: Word): Integer;
{en
Converts an UTF-16 surrogate pair into a unicode character.
}
function utf16PairToUnicode(u1, u2: Word): Cardinal;
function Utf16LEToUtf8(const s: string): string; // UTF16-LE 2 or 4 byte little endian
function Utf16BEToUtf8(const s: string): string; // UTF16-BE 2 or 4 byte big endian
function Utf32LEToUtf8(const s: string): string; // UTF32-LE 4 byte little endian
function Utf32BEToUtf8(const s: string): string; // UTF32-BE 4 byte big endian
function Utf8ToUtf16LE(const s: string): string; // UTF16-LE 2 or 4 byte little endian
function Utf8ToUtf16BE(const s: string): string; // UTF16-BE 2 or 4 byte big endian
function UTF8ToUCS4(const UTF8Text: String): UCS4String;
{en
Replaces invalid UTF-8 characters with '?'.
}
function Utf8ReplaceBroken(const s: String): String;
implementation
uses
LCLProc, LazUTF8;
const
maxUTF8Len = 7; // really is 4, but this includes any invalid characters up to length 7
function SafeUTF8NextCharLen(P: PByte; aMaxBytes: Integer; out InvalidCharLen: Integer): Integer;
var
BytesLen: Integer;
i: Integer;
begin
if (p=nil) or (aMaxBytes = 0) then
begin
InvalidCharLen := 0;
Result := 0;
end
else if p^<%10000000 then begin
// regular single byte character
InvalidCharLen := 0;
Result := 1;
end
else if p^<%11000000 then begin
// invalid single byte character
InvalidCharLen := 1;
Result := 1;
end
else
begin
// Read length of UTF-8 character in bytes.
if ((p^ and %11100000) = %11000000) then BytesLen := 2
else if ((p^ and %11110000) = %11100000) then BytesLen := 3
else if ((p^ and %11111000) = %11110000) then BytesLen := 4
else if ((p^ and %11111100) = %11111000) then BytesLen := 5
else if ((p^ and %11111110) = %11111100) then BytesLen := 6
else if ((p^ and %11111111) = %11111110) then BytesLen := 7
else
begin
InvalidCharLen := 1;
exit(1);
end;
// Check if the next bytes are from the middle of a character.
for i := 1 to BytesLen - 1 do
begin
if (aMaxBytes < i) or ((p[i] and %11000000) <> %10000000) then
begin
InvalidCharLen := i;
exit(1);
end;
end;
InvalidCharLen := 0;
Result := BytesLen;
end;
end;
function SafeUTF8PrevCharLen(P: PByte; aMaxBytes: Integer; out InvalidCharLen: Integer): Integer;
var
BytesLen: Integer;
signature: Byte;
begin
if (p=nil) or (aMaxBytes = 0) then
begin
InvalidCharLen := 0;
Result := 0;
end
else if p[-1]<%10000000 then begin
// regular single byte character
InvalidCharLen := 0;
Result := 1;
end
else
begin
for BytesLen := 1 to maxUTF8Len do
begin
if (aMaxBytes < BytesLen) then
begin
InvalidCharLen := aMaxBytes;
exit(1);
end;
// Move past all the bytes in the middle of a character.
if (p[-BytesLen] and %11000000) <> %10000000 then
break;
if BytesLen = maxUTF8Len then
begin
InvalidCharLen := BytesLen;
exit(1);
end;
end;
if p[-BytesLen]<%11000000 then
begin
// invalid first byte of a character
InvalidCharLen := BytesLen;
Result := 1;
end
else
begin
signature := Byte($FF shl (7 - BytesLen));
if (p[-BytesLen] and signature) = Byte(signature shl 1) then
begin
// Correct first byte of a character.
InvalidCharLen := 0;
Result := BytesLen;
end
else
begin
// Invalid first byte of a character, or p is in the middle of a character.
InvalidCharLen := BytesLen;
Result := 1;
end;
end;
end;
end;
function SafeUTF8NextCharStart(UTF8Str: PByte; Len: PtrInt): PByte;
var
CharLen: LongInt;
InvalidCharLen: Integer;
begin
Result:=UTF8Str;
if Result<>nil then begin
while (Len>0) do begin
CharLen := SafeUTF8NextCharLen(Result, Len, InvalidCharLen);
if InvalidCharLen > 0 then
begin
dec(Len,InvalidCharLen);
inc(Result,InvalidCharLen);
end
else if CharLen = 0 then
exit(nil)
else
exit(Result);
end;
Result:=nil;
end;
end;
function SafeUTF8PrevCharEnd(UTF8Str: PByte; Len: PtrInt): PByte;
var
CharLen: LongInt;
InvalidCharLen: Integer;
begin
Result:=UTF8Str;
if Result<>nil then begin
while (Len>0) do begin
CharLen := SafeUTF8PrevCharLen(Result, Len, InvalidCharLen);
if InvalidCharLen > 0 then
begin
dec(Len,InvalidCharLen);
dec(Result,InvalidCharLen);
end
else if CharLen = 0 then
exit(nil)
else
exit(Result); // Result is the character beginning
end;
Result:=nil;
end;
end;
function UTF16CharLen(utf16char: Word): Integer; inline;
begin
if (utf16char < $D800) or (utf16char > $DFFF) then
Result := 1
else
Result := 2;
end;
function utf16PairToUnicode(u1, u2: Word): Cardinal;
begin
if (u1 >= $D800) and (u1 <= $DBFF) then
begin
if (u2 >= $DC00) and (u2 <= $DFFF) then
Result := (Cardinal(u1 - $D800) shl 10) + Cardinal(u2 - $DC00) + $10000
else
Result := 0;
end
else
Result := u1;
end;
function Utf16LEToUtf8(const s: string): string;
var
len: Integer;
Src, Limit: PWord;
Dest: PAnsiChar;
u: Cardinal;
begin
if Length(s) < 2 then begin
Result:='';
exit;
end;
Src:=PWord(Pointer(s));
Limit := PWord(Pointer(Src) + Length(s));
SetLength(Result, length(s) * 2);
Dest:=PAnsiChar(Result);
while Src + 1 <= Limit do begin
len := UTF16CharLen(Src^);
if len = 1 then
u := LEtoN(Src^)
else
begin
if Src + 2 <= Limit then
u := utf16PairToUnicode(LEtoN(Src[0]), LEtoN(Src[1]))
else
break;
end;
inc(Src, len);
if u<128 then begin
Dest^:=chr(u);
inc(Dest);
end else begin
inc(Dest,UnicodeToUTF8SkipErrors(u,Dest));
end;
end;
len:=PtrUInt(Dest)-PtrUInt(Result);
if len>length(Result) then
RaiseGDBException('');
SetLength(Result,len);
end;
function Utf16BEToUtf8(const s: string): string;
var
len: Integer;
Src, Limit: PWord;
Dest: PAnsiChar;
u: Cardinal;
begin
if Length(s) < 2 then begin
Result:='';
exit;
end;
Src:=PWord(Pointer(s));
Limit := PWord(Pointer(Src) + Length(s));
SetLength(Result, length(s) * 2);
Dest:=PAnsiChar(Result);
while Src + 1 <= Limit do begin
len := UTF16CharLen(Src^);
if len = 1 then
u := BEtoN(Src^)
else
begin
if Src + 2 <= Limit then
u := utf16PairToUnicode(BEtoN(Src[0]), BEtoN(Src[1]))
else
break;
end;
inc(Src, len);
if u<128 then begin
Dest^:=chr(u);
inc(Dest);
end else begin
inc(Dest,UnicodeToUTF8SkipErrors(u,Dest));
end;
end;
len:=PtrUInt(Dest)-PtrUInt(Result);
if len>length(Result) then
RaiseGDBException('');
SetLength(Result,len);
end;
function Utf32LEToUtf8(const s: string): string;
var
len: Integer;
Src: PLongWord;
Dest: PAnsiChar;
i: Integer;
c: LongWord;
begin
if Length(s) < 4 then begin
Result:='';
exit;
end;
len:=length(s) div 4;
SetLength(Result,len*4);
Src:=PLongWord(Pointer(s));
Dest:=PAnsiChar(Result);
for i:=1 to len do begin
c:=LEtoN(Src^);
inc(Src);
if c<128 then begin
Dest^:=chr(c);
inc(Dest);
end else begin
inc(Dest,UnicodeToUTF8SkipErrors(c,Dest));
end;
end;
len:=PtrUInt(Dest)-PtrUInt(Result);
if len>length(Result) then
RaiseGDBException('');
SetLength(Result,len);
end;
function Utf32BEToUtf8(const s: string): string;
var
len: Integer;
Src: PLongWord;
Dest: PAnsiChar;
i: Integer;
c: LongWord;
begin
if Length(s) < 4 then begin
Result:='';
exit;
end;
len:=length(s) div 4;
SetLength(Result,len*4);
Src:=PLongWord(Pointer(s));
Dest:=PAnsiChar(Result);
for i:=1 to len do begin
c:=BEtoN(Src^);
inc(Src);
if c<128 then begin
Dest^:=chr(c);
inc(Dest);
end else begin
inc(Dest,UnicodeToUTF8SkipErrors(c,Dest));
end;
end;
len:=PtrUInt(Dest)-PtrUInt(Result);
if len>length(Result) then
RaiseGDBException('');
SetLength(Result,len);
end;
function Utf8ToUtf16LE(const s: string): string;
var
P: PWord;
I, L: SizeUInt;
begin
if Length(S) = 0 then
begin
Result := '';
Exit;
end;
// Wide chars of UTF-16 <= bytes of UTF-8 string
SetLength(Result, Length(S) * SizeOf(WideChar));
if ConvertUTF8ToUTF16(PWideChar(PAnsiChar(Result)), Length(Result) + SizeOf(WideChar),
PAnsiChar(S), Length(S), [toInvalidCharToSymbol], L) <> trNoError
then
Result := ''
else
begin
SetLength(Result, (L - 1) * SizeOf(WideChar));
// Swap endian if needed
if (NtoLE($FFFE) <> $FFFE) then
begin
P := PWord(PAnsiChar(Result));
for I := 0 to L - 1 do
begin
P[I] := SwapEndian(P[I]);
end;
end;
end;
end;
function Utf8ToUtf16BE(const s: string): string;
var
P: PWord;
I, L: SizeUInt;
begin
if Length(S) = 0 then
begin
Result := '';
Exit;
end;
// Wide chars of UTF-16 <= bytes of UTF-8 string
SetLength(Result, Length(S) * SizeOf(WideChar));
if ConvertUTF8ToUTF16(PWideChar(PAnsiChar(Result)), Length(Result) + SizeOf(WideChar),
PAnsiChar(S), Length(S), [toInvalidCharToSymbol], L) <> trNoError
then
Result := ''
else
begin
SetLength(Result, (L - 1) * SizeOf(WideChar));
// Swap endian if needed
if (NtoBE($FEFF) <> $FEFF) then
begin
P := PWord(PAnsiChar(Result));
for I := 0 to L - 1 do
begin
P[I] := SwapEndian(P[I]);
end;
end;
end;
end;
function UTF8ToUCS4(const UTF8Text: String): UCS4String;
var
Len: PtrInt;
Index: Integer;
CharLen: Integer;
SrcPos: PAnsiChar;
begin
Len:= Length(UTF8Text);
SetLength(Result, Len);
if Len = 0 then Exit;
Index:= 0;
SrcPos:= PAnsiChar(UTF8Text);
while Len > 0 do begin
Result[Index]:= UTF8CharacterToUnicode(SrcPos, CharLen);
Inc(SrcPos, CharLen);
Dec(Len, CharLen);
Inc(Index);
end;
SetLength(Result, Index);
end;
function Utf8ReplaceBroken(const s: String): String;
var
Src, Dst, LastGoodPos: PByte;
BytesLeft: Integer;
InvalidCharLen: Integer;
CharLen: Integer;
begin
if Length(s) = 0 then
Exit(s);
BytesLeft := Length(s);
SetLength(Result, BytesLeft); // at most the same length
Src := PByte(s);
Dst := PByte(Result);
LastGoodPos := Src;
while BytesLeft > 0 do
begin
CharLen := SafeUTF8NextCharLen(Src, BytesLeft, InvalidCharLen);
if InvalidCharLen > 0 then
begin
if LastGoodPos < Src then
begin
System.Move(LastGoodPos^, Dst^, Src - LastGoodPos);
Inc(Dst, Src - LastGoodPos);
end;
Inc(Src, InvalidCharLen);
Dec(BytesLeft, InvalidCharLen);
LastGoodPos := Src;
Dst^ := ord('?');
Inc(Dst);
end
else
begin
Inc(Src, CharLen);
Dec(BytesLeft, CharLen);
end;
end;
if LastGoodPos = PByte(s) then
Result := s // All characters are good.
else
begin
if LastGoodPos < Src then
begin
System.Move(LastGoodPos^, Dst^, Src - LastGoodPos);
Inc(Dst, Src - LastGoodPos);
end;
SetLength(Result, Dst - PByte(Result));
end;
end;
end.
|