//
//  DateUtils.m
//  Cloudy
//
//  Created by Jens Alfke on 3/25/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "DateUtils.h"

#include <assert.h>
#include <CoreServices/CoreServices.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <unistd.h>


/** Absolute time (since 'reference date') to NSDate. 0.0 -> nil. */
NSDate* $date( CFAbsoluteTime time )
{
    CAssert(time>=0.0 && time < 1.0e15, @"Bogus timestamp %g",time);
    return time ?[NSDate dateWithTimeIntervalSinceReferenceDate: time] :nil;
}


/** NSDate to absolute time (since 'reference date'). nil -> 0.0 */
CFAbsoluteTime $time( NSDate* date )
{
    return date ?[date timeIntervalSinceReferenceDate] :0.0;
}



NSTimeInterval TimeIntervalSinceBoot(void)
{
    // From http://developer.apple.com/qa/qa2004/qa1398.html
    uint64_t abstime = mach_absolute_time();
    // Have to do some pointer fun because AbsoluteToNanoseconds
    // works in terms of UnsignedWide, which is a structure rather
    // than a proper 64-bit integer.
    Nanoseconds elapsedNano = AbsoluteToNanoseconds( *(AbsoluteTime *) &abstime );
    return *(uint64_t*)&elapsedNano / 1.0e9;
}

