Debian Codegraph @

plugins/wcx/zip/src/fparchive/abswstm.pas

raw
1 (* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1
3 *
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
8 *
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
12 * License.
13 *
14 * The Original Code is TurboPower Abbrevia
15 *
16 * The Initial Developer of the Original Code is
17 * TurboPower Software
18 *
19 * Portions created by the Initial Developer are Copyright (C) 1997-2002
20 * the Initial Developer. All Rights Reserved.
21 *
22 * Contributor(s):
23 *
24 * ***** END LICENSE BLOCK ***** *)
25
26 {*********************************************************}
27 {* ABBREVIA: AbSWStm.pas *}
28 {*********************************************************}
29 {* ABBREVIA: TabSlidingWindowStream class *}
30 {*********************************************************}
31
32 unit AbSWStm;
33
34 {$I AbDefine.inc}
35
36 {Notes: The TabSlidingWindowStream class provides a simple buffered
37 stream for sliding window compression/decompression routines.
38 The sliding window stream is limited when compared with a true
39 buffered stream:
40 - it is assumed that the underlying stream is just going to
41 be written to and is initially empty
42 - the buffer is fixed in size to 40KB
43 - write operations can only occur at the end of the stream
44 - the stream can only be positioned with a certain limited
45 range
46 - we can only read up to 32KB
47 - we can only write up to 32KB
48 The stream is written as a wrapper around another stream
49 (presumably a file stream) which is used for actual reads to
50 the buffer and writes from the buffer.
51 The stream buffer is organized as five 8KB chunks in an
52 array. The last chunk is the only one used for writing, the
53 other four are a 32KB buffer for reading. As the final chunk
54 gets filled, the class will drop off the first chunk (writing
55 it to the underlying stream, and shift the other chunks in the
56 array.}
57
58
59 {Define this if you wish to see a trace of the stream usage in a file
60 called C:\SlideWin.LOG}
61 {.$DEFINE DebugTrace}
62
63 interface
64
65 uses
66 SysUtils,
67 Classes;
68
69 const
70 abSWChunkCount = 5;
71
72 type
73 TabSlidingWindowStream = class(TStream)
74 protected {private}
75 bsChunks : array [0..pred(abSWChunkCount)] of PByteArray;
76 bsBufferStart : longint;
77 bsLastPos : integer;
78 bsCurChunk : integer;
79 bsPosInChunk : integer;
80 bsPosInBuffer : longint;
81 bsSize : Longint; {count of bytes in stream}
82 bsDirty : boolean; {whether the buffer is dirty or not}
83 bsStream : TStream; {actual stream containing data}
84 {$IFDEF DebugTrace}
85 bsF : System.Text;
86 {$ENDIF}
87 protected
88 procedure bsWriteChunk(aIndex : integer);
89 procedure bsSlide;
90
91 public
92 constructor Create(aStream : TStream);
93 {-create the buffered stream}
94 destructor Destroy; override;
95 {-destroy the buffered stream}
96
97 procedure Flush;
98 {-ensures that all dirty buffered data is flushed}
99 function Read(var Buffer; Count : Longint) : Longint; override;
100 {-read from the stream into a buffer}
101 function Seek(Offset : Longint; Origin : Word) : Longint; override;
102 {-seek to a particular point in the stream}
103 function Write(const Buffer; Count : Longint) : Longint; override;
104 {-write to the stream from a buffer}
105 end;
106
107 implementation
108
109 const
110 ChunkSize = 8192; {cannot be greater than MaxInt}
111
112
113 {===Helper routines==================================================}
114 procedure RaiseException(const S : string);
115 begin
116 raise Exception.Create(S);
117 end;
118 {====================================================================}
119
120
121 {===TabSlidingWindowStream===========================================}
122 constructor TabSlidingWindowStream.Create(aStream : TStream);
123 var
124 i : integer;
125 begin
126 inherited Create;
127 {save the actual stream}
128 bsStream := aStream;
129 {allocate the chunks-they must be set to binary zeros}
130 for i := 0 to pred(abSWChunkCount) do
131 bsChunks[i] := AllocMem(ChunkSize);
132 {set the page/buffer variables to the start of the stream; remember
133 we only write to the last chunk--the previous chunks are set to
134 binary zeros}
135 aStream.Position := 0;
136 bsSize := 0;
137 bsBufferStart := -ChunkSize * pred(abSWChunkCount);
138 bsPosInBuffer := ChunkSize * pred(abSWChunkCount);
139 bsCurChunk := pred(abSWChunkCount);
140 bsPosInChunk := 0;
141 bsDirty := false;
142 {$IFDEF DebugTrace}
143 System.Assign(bsF, 'c:\SlideWin.LOG');
144 if FileExists('c:\SlideWin.LOG') then
145 System.Append(bsF)
146 else
147 System.Rewrite(bsF);
148 writeln(bsF, '---NEW LOG---');
149 {$ENDIF}
150 end;
151 {--------}
152 destructor TabSlidingWindowStream.Destroy;
153 var
154 i : integer;
155 begin
156 {destroy the buffer, after writing it to the actual stream}
157 if bsDirty then
158 Flush;
159 for i := 0 to pred(abSWChunkCount) do
160 if (bsChunks[i] <> nil) then
161 FreeMem(bsChunks[i], ChunkSize);
162 {$IFDEF DebugTrace}
163 System.Close(bsF);
164 {$ENDIF}
165 {let our ancestor clean up}
166 inherited Destroy;
167 end;
168 {--------}
169 procedure TabSlidingWindowStream.bsSlide;
170 var
171 SavePtr : PByteArray;
172 i : integer;
173 begin
174 {write out the first chunk}
175 bsWriteChunk(0);
176 {slide the chunks around}
177 SavePtr := bsChunks[0];
178 for i := 0 to abSWChunkCount-2 do
179 bsChunks[i] := bsChunks[i+1];
180 bsChunks[pred(abSWChunkCount)] := SavePtr;
181 {advance the buffer start position}
182 inc(bsBufferStart, ChunkSize);
183 {reset the write position}
184 bsPosInChunk := 0;
185 bsPosInBuffer := ChunkSize * pred(abSWChunkCount);
186 bsLastPos := 0;
187 end;
188 {--------}
189 procedure TabSlidingWindowStream.bsWriteChunk(aIndex : integer);
190 var
191 SeekResult : longint;
192 BytesWrit : longint;
193 Offset : longint;
194 BytesToWrite : integer;
195 begin
196 Offset := bsBufferStart + (longint(aIndex) * ChunkSize);
197 if (Offset >= 0) then begin
198 SeekResult := bsStream.Seek(Offset, 0);
199 if (SeekResult = -1) then
200 RaiseException('TabSlidingWindowStream.bsWriteChunk: seek failed');
201 if (aIndex <> pred(abSWChunkCount)) then
202 BytesToWrite := ChunkSize
203 else
204 BytesToWrite := bsLastPos;
205 BytesWrit := bsStream.Write(bsChunks[aIndex]^, BytesToWrite);
206 if (BytesWrit <> BytesToWrite) then
207 RaiseException('TabSlidingWindowStream.bsWriteChunk: write failed');
208 end;
209 end;
210 {--------}
211 procedure TabSlidingWindowStream.Flush;
212 var
213 i : integer;
214 begin
215 if bsDirty then begin
216 for i := 0 to pred(abSWChunkCount) do
217 bsWriteChunk(i);
218 bsDirty := false;
219 end;
220 end;
221 {--------}
222 function TabSlidingWindowStream.Read(var Buffer; Count : Longint) : Longint;
223 var
224 BufPtr : PByte;
225 BytesToGo : Longint;
226 BytesToRead : integer;
227 begin
228 BufPtr := @Buffer;
229
230 {$IFDEF DebugTrace}
231 System.Writeln(bsF, 'Read: ', Count, ' bytes');
232 {$ENDIF}
233 {we do not support reads greater than 32KB bytes}
234 if (Count > 32*1024) then
235 Count := 32*1024;
236
237 {reading is complicated by the fact we can only read in chunks of
238 ChunkSize: we need to partition out the overall read into a
239 read from part of the chunk, zero or more reads from complete
240 chunks and then a possible read from part of a chunk}
241
242 {calculate the actual number of bytes we can read - this depends on
243 the current position and size of the stream as well as the number
244 of bytes requested}
245 BytesToGo := Count;
246 if (bsSize < (bsBufferStart + bsPosInBuffer + Count)) then
247 BytesToGo := bsSize - (bsBufferStart + bsPosInBuffer);
248 if (BytesToGo <= 0) then begin
249 Result := 0;
250 Exit;
251 end;
252 {remember to return the result of our calculation}
253 Result := BytesToGo;
254
255 {calculate the number of bytes we can read prior to the loop}
256 BytesToRead := ChunkSize - bsPosInChunk;
257 if (BytesToRead > BytesToGo) then
258 BytesToRead := BytesToGo;
259 {copy from the stream buffer to the caller's buffer}
260 if (BytesToRead = 1) then
261 BufPtr^ := bsChunks[bsCurChunk]^[bsPosInChunk]
262 else
263 Move(bsChunks[bsCurChunk]^[bsPosInChunk], BufPtr^, BytesToRead);
264 {calculate the number of bytes still to read}
265 dec(BytesToGo, BytesToRead);
266
267 {while we have bytes to read, read them}
268 while (BytesToGo > 0) do begin
269 {advance the pointer for the caller's buffer}
270 inc(BufPtr, BytesToRead);
271 {as we've exhausted this chunk, advance to the next}
272 inc(bsCurChunk);
273 bsPosInChunk := 0;
274 {calculate the number of bytes we can read in this cycle}
275 BytesToRead := ChunkSize;
276 if (BytesToRead > BytesToGo) then
277 BytesToRead := BytesToGo;
278 {copy from the stream buffer to the caller's buffer}
279 Move(bsChunks[bsCurChunk]^, BufPtr^, BytesToRead);
280 {calculate the number of bytes still to read}
281 dec(BytesToGo, BytesToRead);
282 end;
283 {remember our new position}
284 inc(bsPosInChunk, BytesToRead);
285 end;
286 {--------}
287 function TabSlidingWindowStream.Seek(Offset : Longint;
288 Origin : Word) : Longint;
289 {$IFDEF DebugTrace}
290 const
291 OriginStr : array [0..2] of string[7] = ('start', 'current', 'end');
292 {$ENDIF}
293 var
294 NewPos : Longint;
295 begin
296 {$IFDEF DebugTrace}
297 System.Writeln(bsF, 'Seek: ', Offset, ' bytes from ', OriginStr[Origin]);
298 {$ENDIF}
299 {calculate the new position}
300 case Origin of
301 soFromBeginning : NewPos := Offset;
302 soFromCurrent : NewPos := bsBufferStart + bsPosInBuffer + Offset;
303 soFromEnd : NewPos := bsSize + Offset;
304 else
305 NewPos := 0;
306 RaiseException('TabSlidingWindowStream.Seek: invalid origin');
307 end;
308 {if the new position is invalid, say so}
309 if (NewPos < bsBufferStart) or (NewPos > bsSize) then
310 RaiseException('TabSlidingWindowStream.Seek: invalid new position');
311 {calculate the chunk number and the position in buffer & chunk}
312 bsPosInBuffer := NewPos - bsBufferStart;
313 bsCurChunk := bsPosInBuffer div ChunkSize;
314 bsPosInChunk := bsPosInBuffer mod ChunkSize;
315 {return the new position}
316 Result := NewPos;
317 end;
318 {--------}
319 function TabSlidingWindowStream.Write(const Buffer; Count : Longint) : Longint;
320 var
321 BufPtr : PByte;
322 BytesToGo : Longint;
323 BytesToWrite: integer;
324 begin
325 BufPtr := @Buffer;
326
327 {$IFDEF DebugTrace}
328 System.Writeln(bsF, 'Write: ', Count, ' bytes');
329 {$ENDIF}
330 {we ONLY write at the end of the stream}
331 if ((bsBufferStart + bsPosInBuffer) <> bsSize) then
332 RaiseException('TabSlidingWindowStream.Write: Not at end of stream');
333
334 {we do not support writes greater than 32KB bytes}
335 if (Count > 32*1024) then
336 Count := 32*1024;
337
338 {writing is complicated by the fact we write in chunks of Chunksize
339 bytes: we need to partition out the overall write into a write
340 to part of the chunk, zero or more writes to complete chunks and
341 then a possible write to part of a chunk; every time we fill a
342 chunk we have toi slide the buffer}
343
344 {when we write to this stream we always assume that we can write the
345 requested number of bytes: if we can't (eg, the disk is full) we'll
346 get an exception somewhere eventually}
347 BytesToGo := Count;
348 {remember to return the result of our calculation}
349 Result := BytesToGo;
350
351 {calculate the number of bytes we can write prior to the loop}
352 BytesToWrite := ChunkSize - bsPosInChunk;
353 if (BytesToWrite > BytesToGo) then
354 BytesToWrite := BytesToGo;
355 {copy from the caller's buffer to the stream buffer}
356 if (BytesToWrite = 1) then
357 bsChunks[pred(abSWChunkCount)]^[bsPosInChunk] := BufPtr^
358 else
359 Move(BufPtr^,
360 bsChunks[pred(abSWChunkCount)]^[bsPosInChunk],
361 BytesToWrite);
362 {mark our buffer as requiring a save to the actual stream}
363 bsDirty := true;
364 {calculate the number of bytes still to write}
365 dec(BytesToGo, BytesToWrite);
366
367 {while we have bytes to write, write them}
368 while (BytesToGo > 0) do begin
369 {slide the buffer}
370 bsSlide;
371 {advance the pointer for the caller's buffer}
372 inc(BufPtr, BytesToWrite);
373 {calculate the number of bytes we can write in this cycle}
374 BytesToWrite := ChunkSize;
375 if (BytesToWrite > BytesToGo) then
376 BytesToWrite := BytesToGo;
377 {copy from the caller's buffer to our buffer}
378 Move(BufPtr^,
379 bsChunks[pred(abSWChunkCount)]^,
380 BytesToWrite);
381 {calculate the number of bytes still to write}
382 dec(BytesToGo, BytesToWrite);
383 end;
384 {remember our new position}
385 inc(bsPosInChunk, BytesToWrite);
386 bsPosInBuffer := (longint(ChunkSize) * pred(abSWChunkCount)) + bsPosInChunk;
387 bsLastPos := bsPosInChunk;
388 {make sure the stream size is correct}
389 inc(bsSize, Result);
390 {if we're at the end of the chunk, slide the buffer ready for next
391 time we write}
392 if (bsPosInChunk = ChunkSize) then
393 bsSlide;
394 end;
395 {====================================================================}
396
397 end.