1 /**
2 * Copyright © Novelate 2020
3 * License: MIT (https://github.com/Novelate/NovelateEngine/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 * Website: https://novelate.com/
6 * ------
7 * Novelate is a free and open-source visual novel engine and framework written in the D programming language.
8 * It can be used freely for both personal and commercial projects.
9 * ------
10 * Module Description:
11 * This module is a wrapper around a simple queue.
12 */
13 module novelate.queue;
14 
15 /// A simple queue wrapper around a dynamic array.
16 final class Queue(T)
17 {
18   private:
19   /// The items of the queue.
20   T[] _items;
21 
22   public:
23   final:
24   /// Creates a new queue.
25   this()
26   {
27     _items = [];
28   }
29 
30   @property
31   {
32     /// Gets the length of the queue.
33     size_t length() { return _items ? _items.length : 0; }
34   }
35 
36   /**
37   * Enqueues an item.
38   * Params:
39   *   item = The item to enqueue.
40   */
41   void enqueue(T item)
42   {
43     _items ~= item;
44   }
45 
46   /**
47   * Peeks within the queue for the current front item. Use has() before calling this.
48   * Returns:
49   *   The current front item.
50   */
51   T peek()
52   {
53     auto item = _items[0];
54 
55     return item;
56   }
57 
58   /**
59   * Retrieves and removes the front item from the queue. Use has() before calling this.
60   * Returns:
61   *   The front item of the queue.
62   */
63   T dequeue()
64   {
65     auto item = _items[0];
66 
67     if (_items.length > 1)
68     {
69       _items = _items[1 .. $];
70     }
71     else
72     {
73       _items = [];
74     }
75 
76     return item;
77   }
78 
79   /**
80   * Checks whether the queue has any items or not.
81   * Returns:
82   *   True if the queue has any items, false otherwise.
83   */
84   bool has()
85   {
86     return _items && _items.length;
87   }
88 }