unit ddumper;

{$MODE FPC}
{$MODESWITCH RESULT}

interface

uses
  dtypes,
  dstrnum;

function Dump4BytesToStr(P: Pointer): TString;
function DumpLineToStr(P: PByte; Size: LongInt): TString;
function DumpToStr(P: Pointer; Size: LongInt): TString;
procedure Dump(P: Pointer; Size: LongInt); overload;

implementation

function Dump4BytesToStr(P: Pointer): TString;
begin
  Result := UintToHex(Cardinal(P^));
end;

function DumpLineToStr(P: PByte; Size: LongInt): TString;
var
  I: LongInt;
begin
  Result := '';
  for I := 0 to 15 do begin
    if Size > I then begin
      Result := Result + IntToHex(P[I], 2);
    end else
      Result := Result + '  ';
    if I mod 4 = 3 then
      Result := Result + '  ';
  end;
  Result := Result + '| ';
  for I := 0 to 15 do begin
    if Size <= I then
      break;
    if (P[I] >= 32) and (P[I] <= 127) then begin
      Result := Result + Char(P[I])
    end else
      Result := Result + '.';
  end;
end;

function DumpToStr(P: Pointer; Size: LongInt): TString;
begin
  Result := '';
  while Size > 0 do begin
    if Size >= 16 then begin
      Result := Result + DumpLineToStr(P, 16) + #10;
      Size := Size - 16;
      Inc(P, 16);
    end else begin
      Result := Result + DumpLineToStr(P, Size) + #10;
      Break;
    end;
  end;
end;

procedure Dump(P: Pointer; Size: LongInt);
begin
  Write(DumpToStr(P, Size));
end;

end.
