#include "cpp-vstack.hpp"
#include <utility>

stack::node::node( const object & v, node * n ) : value( v.new_copy() ), next( n ) {}

void stack::copy( const stack & o ) {
	node ** cr = &head;
	for ( node * nx = o.head; nx; nx = nx->next ) {
		*cr = new node{ *nx->value }; /***/
		cr = &(*cr)->next;
	}
	*cr = nullptr;
}

void stack::clear() {
	for ( node * nx = head; nx; ) {
		node * cr = nx;
		nx = cr->next;
		delete cr;
	}
	head = nullptr;
}

stack::stack() : head( nullptr ) {}
stack::stack( const stack & o ) { copy( o ); }
stack::~stack() { clear(); }

stack & stack::operator=( const stack & o ) {
	if ( this == &o ) return *this;
	clear();
	copy( o );
	return *this;
}

bool stack::empty() const {
	return head == nullptr;
}

void stack::push( const object & value ) {
	head = new node{ value, head }; /***/
}

ptr<object> stack::pop() {
	node * n = head;
	head = n->next;
	ptr<object> v = std::move( n->value );
	delete n;
	return v;
}
