Search code examples
delphiqueuedelphi-xe2

How to manipulate Collections.TQueue order?


I have a queue in which I store packets to be transmitted:

TfrmFoo = class(TForm)
    public
        tx_queue: System.Generics.Collections.TObjectQueue<TPacket>;

Sometimes I need to queue a packet with the top-most priority. This is how I would do it:

for i := 0 to tx_queue.Count do
    // Shift all queue items one space up the queue.
    tx_queue.FItems[tx_queue.Count - i + 1] :=
        tx_queue.FItems[tx_queue.Count - i];
// Add a packet to the--now vacant--top-most position.
tx_queue.FItems[0] := VipPacket;

Unfortunately, FItems is private so I don't have access to it:

E2361 Cannot access private symbol {System.Generics.Collections}TQueue<Comm.TPacket>.FItems

How can I do what I described without rolling my own FIFO queue data structure, as I still want to be able to use all the features offered by the stdlib?

UPDATE: Having 2 queues is a solution, but there is another place in my code where I require access to the Queue items, e.g. where I print the queue:

DebugMsg('Contents of Tx-Queue:');
for i := 0 to (tx_queue.Count - 1) do
    DebugMsg(tx_queue.FItems[i]);

or a function that iterates over the queue and counts how many packets of a certain ID have been queued.


Solution

  • A queue isn't meant to be manipulated the way you want to manipulate your data structure. Use TList instead. Use Add to put things on the back, Insert to put something on the front, and ExtractItem(0) to fetch the first item.