How do you design FIFO queue with variable data size?

前端 未结 3 1140
借酒劲吻你
借酒劲吻你 2020-12-18 12:48

I\'m just working on the FIFO queue (the simple one, just what\'s pushed first, pops at first) with the variable data size but I\'m not sure with the way I\'m designing it.

3条回答
  •  执念已碎
    2020-12-18 13:17

    I would use memory streams and a TObjectQueue (as Uwe suggested).

    type
      TListQueue = class
      private
        FList: TObjectQueue;
      public
        constructor Create;
        destructor Destroy; override;
        procedure Push(const Value; const Size: Integer);
        procedure Pop(var Value; var Size: Integer);
      end;
    
    implementation
    
    constructor TListQueue.Create;
    begin
      inherited;
      FList := TObjectQueue.Create;
    end;
    
    destructor TListQueue.Destroy;
    begin
      while FList.Count > 0 do
        TMemoryStream(FList.Pop).Free;
      FreeAndNil(FList);
      inherited;
    end;
    
    procedure TListQueue.Push(const Value; const Size: Integer);
    var
      LStream: TMemoryStream;
    begin
      LStream := TMemoryStream.Create;
      LStream.Write(Value, Size);
      FList.Push(LStream);
    end;
    
    procedure TListQueue.Pop(var Value; var Size: Integer);
    var
      LStream: TMemoryStream;
    begin
      if FList.Count > 0 then
      begin
        LStream := TMemoryStream(FList.Pop);
        Size := LStream.Size;
        LStream.Position := 0;
        LStream.Read(Value, Size);
        LStream.Free;
      end;
    end;
    

提交回复
热议问题