unit JavaString;
interface
function JavaString_Decode(
const AStr:
string ):
string;
implementation
uses
System.SysUtils;
function OctalStrToInt( AOctal:
string ): Integer;
var
LChar: Char;
begin
Result := 0;
for LChar
in AOctal
do
begin
Result := Result * 8 + Ord( LChar ) - Ord( '
0' );
end;
end;
function JavaString_Decode(
const AStr:
string ):
string;
var
LTempBuffer:
string;
LChar: Char;
LState: Integer;
procedure Normal;
begin
case LChar
of
'
\':
LState := 1;
else
Result := Result + LChar;
end;
end;
procedure Escape;
begin
case LChar
of
'
\', '
/', '
"', '
''
':
;
'
b':
// Backspace
LChar := #$0008;
'
t':
// Horizontal Tab
LChar := #$0009;
'
n':
// New Line
LChar := #$000A;
'
v':
// Vertical Tab
LChar := #$000B;
'
f':
// Form Feed
LChar := #$000C;
'
r':
// Carriage Return
LChar := #$000D;
'
0' .. '
3':
// Latin1 Octal
begin
LTempBuffer := LChar;
LState := 2;
Exit;
end;
'
x':
// Latin1 Hex
begin
LTempBuffer := '
';
LState := 3;
Exit;
end;
'
u':
// Unicode Hex
begin
LTempBuffer := '
';
LState := 4;
Exit;
end;
else
raise EArgumentException.Create( '
Parse Error' );
end;
Result := Result + LChar;
LState := 0;
end;
procedure Latin1Octal;
var
LByte: Byte;
begin
case LChar
of
'
0' .. '
7':
LTempBuffer := LTempBuffer + LChar;
else
raise EArgumentException.Create( '
Parse Error' );
end;
if Length( LTempBuffer ) = 3
then
begin
LByte := OctalStrToInt( LTempBuffer );
Result := Result + TEncoding.
Default.GetString( TArray<Byte>.Create( LByte ) );
LState := 0;
end;
end;
procedure Latin1Hex;
var
LByte: Byte;
begin
case LChar
of
'
0' .. '
9', '
A' .. '
F', '
a' .. '
f':
LTempBuffer := LTempBuffer + LChar;
else
raise EArgumentException.Create( '
Parse Error' );
end;
if Length( LTempBuffer ) = 2
then
begin
LByte := StrToInt( '
$' + LTempBuffer );
Result := Result + TEncoding.
Default.GetString( TArray<Byte>.Create( LByte ) );
LState := 0;
end;
end;
procedure UnicodeHex;
var
LWord: Word;
begin
case LChar
of
'
0' .. '
9', '
A' .. '
F', '
a' .. '
f':
LTempBuffer := LTempBuffer + LChar;
else
raise EArgumentException.Create( '
Parse Error' );
end;
if Length( LTempBuffer ) = 4
then
begin
LWord := StrToInt( '
$' + LTempBuffer );
Result := Result + TEncoding.Unicode.GetString( TArray<Byte>.Create( Lo( LWord ), Hi( LWord ) ) );
LState := 0;
end;
end;
begin
Result := '
';
LState := 0;
for LChar
in AStr
do
case LState
of
0:
Normal;
1:
Escape;
2:
Latin1Octal;
3:
Latin1Hex;
4:
UnicodeHex;
end;
if LState <> 0
then
raise EArgumentException.Create( '
Parse Error' );
end;
end.