DELPHI写的循环队列

unit cirstream;

interface

uses Windows, Classes, SysUtils;

type
TCircleMemStream = Class(TObject)
private
FMemory: PChar;
FCapacity: integer;
ReadPosition: integer;
WritePosition: integer;
public
constructor Create(BufferSize: integer);
destructor Destroy; override;
// function NextPosition();
function Read(Buffer: PChar; Count: Longint): Longint;
function Write(Buffer: PChar; Count: Longint): Longint;
function DataSize(): integer;
end;

implementation

constructor TCircleMemStream.Create(BufferSize: integer);
begin
FCapacity := 1;
while BufferSize <> 1 do
begin
FCapacity := FCapacity shl 1;
BufferSize := BufferSize shr 1;
end;
GetMem(FMemory, FCapacity);
ReadPosition := 0;
WritePosition := 0;
end;

destructor TCircleMemStream.Destroy;
begin
FreeMem(FMemory);
end;

function TCircleMemStream.Read(Buffer: PChar; Count: Longint): Longint;
var
Mask: integer;
roff: integer;
readsize: integer;
begin
Mask := FCapacity - 1;
Result := 0;
roff := 0;


while (ReadPosition <> WritePosition) and (Count > 0) do
begin
if WritePosition > ReadPosition then
readsize := WritePosition - ReadPosition
else
readsize := FCapacity - ReadPosition;
if readsize > Count then
readsize := Count;
MoveMemory(@Buffer[roff], @FMemory[ReadPosition], readsize);
Dec(Count, readsize);
Inc(roff, readsize);
Inc(Result, readsize);
ReadPosition := (ReadPosition + readsize) and Mask;


end;
end;

function TCircleMemStream.Write(Buffer: PChar; Count: Longint): Longint;
var
Mask: integer;
writesize: integer;
woff: integer;
begin
Mask := FCapacity - 1;
Result := 0;
woff := 0;

writesize := (ReadPosition - WritePosition - 1) and Mask; //允许写入的大小
while (writesize > 0) and (Count > 0) do
begin
if ReadPosition <= WritePosition then
begin
writesize := FCapacity - WritePosition;
if ReadPosition = 0 then
Dec(writesize, 1);
end;
if writesize > Count then
writesize := Count;
MoveMemory(@FMemory[WritePosition], @Buffer[woff], writesize);
Dec(Count, writesize);
Inc(woff, writesize);
Inc(Result, writesize);
WritePosition := WritePosition + writesize and Mask;

writesize := (ReadPosition - WritePosition - 1) and Mask; //允许写入的大小
end;

end;

function TCircleMemStream.DataSize(): integer;
var
Mask: integer;
begin
Mask := FCapacity - 1;
Result := (WritePosition - ReadPosition) and Mask;
end;

end.

你可能感兴趣的:(delphi类)