/*
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * Author:
 *         Roman Krenicky
 *
 * $Id: misc.cpp,v 1.2 2005/11/21 09:39:01 kutzner Exp $
 *
 */

/*
  misc.cpp
  created: 30.4.2005
  last change: 30.4.2005
*/
/*! @file
    some useful utility functions
*/

#include "globalheader.h"

#include "misc.h"


/*! @brief adds two times

    @param time1  some time (0 <= time1.tv_nsec <= 999 999 999)
    @param time2  some time (0 <= time2.tv_nsec <= 999 999 999)
    @return @a time1 + @a time2
*/
timespec timeadd (const timespec &time1, const timespec &time2)
{
   timespec retval;

   retval.tv_sec = time1.tv_sec + time2.tv_sec;
   retval.tv_nsec = time1.tv_nsec + time2.tv_nsec;
   // overflow:
   if (retval.tv_nsec >= 1000000000L)
   {
      retval.tv_nsec -= 1000000000L;
      retval.tv_sec++;
   } // if (retval.tv_nsec >= 1000000000L)

   return retval;
} // timeadd (...)


/*! @brief subtracts two times

    @param time1  some time (0 <= time1.tv_nsec <= 999 999 999)
    @param time2  some time (0 <= time2.tv_nsec <= 999 999 999)
    @return @a time1 - @a time2
*/
timespec timesub (const timespec &time1, const timespec &time2)
{
   timespec retval;

   retval.tv_sec = time1.tv_sec - time2.tv_sec;
   // carry:
   if (time1.tv_nsec >= time2.tv_nsec)
      retval.tv_nsec = time1.tv_nsec - time2.tv_nsec;
   else  // carry
   {
      retval.tv_nsec = 1000000000L + time1.tv_nsec - time2.tv_nsec;
      retval.tv_sec--;
   } // else  -> carry

   return retval;
} // timesub (...)


/*! @brief compares two times
    @param time1  some time (0 <= time1.tv_nsec <= 999 999 999)
    @param time2  some time (0 <= time2.tv_nsec <= 999 999 999)
    @return -1, 0 or 1 if @a time1 is less than, equals or is greater than
            @a time2
*/
int timecmp (const timespec &time1, const timespec &time2)
{
   if (time1.tv_sec < time2.tv_sec)
      return -1;
   else if (time1.tv_sec > time2.tv_sec)
      return 1;
   else // (time1.tv_sec == time2.tv_sec)
   {
      if (time1.tv_nsec < time2.tv_nsec)
         return -1;
      else if (time1.tv_nsec > time2.tv_nsec)
         return 1;
      // else:
      return 0;
   } // else -> (time1.tv_sec == time2.tv_sec)
} // timecmp (...)
