Delphi code of the day:


Delphi code of the day:

function UTF8ToString(const S: array of Byte): string; overload;
var
  Dest: array[0..511] of Char;
begin
  SetString(Result, Dest, UTF8ToUnicode(Dest, Length(Dest), _PAnsiChr(@S[1]), S[0])-1);
end;

Guess where it is: in System.pas ;)

And now some sample code to see the output:
procedure TForm1.FormCreate(Sender: TObject);
var
  xStr: string;
  xBuf: TBytes;
begin
  xStr := 'double';
  xBuf := TEncoding.UTF8.GetBytes(xStr);
  xStr := UTF8ToString(xBuf);

  Memo1.Lines.Text := xStr;
end;
Screenshot of the app is attached.

Disclaimer: For me it's hard to believe that such crap code is in the RTL. Didn't I miss something???

http://docwiki.embarcadero.com/Libraries/XE8/en/System.UTF8ToString

Comments

  1. I wouldn't say that the RTL is that bad...
    + Maybe both UTF8ToString overloads are correct but the documentation is wrong :)

    ReplyDelete
  2. Both issues were closed as test case errors in D10Seattle.

    ReplyDelete
  3. Yeah, reading outside the bounds of a buffer isn't a bug. Very sad...

    ReplyDelete

Post a Comment