Debian Codegraph @

plugins/wcx/zip/src/fparchive/abvmstrm.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: AbVMStrm.pas *}
28 {*********************************************************}
29 {* ABBREVIA: Virtual Memory Stream *}
30 {*********************************************************}
31
32 unit AbVMStrm;
33
34 {$I AbDefine.inc}
35
36 interface
37
38 uses
39 Classes;
40
41 const
42 AB_VMSPageSize = 4096; {must be a power of two}
43 AB_VMSMaxPages = 16384; {makes 64MB with the above value}
44
45 type
46 PvmsPage = ^TvmsPage;
47 TvmsPage = packed record
48 vpStmOfs : Int64; {value will be multiple of AB_VMSPageSize}
49 vpLRU : integer; {'time' page was last accessed}
50 vpDirty : Boolean; {has the page been changed?}
51 vpData : array [0..pred(AB_VMSPageSize)] of byte; {stream data}
52 end;
53
54 type
55 TAbVirtualMemoryStream = class(TStream)
56 protected {private}
57 vmsCachePage : PvmsPage; {the latest page used}
58 vmsLRU : Longint; {'tick' value}
59 vmsMaxMemToUse : Longword; {maximum memory to use for data}
60 vmsMaxPages : Integer; {maximum data pages}
61 vmsPageList : TList; {page array, sorted by offset}
62 vmsPosition : Int64; {position of stream}
63 vmsSize : Int64; {size of stream}
64 vmsSwapFileDir : string; {swap file directory}
65 vmsSwapFileName : string; {swap file name}
66 vmsSwapFileSize : Int64; {size of swap file}
67 vmsSwapHandle : System.THandle; {swap file handle}
68 protected
69 procedure vmsSetMaxMemToUse(aNewMem : Longword);
70
71 function vmsAlterPageList(aNewMem : Longword) : Longword;
72 procedure vmsFindOldestPage(out OldestInx : Longint;
73 out OldestPage: PvmsPage);
74 function vmsGetNextLRU : Longint;
75 function vmsGetPageForOffset(aOffset : Int64) : PvmsPage;
76
77 procedure vmsSwapFileCreate;
78 procedure vmsSwapFileDestroy;
79 procedure vmsSwapFileRead(aPage : PvmsPage);
80 procedure vmsSwapFileWrite(aPage : PvmsPage);
81 public
82 constructor Create;
83 {-create the virtual memory stream}
84 destructor Destroy; override;
85 {-destroy the virtual memory stream}
86
87 function Read(var Buffer; Count : Longint) : Longint; override;
88 {-read from the stream into a buffer}
89 function Write(const Buffer; Count : Longint) : Longint; override;
90 {-write to the stream from a buffer}
91 function Seek(const Offset : Int64; Origin : TSeekOrigin) : Int64; override;
92 {-seek to a particular point in the stream}
93
94 procedure SetSize(const NewSize : Int64); override;
95 {-set the stream size}
96
97 property MaxMemToUse : Longword
98 read vmsMaxMemToUse write vmsSetMaxMemToUse;
99 {-maximum memory to use for data before swapping to disk}
100 property SwapFileDirectory : string
101 read vmsSwapFileDir write vmsSwapFileDir;
102 end;
103
104 implementation
105
106 uses
107 {$IFDEF MSWINDOWS}
108 Windows, // Fix warning about unexpanded inline functions
109 {$ENDIF}
110 SysUtils,
111 AbExcept,
112 AbUtils,
113 DCOSUtils;
114
115 const
116 LastLRUValue = $7FFFFFFF;
117
118 {===TAbVirtualMemoryStream===========================================}
119 constructor TAbVirtualMemoryStream.Create;
120 var
121 Page : PvmsPage;
122 begin
123 inherited Create;
124 {create the page array}
125 vmsPageList := TList.Create;
126 {create the first page}
127 New(Page);
128 with Page^ do begin
129 vpStmOfs := 0;
130 vpLRU := vmsGetNextLRU;
131 vpDirty := False;
132 FillChar(vpData, AB_VMSPageSize, 0);
133 end;
134 vmsPageList.Insert(0, pointer(Page));
135 {prime the cache, from now on the cache will never be nil}
136 vmsCachePage := Page;
137 {default to using all allowed pages}
138 MaxMemToUse := AB_VMSMaxPages * AB_VMSPageSize;
139 end;
140 {--------}
141 destructor TAbVirtualMemoryStream.Destroy;
142 var
143 Inx : integer;
144 begin
145 {destroy the swap file}
146 vmsSwapFileDestroy;
147 {throw away all pages in the list}
148 if (vmsPageList <> nil) then begin
149 for Inx := 0 to pred(vmsPageList.Count) do
150 Dispose(PvmsPage(vmsPageList[Inx]));
151 vmsPageList.Destroy;
152 end;
153 {let our ancestor clean up}
154 inherited Destroy;
155 end;
156 {--------}
157 function TAbVirtualMemoryStream.Read(var Buffer; Count : Longint) : Longint;
158 var
159 BufPtr : PByte;
160 Page : PvmsPage;
161 PageDataInx : integer;
162 Posn : int64;
163 BytesToGo : int64;
164 BytesToRead : int64;
165 StartOfs : int64;
166 begin
167 {reading is complicated by the fact we can only read in chunks of
168 AB_VMSPageSize: we need to partition out the overall read into a read
169 from a partial page, zero or more reads from complete pages and
170 then a possible read from a partial page}
171
172 {initialise some variables, note that the complex calc in the
173 expression for PageDataInx is the offset of the start of the page
174 where Posn is found.}
175 BufPtr := @Buffer;
176 Posn := vmsPosition;
177 PageDataInx := Posn - (Posn and (not pred(AB_VMSPageSize)));
178 BytesToRead := AB_VMSPageSize - PageDataInx;
179 {calculate the actual number of bytes to read - this depends on the
180 current position and size of the stream}
181 BytesToGo := Count;
182 if (vmsSize < (vmsPosition + Count)) then
183 BytesToGo := vmsSize - vmsPosition;
184 if (BytesToGo < 0) then
185 BytesToGo := 0;
186 Result := BytesToGo;
187
188 {while we have bytes to read, read them}
189 while (BytesToGo <> 0) do begin
190 if (BytesToRead > BytesToGo) then
191 BytesToRead := BytesToGo;
192 StartOfs := Posn and (not pred(AB_VMSPageSize));
193 if (vmsCachePage^.vpStmOfs = StartOfs) then
194 Page := vmsCachePage
195 else
196 Page := vmsGetPageForOffset(StartOfs);
197 Move(Page^.vpData[PageDataInx], BufPtr^, BytesToRead);
198 dec(BytesToGo, BytesToRead);
199 inc(Posn, BytesToRead);
200 inc(BufPtr, BytesToRead);
201 PageDataInx := 0;
202 BytesToRead := AB_VMSPageSize;
203 end;
204 {remember our new position}
205 vmsPosition := Posn;
206 end;
207 {--------}
208 function TAbVirtualMemoryStream.Seek(const Offset : Int64;
209 Origin : TSeekOrigin) : Int64;
210 begin
211 case Origin of
212 soBeginning : vmsPosition := Offset;
213 soCurrent : inc(vmsPosition, Offset);
214 soEnd : vmsPosition := vmsSize + Offset;
215 else
216 raise EAbVMSInvalidOrigin.Create( Integer(Origin));
217 end;
218 Result := vmsPosition;
219 end;
220 {--------}
221 procedure TAbVirtualMemoryStream.SetSize(const NewSize : Int64);
222 var
223 Page : PvmsPage;
224 Inx : integer;
225 NewFileSize : Int64;
226 begin
227 if (NewSize < vmsSize) then begin
228 {go through the page list discarding pages whose offset is greater
229 than our new size; don't bother saving any data from them since
230 it be beyond the end of the stream anyway}
231 {never delete the last page here}
232 for Inx := pred(vmsPageList.Count) downto 1 do begin
233 Page := PvmsPage(vmsPageList[Inx]);
234 if (Page^.vpStmOfs >= NewSize) then begin
235 Dispose(Page);
236 vmsPageList.Delete(Inx);
237 end else begin
238 Break;
239 end;
240 end;
241
242 { Reset cache to the first page in case the cached page was deleted. }
243 vmsCachePage := vmsPageList[0];
244
245 {force the swap file file size in range, it'll be a multiple of
246 AB_VMSPageSize}
247 NewFileSize := pred(NewSize + AB_VMSPageSize) and
248 (not pred(AB_VMSPageSize));
249 if (NewFileSize < vmsSwapFileSize) then
250 vmsSwapFileSize := NewFileSize;
251 {ignore the swap file itself}
252 end;
253 vmsSize := NewSize;
254 if (vmsPosition > NewSize) then
255 vmsPosition := NewSize;
256 end;
257 {--------}
258 function TAbVirtualMemoryStream.vmsAlterPageList(aNewMem : Longword) : Longword;
259 var
260 NumPages : Longint;
261 Page : PvmsPage;
262 i : integer;
263 OldestPageNum : Longint;
264 begin
265 {calculate the max number of pages required}
266 if aNewMem = 0 then
267 NumPages := 1 // always have at least one page
268 else
269 NumPages := pred(aNewMem + AB_VMSPageSize) div AB_VMSPageSize;
270 if (NumPages > AB_VMSMaxPages) then
271 NumPages := AB_VMSMaxPages;
272 {if the maximum number of pages means we have to shrink the current
273 list, do so, tossing out the oldest pages first}
274 if (NumPages < vmsPageList.Count) then
275 begin
276 for i := 1 to (vmsPageList.Count - NumPages) do begin
277 {find the oldest page}
278 vmsFindOldestPage(OldestPageNum, Page);
279 {if it is dirty, write it out to the swap file}
280 if Page^.vpDirty then begin
281 vmsSwapFileWrite(Page);
282 end;
283 {remove it from the page list}
284 vmsPageList.Delete(OldestPageNum);
285 {free the page memory}
286 Dispose(Page);
287 end;
288
289 { Reset cache to the first page in case the cached page was deleted. }
290 vmsCachePage := vmsPageList[0];
291 end;
292 {remember our new max number of pages}
293 vmsMaxPages := NumPages;
294 Result := NumPages * AB_VMSPageSize;
295 end;
296 {--------}
297 procedure TAbVirtualMemoryStream.vmsFindOldestPage(out OldestInx : Longint;
298 out OldestPage: PvmsPage);
299 var
300 OldestLRU : Longint;
301 Inx : integer;
302 Page : PvmsPage;
303 begin
304 OldestInx := -1;
305 OldestLRU := LastLRUValue;
306 for Inx := 0 to pred(vmsPageList.Count) do begin
307 Page := PvmsPage(vmsPageList[Inx]);
308 if (Page^.vpLRU < OldestLRU) then begin
309 OldestInx := Inx;
310 OldestLRU := Page^.vpLRU;
311 OldestPage := Page;
312 end;
313 end;
314 end;
315 {--------}
316 function TAbVirtualMemoryStream.vmsGetNextLRU : Longint;
317 var
318 Inx : integer;
319 begin
320 if (vmsLRU = LastLRUValue) then begin
321 {reset all LRUs in list}
322 for Inx := 0 to pred(vmsPageList.Count) do
323 PvmsPage(vmsPageList[Inx])^.vpLRU := 0;
324 vmsLRU := 0;
325 end;
326 inc(vmsLRU);
327 Result := vmsLRU;
328 end;
329 {--------}
330 function TAbVirtualMemoryStream.vmsGetPageForOffset(aOffset : Int64) : PvmsPage;
331 var
332 Page : PvmsPage;
333 PageOfs : Int64;
334 L, M, R : integer;
335 OldestPageNum : integer;
336 CreatedNewPage: boolean;
337 begin
338 {using a sequential or a binary search (depending on the number of
339 pages), try to find the page in the cache; we'll do a sequential
340 search if the number of pages is very small, eg less than 4}
341 if (vmsPageList.Count < 4) then begin
342 L := vmsPageList.Count;
343 for M := 0 to pred(vmsPageList.Count) do begin
344 Page := PvmsPage(vmsPageList[M]);
345 PageOfs := Page^.vpStmOfs;
346 if (aOffset < PageOfs) then begin
347 L := M;
348 Break;
349 end;
350 if (aOffset = PageOfs) then begin
351 Page^.vpLRU := vmsGetNextLRU;
352 vmsCachePage := Page;
353 Result := Page;
354 Exit;
355 end;
356 end;
357 end
358 else {we need to do a binary search} begin
359 L := 0;
360 R := pred(vmsPageList.Count);
361 repeat
362 M := (L + R) div 2;
363 Page := PvmsPage(vmsPageList[M]);
364 PageOfs := Page^.vpStmOfs;
365 if (aOffset < PageOfs) then
366 R := pred(M)
367 else if (aOffset > PageOfs) then
368 L := succ(M)
369 else {aOffset = PageOfs} begin
370 Page^.vpLRU := vmsGetNextLRU;
371 vmsCachePage := Page;
372 Result := Page;
373 Exit;
374 end;
375 until (L > R);
376 end;
377 {if we get here the page for the offset is not present in the page
378 list, and once created/loaded, the page should be inserted at L}
379
380 {enter a try..except block so that if a new page is created and an
381 exception occurs, the page is freed}
382 CreatedNewPage := false;
383 Result := nil;
384 try
385 {if there is room to insert a new page, create one ready}
386 if (vmsPageList.Count < vmsMaxPages) then begin
387 New(Page);
388 CreatedNewPage := true;
389 end
390 {otherwise there is no room for the insertion, so find the oldest
391 page in the list and discard it}
392 else {vmsMaxPages <= vmsPageList.Count} begin
393 {find the oldest page}
394 vmsFindOldestPage(OldestPageNum, Page);
395 {if it is dirty, write it out to the swap file}
396 if Page^.vpDirty then begin
397 vmsSwapFileWrite(Page);
398 end;
399 {remove it from the page list}
400 vmsPageList.Delete(OldestPageNum);
401 {patch up the insertion point, in case the page just deleted was
402 before it}
403 if (OldestPageNum < L) then
404 dec(L);
405 end;
406 {set all the page fields}
407 with Page^ do begin
408 vpStmOfs := aOffset;
409 vpLRU := vmsGetNextLRU;
410 vpDirty := False;
411 vmsSwapFileRead(Page);
412 end;
413 {insert the page into the correct spot}
414 vmsPageList.Insert(L, pointer(Page));
415 {return the page, remembering to save it in the cache}
416 vmsCachePage := Page;
417 Result := Page;
418 except
419 if CreatedNewPage then
420 Dispose(Page);
421 raise;
422 end;{try..except}
423 end;
424 {--------}
425 procedure TAbVirtualMemoryStream.vmsSetMaxMemToUse(aNewMem : Longword);
426 begin
427 vmsMaxMemToUse := vmsAlterPageList(aNewMem);
428 end;
429 {--------}
430 procedure TAbVirtualMemoryStream.vmsSwapFileCreate;
431 begin
432 if (vmsSwapHandle = 0) then begin
433 vmsSwapFileName := AbCreateTempFile(vmsSwapFileDir);
434 vmsSwapHandle := mbFileOpen(vmsSwapFileName, fmOpenReadWrite);
435 if (vmsSwapHandle <= 0) then begin
436 vmsSwapHandle := 0;
437 mbDeleteFile(vmsSwapFileName);
438 raise EAbVMSErrorOpenSwap.Create( vmsSwapFileName );
439 end;
440 vmsSwapFileSize := 0;
441 end;
442 end;
443 {--------}
444 procedure TAbVirtualMemoryStream.vmsSwapFileDestroy;
445 begin
446 if (vmsSwapHandle <> 0) then begin
447 FileClose(vmsSwapHandle);
448 mbDeleteFile(vmsSwapFileName);
449 vmsSwapHandle := 0;
450 end;
451 end;
452 {--------}
453 procedure TAbVirtualMemoryStream.vmsSwapFileRead(aPage : PvmsPage);
454 var
455 BytesRead : Longint;
456 SeekResult: Int64;
457 begin
458 if (vmsSwapHandle = 0) or (aPage^.vpStmOfs >= vmsSwapFileSize) then begin
459 {there is nothing to be read from the disk (either the swap file
460 doesn't exist or it's too small) so zero out the page data}
461 FillChar(aPage^.vpData, AB_VMSPageSize, 0)
462 end
463 else {there is something to be read from the swap file} begin
464 SeekResult := FileSeek(vmsSwapHandle, aPage^.vpStmOfs, 0);
465 if (SeekResult = -1) then
466 raise EAbVMSSeekFail.Create( vmsSwapFileName );
467 BytesRead := FileRead(vmsSwapHandle, aPage^.vpData, AB_VMSPageSize);
468 if (BytesRead <> AB_VMSPageSize) then
469 raise EAbVMSReadFail.Create( AB_VMSPageSize, vmsSwapFileName );
470 end;
471 end;
472 {--------}
473 procedure TAbVirtualMemoryStream.vmsSwapFileWrite(aPage : PvmsPage);
474 var
475 NewPos : Int64;
476 SeekResult: Int64;
477 BytesWritten : Longint;
478 begin
479 if (vmsSwapHandle = 0) then
480 vmsSwapFileCreate;
481 SeekResult := FileSeek(vmsSwapHandle, aPage^.vpStmOfs, 0);
482 if (SeekResult = -1) then
483 raise EAbVMSSeekFail.Create( vmsSwapFileName );
484 BytesWritten := FileWrite(vmsSwapHandle, aPage^.vpData, AB_VMSPageSize);
485 if BytesWritten <> AB_VMSPageSize then
486 raise EAbVMSWriteFail.Create( AB_VMSPageSize, vmsSwapFileName );
487 NewPos := aPage^.vpStmOfs + AB_VMSPageSize;
488 if (NewPos > vmsSwapFileSize) then
489 vmsSwapFileSize := NewPos;
490 end;
491 {--------}
492 function TAbVirtualMemoryStream.Write(const Buffer; Count : Longint) : Longint;
493 var
494 BufPtr : PByte;
495 Page : PvmsPage;
496 PageDataInx : integer;
497 Posn : Int64;
498 BytesToGo : Int64;
499 BytesToWrite: Int64;
500 StartOfs : Int64;
501 begin
502 {writing is complicated by the fact we can only write in chunks of
503 AB_VMSPageSize: we need to partition out the overall write into a
504 write to a partial page, zero or more writes to complete pages and
505 then a possible write to a partial page}
506
507 {initialise some variables, note that the complex calc in the
508 expression for PageDataInx is the offset of the start of the page
509 where Posn is found.}
510 BufPtr := @Buffer;
511 Posn := vmsPosition;
512 PageDataInx := Posn - (Posn and (not pred(AB_VMSPageSize)));
513 BytesToWrite := AB_VMSPageSize - PageDataInx;
514 {calculate the actual number of bytes to write}
515 BytesToGo := Count;
516 Result := BytesToGo;
517
518 {while we have bytes to write, write them}
519 while (BytesToGo <> 0) do begin
520 if (BytesToWrite > BytesToGo) then
521 BytesToWrite := BytesToGo;
522 StartOfs := Posn and (not pred(AB_VMSPageSize));
523 if (vmsCachePage^.vpStmOfs = StartOfs) then
524 Page := vmsCachePage
525 else
526 Page := vmsGetPageForOffset(StartOfs);
527 Move(BufPtr^, Page^.vpData[PageDataInx], BytesToWrite);
528 Page^.vpDirty := True;
529 dec(BytesToGo, BytesToWrite);
530 inc(Posn, BytesToWrite);
531 inc(BufPtr, BytesToWrite);
532 PageDataInx := 0;
533 BytesToWrite := AB_VMSPageSize;
534 end;
535 {remember our new position}
536 vmsPosition := Posn;
537 {if we've grown the stream, make a note of it}
538 if (vmsPosition > vmsSize) then
539 vmsSize := vmsPosition;
540 end;
541 {====================================================================}
542
543 end.