// ===========================================================
// File: Semaphore.cpp
//
// Implementation of the Semaphore class. Semaphore provides
// resource for client programs during system call. They
// organize synchronization of concurrent processes.
// ===========================================================

#include <stdlib.h>
#include "Pcib.h"
#include "List.h"
#include "Semaphore.h"

// ===========================================================
// Identifier:  Semaphore()
//
// Comments:    Semaphore default constructor. Initialize
//              all data structure and create 2 list
// ===========================================================

Semaphore::Semaphore()
{
    this->semId = -1;
    this->semKey = -1;
    this->semValue = 0;

    this->AuthorizedList = new List;
    this->WaitingList = new List;
}

// ===========================================================
// Identifier:  Semaphore(const Semaphore&)
//
// Parameter:   &s      -- a semaphore
//
// Comments:    Semaphore copy constructor. Performs a deep
//              copy of the lists.
// ===========================================================

Semaphore::Semaphore(const Semaphore &s)
{
    this->semId = s.semId;
    this->semKey = s.semKey;
    this->semValue = s.semValue;
    *(this->AuthorizedList) = *(s.AuthorizedList);
    *(this->WaitingList) = *(s.WaitingList);
}

// ===========================================================
// Identifier:  ~Semaphore()
//
// Comments:    Semaphore destructor. Prevents memory leak
// ===========================================================

Semaphore::~Semaphore()
{
    this->semKey = -1;
    this->semValue = -1;

    delete this->AuthorizedList;
    delete this->WaitingList;

    this->AuthorizedList = NULL;
    this->WaitingList = NULL;
}

// ===========================================================
// Identifier:  Semaphore& operator=(const Semaphore&)
//
// Parameter:   &s          -- a semaphore
//
// Comments:    Semaphore overloaded = operator. Enables
//              semaphore instances to be assigned to another
//              semaphore.
//
// Returns:     *this   -- for concatenation
// ===========================================================

Semaphore& Semaphore::operator=(const Semaphore &s)
{
    if (this != &s)
    {
        this->~Semaphore();
        this->semId = s.semId;
        this->semKey = s.semKey;
        this->semValue = s.semValue;
        *(this->AuthorizedList) = *(s.AuthorizedList);
        *(this->WaitingList) = *(s.WaitingList);
    }
    return *this;
}