Queue optimization. Fix #5

This commit is contained in:
Eugen Wissner 2017-01-14 21:27:07 +01:00
parent c567b88d5d
commit f5fe7bec4a

View File

@ -10,6 +10,7 @@
*/ */
module tanya.container.queue; module tanya.container.queue;
import core.exception;
import std.traits; import std.traits;
import std.algorithm.mutation; import std.algorithm.mutation;
import tanya.container.entry; import tanya.container.entry;
@ -71,6 +72,29 @@ struct Queue(T)
assert(q.length == 0); assert(q.length == 0);
} }
private void enqueueEntry(ref Entry!T* entry)
{
if (empty)
{
first = rear = entry;
}
else
{
rear.next = entry;
rear = rear.next;
}
}
private Entry!T* allocateEntry()
{
auto temp = cast(Entry!T*) allocator.allocate(Entry!T.sizeof);
if (temp is null)
{
onOutOfMemoryError();
}
return temp;
}
/** /**
* Inserts a new element. * Inserts a new element.
* *
@ -81,23 +105,27 @@ struct Queue(T)
*/ */
ref typeof(this) enqueue(ref T x) ref typeof(this) enqueue(ref T x)
{ {
auto temp = allocator.make!(Entry!T)(x); auto temp = allocateEntry();
if (empty)
{ *temp = Entry!T.init;
first = rear = temp; temp.content = x;
}
else enqueueEntry(temp);
{
rear.next = temp;
rear = rear.next;
}
return this; return this;
} }
/// Ditto. /// Ditto.
ref typeof(this) enqueue(T x) ref typeof(this) enqueue(T x)
{ {
return enqueue(x); auto temp = allocateEntry();
moveEmplace(x, (*temp).content);
(*temp).next = null;
enqueueEntry(temp);
return this;
} }
/// ///