//  Beta release only.
//
//  Copyright(c) Ivyware Pty Ltd  2006-9
//               MELBOURNE, VICTORIA, AUSTRALIA, 3130
//
//  Implementations for Microsoft Kernel32 C++ extensions
//
#include "StdAfx.h"

#include "Kernel32_Ext.h"

///////////////////////////////////////////////////////////////////////
//  Safe CRITICAL_SECTION container
//  NOTES: Allocated CRITICAL_SECTION is managed within the life cycle
//         of this object.

P2PsafeCS::P2PsafeCS ( )
{   
    m_pCSection = 0;
}
P2PsafeCS::P2PsafeCS ( CRITICAL_SECTION& rhs )
{
    EnterCriticalSection ( &rhs );   
    m_pCSection = &rhs;
}
P2PsafeCS::~P2PsafeCS ( )
{   
    if ( m_pCSection )
      LeaveCriticalSection ( m_pCSection );
}
P2PsafeCS&
P2PsafeCS::operator = ( CRITICAL_SECTION& rhs )
{   
    EnterCriticalSection ( &rhs );
    if ( m_pCSection )
      LeaveCriticalSection ( m_pCSection );
    m_pCSection = &rhs;
    return *this;
}

///////////////////////////////////////////////////////////////////////
//  Safe HANDLE implementation
//  NOTES: Assigned HANDLE is managed within the life cycle of this
//         object.
//
P2PsafeHANDLE::P2PsafeHANDLE ( )
{   
    m_oHandle = INVALID_HANDLE_VALUE;
}
P2PsafeHANDLE::P2PsafeHANDLE ( HANDLE oHandle )
{
    m_oHandle = oHandle;
}
P2PsafeHANDLE::~P2PsafeHANDLE ( )
{   
    if ( m_oHandle != INVALID_HANDLE_VALUE )
      CloseHandle ( m_oHandle );
}
P2PsafeHANDLE&
P2PsafeHANDLE::operator = ( HANDLE oHandle )
{
    if ( m_oHandle != oHandle              &&
         m_oHandle != INVALID_HANDLE_VALUE    )
      CloseHandle ( m_oHandle );
    m_oHandle = oHandle;
    return *this;
}
P2PsafeHANDLE::operator HANDLE ( )
{   
    return m_oHandle;
}
HANDLE
P2PsafeHANDLE::Dereference()
{   
    HANDLE oHandle = m_oHandle;
    m_oHandle = INVALID_HANDLE_VALUE;
    return oHandle;
}
