from__future__importannotationsfromtypingimportTYPE_CHECKING,Generic,no_type_checkfromtyping_extensionsimportSelffromguppylang.decoratorimportguppyfromguppylang.std.arrayimportarrayfromguppylang.std.optionimportOption,nothing,somefromguppylang.std.platformimportpanicifTYPE_CHECKING:fromguppylang.std.langimportownedT=guppy.type_var("T",copyable=False,droppable=False)TCopyable=guppy.type_var("TCopyable",copyable=True,droppable=False)MAX_SIZE=guppy.nat_var("MAX_SIZE")@guppy.structclassQueue(Generic[T,MAX_SIZE]):# type: ignore[misc]"""A first-in-first-out (FIFO) growable collection of values. To ensure static allocation, the maximum queue size must be specified in advance and is tracked in the type. For example, `Queue[int, 10]` is a queue that can hold at most 10 integers. Implemented as a circular buffer, giving O(1) push and pop. Use `empty_queue` to construct a new queue. """#: Underlying circular buffer holding the queue elements.#:#: Elements are stored contiguously from `self._start` up to and#: including `self._end`, wrapping around modulo MAX_SIZE.#:#: The `self._size` field tracks the number of elements currently#: in the queue, so we can distinguish between full and empty states.#: Without this, then the queue would be limited to MAX_SIZE - 1 since#: we cannot distinguish completely full and completely empty states#: with just using `self._start` and `self._end`._buf:array[Option[T],MAX_SIZE]# type: ignore[valid-type, type-arg]#: Index of the current front of the queue (first element to be popped)._start:int#: Index of the next free slot in `self._buf`._end:int#: Number of elements currently stored in the queue._size:int@guppy@no_type_checkdef__len__(self)->int:"""Returns the number of elements currently stored in the queue."""returnself._size@guppy@no_type_checkdef__iter__(self:Self@owned)->Self:"""Returns an iterator over the elements in the queue from bottom to top."""returnself@guppy@no_type_checkdef__next__(self:Self@owned)->Option[tuple[T,Self]]:iflen(self)==0:self.discard_empty()returnnothing()val=self.pop()returnsome((val,self))@guppy@no_type_checkdefpush(self,elem:T@owned)->None:"""Adds an element to the end of the queue. Panics if the queue has already reached its maximum size. """ifself._size>=MAX_SIZE:panic("Queue.push: max size reached")self._buf[self._end].swap(some(elem)).unwrap_nothing()self._end=(self._end+1)%MAX_SIZEself._size+=1@guppy@no_type_checkdefpop(self)->T:""" Removes the next element from the queue and returns it. Panics if the queue is empty. """ifself._size==0:panic("Queue.pop: queue is empty")elem=self._buf[self._start].take().unwrap()self._start=(self._start+1)%MAX_SIZEself._size-=1returnelem@guppy@no_type_checkdefpeek(self:Queue[TCopyable,MAX_SIZE]@owned)->TCopyable:"""Returns a copy of the top element of the queue without removing it. Panics if the queue is empty. Note that this operation is only allowed if the queue elements are copyable. """ifself._size==0:panic("Queue.peek: queue is empty")elem=self._buf[self._start].unwrap()returnelem@guppy@no_type_checkdefdiscard_empty(self:Queue[T,MAX_SIZE]@owned)->None:"""Discards a queue of potentially non-droppable elements assuming that the queue is empty. Panics if the queue is not empty. """ifself._size!=0:panic("Queue.discard_empty: queue is not empty")foreleminself._buf:elem.unwrap_nothing()
[docs]@guppy@no_type_checkdefempty_queue()->Queue[T,MAX_SIZE]:"""Constructs a new empty queue."""buf=array(nothing[T]()for_inrange(MAX_SIZE))returnQueue(buf,0,0,0)