@@ -14,8 +14,8 @@ interface
14
14
simba.base, simba.encoding;
15
15
16
16
// TByteArray
17
- function CompressBytes (Data: TByteArray): TByteArray;
18
- function DecompressBytes (Data: TByteArray): TByteArray;
17
+ function CompressBytes (const Data: TByteArray): TByteArray;
18
+ function DecompressBytes (const Data: TByteArray): TByteArray;
19
19
20
20
// String
21
21
function CompressString (S: String; Encoding: EBaseEncoding = EBaseEncoding.b64): String;
@@ -26,47 +26,56 @@ implementation
26
26
uses
27
27
basenenc_simba, ZStream;
28
28
29
- function CompressBytes (Data: TByteArray): TByteArray;
29
+ function CompressBytes (const Data: TByteArray): TByteArray;
30
30
var
31
- InStream: Tcompressionstream ;
32
- OutStream: TBytesStream ;
31
+ InStream: TCompressionstream ;
32
+ OutStream: TMemoryStream ;
33
33
begin
34
- OutStream := TBytesStream.Create();
34
+ Result := [];
35
+
36
+ OutStream := TMemoryStream.Create();
35
37
InStream := TCompressionStream.Create(clDefault, OutStream);
36
38
try
37
39
InStream.Write(Data[0 ], Length(Data));
38
40
InStream.Flush();
39
41
40
- Result := OutStream.Bytes;
41
- SetLength(Result, OutStream.Size);
42
+ SetLength(Result, OutStream.Position);
43
+ if (Length(Result) > 0 ) then
44
+ Move(OutStream.Memory^, Result[0 ], Length(Result));
42
45
finally
43
46
InStream.Free();
44
47
OutStream.Free();
45
48
end ;
46
49
end ;
47
50
48
- function DecompressBytes (Data: TByteArray): TByteArray;
51
+ function DecompressBytes (const Data: TByteArray): TByteArray;
49
52
var
50
53
InStream: TBytesStream;
51
54
OutStream: Tdecompressionstream;
52
- Count, Len: Integer;
55
+ ReadCount, TotalCount: Integer;
56
+ Chunk: array [0 ..2048 -1 ] of Byte;
53
57
begin
54
- SetLength(Result, 4096 );
55
- Len := 0 ;
58
+ TotalCount := 0 ;
56
59
57
60
InStream := TBytesStream.Create(Data);
58
61
OutStream := TDeCompressionStream.Create(InStream);
59
62
try
60
63
repeat
61
- Count := OutStream.Read(Result[Len], Length(Result) - Len);
62
- Len := Len + Count;
63
- until (Count = 0 );
64
+ ReadCount := OutStream.Read(Chunk[0 ], Length(Chunk));
65
+ if (ReadCount > 0 ) then
66
+ begin
67
+ if (TotalCount + ReadCount > High(Result)) then
68
+ SetLength(Result, 4 + (High(Result) * 2 ) + ReadCount);
69
+ Move(Chunk[0 ], Result[TotalCount], ReadCount);
70
+ Inc(TotalCount, ReadCount);
71
+ end ;
72
+ until (ReadCount = 0 );
64
73
finally
65
74
InStream.Free();
66
75
OutStream.Free();
67
76
end ;
68
77
69
- SetLength(Result, Len );
78
+ SetLength(Result, TotalCount );
70
79
end ;
71
80
72
81
function CompressString (S: String; Encoding: EBaseEncoding): String;
0 commit comments