| 1 |
// Licensed to the .NET Foundation under one or more agreements. |
| 2 |
// The .NET Foundation licenses this file to you under the MIT license. |
| 3 |
// See the LICENSE.txt file in the directory for more information. |
| 4 |
// The Pascal translation by Alexander Koblov. |
| 5 |
|
| 6 |
unit Inflate64Stream; |
| 7 |
|
| 8 |
{$mode ObjFPC}{$H+} |
| 9 |
|
| 10 |
interface |
| 11 |
|
| 12 |
uses |
| 13 |
Classes, SysUtils, InflaterManaged; |
| 14 |
|
| 15 |
type |
| 16 |
|
| 17 |
{ TInflate64Stream } |
| 18 |
|
| 19 |
TInflate64Stream = class(TOwnerStream) |
| 20 |
private |
| 21 |
_buffer: array[Word] of Byte; |
| 22 |
_inflater: TInflaterManaged; |
| 23 |
public |
| 24 |
constructor Create(ASource: TStream); |
| 25 |
destructor Destroy; override; |
| 26 |
function Read(var Buffer; Count: Longint): Longint; override; |
| 27 |
end; |
| 28 |
|
| 29 |
implementation |
| 30 |
|
| 31 |
{ TInflate64Stream } |
| 32 |
|
| 33 |
constructor TInflate64Stream.Create(ASource: TStream); |
| 34 |
begin |
| 35 |
inherited Create(ASource); |
| 36 |
_inflater:= TInflaterManaged.Create(True); |
| 37 |
end; |
| 38 |
|
| 39 |
destructor TInflate64Stream.Destroy; |
| 40 |
begin |
| 41 |
inherited Destroy; |
| 42 |
_inflater.Free; |
| 43 |
end; |
| 44 |
|
| 45 |
function TInflate64Stream.Read(var Buffer; Count: Longint): Longint; |
| 46 |
var |
| 47 |
bytesRead, bytes: Integer; |
| 48 |
currentOffset, remainingCount: Integer; |
| 49 |
begin |
| 50 |
currentOffset := 0; |
| 51 |
remainingCount := Count; |
| 52 |
|
| 53 |
while (true) do |
| 54 |
begin |
| 55 |
bytesRead := _inflater.Inflate(@Buffer, currentOffset, remainingCount); |
| 56 |
currentOffset += bytesRead; |
| 57 |
remainingCount -= bytesRead; |
| 58 |
|
| 59 |
if (remainingCount = 0) then |
| 60 |
begin |
| 61 |
break; |
| 62 |
end; |
| 63 |
|
| 64 |
if (_inflater.Finished()) then |
| 65 |
begin |
| 66 |
// if we finished decompressing, we can't have anything left in the outputwindow. |
| 67 |
Assert( |
| 68 |
_inflater.AvailableOutput = 0, |
| 69 |
'We should have copied all stuff out!' |
| 70 |
); |
| 71 |
break; |
| 72 |
end; |
| 73 |
|
| 74 |
bytes := FSource.Read(_buffer, Length(_buffer)); |
| 75 |
if (bytes <= 0) then |
| 76 |
begin |
| 77 |
break; |
| 78 |
end |
| 79 |
else if (bytes > Length(_buffer)) then |
| 80 |
begin |
| 81 |
// The stream is either malicious or poorly implemented and returned a number of |
| 82 |
// bytes larger than the buffer supplied to it. |
| 83 |
raise Exception.Create('Deflate64: invalid data'); |
| 84 |
end; |
| 85 |
|
| 86 |
_inflater.SetInput(_buffer, 0, bytes); |
| 87 |
end; |
| 88 |
|
| 89 |
Result := count - remainingCount; |
| 90 |
end; |
| 91 |
|
| 92 |
end. |
| 93 |
|