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.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值