/* VectorNav HSI Calibration Library v1.0.0.2
 *
 * Copyright (c) 2018 VectorNav Technologies, LLC
 *
 * This source code is proprietary to and copyrighted by VectorNav Technologies, LLC and is
 * available solely under license from VectorNav. All rights reserved. If you do not have a
 * license to use this source code from VectorNav, any use hereof is strictly prohibited by
 * U.S. law and other applicable law. This source code is restricted for use solely with the
 * products of VectorNav and as otherwise set forth in any agreement with VectorNav. Any
 * disclosure of this source code to the public or to any third party is also prohibited.
 */
#include "vncriticalsection.h"

enum VnError VnCriticalSection_initialize(struct VnCriticalSection *cs)
{
  #if VN_WINDOWS_BASED

  InitializeCriticalSection(&cs->handle);

  #elif VN_UNIX_BASED

  if (pthread_mutex_init(&cs->handle, NULL))
    return E_UNKNOWN;

  #endif

  return E_NONE;
}

enum VnError VnCriticalSection_deinitialize(struct VnCriticalSection *cs)
{
  #if VN_WINDOWS_BASED
  
  DeleteCriticalSection(&cs->handle);
  
  #elif VN_UNIX_BASED
  
  if (pthread_mutex_destroy(&cs->handle))
    return E_UNKNOWN;
  
  #endif

  return E_NONE;
}

enum VnError VnCriticalSection_enter(struct VnCriticalSection *cs)
{
  #if VN_WINDOWS_BASED
  
  EnterCriticalSection(&cs->handle);
  
  #elif VN_UNIX_BASED
  
  if (pthread_mutex_lock(&cs->handle))
    return E_UNKNOWN;

  #endif

  return E_NONE;
}

enum VnError VnCriticalSection_leave(struct VnCriticalSection *cs)
{
  #if VN_WINDOWS_BASED
  
  LeaveCriticalSection(&cs->handle);
  
  #elif VN_UNIX_BASED
  
  if (pthread_mutex_unlock(&cs->handle))
    return E_UNKNOWN;
  
  #endif

  return E_NONE;
}
