Livt packages

Livt.Collections

Version 1.4.2

Fixed-capacity FIFOs, queues, stacks, circular buffers, lists, and bit sets for Livt hardware.

Published files (62)

src/stack/Stack.lvt

namespace Livt.Collections.Stack

/**
 * Fixed-capacity LIFO storage selected by element type and compile-time capacity.
 * Writes while full are ignored. Empty reads return the element type's zero value.
 */
component Stack<T, CAPACITY: int = 64> : IStack<T>
{
	static assert CAPACITY > 0, "Stack capacity must be positive"

	// Capacity-derived logical occupancy width.
	const COUNT_BITS: int = Bits.RequiredFor(CAPACITY)

	// Backing cells retain inactive values across Clear; size defines validity.
	@UninitializedStorage
	storage: T[CAPACITY]

	// Logical occupancy and the value returned by empty reads.
	size: logic[COUNT_BITS]
	zero: T

	/**
	 * Appends a value to the top when capacity is available.
	 */
	override fn Push(value: T)
	{
		if ((this.size as uint) < (CAPACITY as uint)) {
			this.storage[this.size as uint] = value
			this.size = ((this.size as uint) + 1) as logic[COUNT_BITS]
		}
	}

	/**
	 * Removes and returns the newest value, or zero when empty.
	 */
	override fn Pop() T
	{
		if ((this.size as uint) > 0) {
			var topIndex = (this.size as uint) - 1
			this.size = topIndex as logic[COUNT_BITS]
			return this.storage[topIndex]
		}

		return this.zero
	}

	/**
	 * Returns the newest value without removing it, or zero when empty.
	 */
	override fn Peek() T
	{
		if ((this.size as uint) > 0) {
			var topIndex = (this.size as uint) - 1
			return this.storage[topIndex]
		}

		return this.zero
	}

	/**
	 * Returns true when the stack contains no values.
	 */
	override fn IsEmpty() bool
	{
		return (this.size as uint) == 0
	}

	/**
	 * Returns true when the stack has reached its configured capacity.
	 */
	override fn IsFull() bool
	{
		return (this.size as uint) == (CAPACITY as uint)
	}

	/**
	 * Returns the current number of stacked values.
	 */
	override fn GetSize() int
	{
		return (this.size as uint) as int
	}

	/**
	 * Resets logical occupancy without erasing inactive storage cells.
	 */
	override fn Clear()
	{
		this.size = 0
	}
}