#include <time.h>

static inline struct timespec timespec_from_int64_ns(int64_t time_ns){
    struct timespec r;
    if (time_ns < 0){
        // Round negative times towards -infinity
        time_ns = -time_ns;
        r.tv_nsec = 999999999 - ((time_ns-1) % 1000000000);
        r.tv_sec = -((time_ns+999999999) / 1000000000);
    } else {
        r.tv_nsec = time_ns % 1000000000;
        r.tv_sec = time_ns / 1000000000;
    }
    return r;
}


static inline int64_t int64_ns_from_timespec(struct timespec time){
    return (int64_t)time.tv_sec * 1000000000 + time.tv_nsec;
}


static inline bool timespec_lt(struct timespec a, struct timespec b){
    return a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_nsec < b.tv_nsec);
}

static inline bool timespec_lte(struct timespec a, struct timespec b){
    return a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_nsec <= b.tv_nsec);
}

static inline bool timespec_eq(struct timespec a, struct timespec b){
    return a.tv_sec == b.tv_sec && a.tv_nsec == b.tv_nsec;
}

static inline bool timespec_gt(struct timespec a, struct timespec b){
    return timespec_lt(b, a);
}

static inline struct timespec timespec_sub(struct timespec a, struct timespec b){
    struct timespec r;
    if (a.tv_nsec < b.tv_nsec){
        r.tv_nsec = 1000000000 + a.tv_nsec - b.tv_nsec;
        r.tv_sec = a.tv_sec - b.tv_sec - 1;
    } else {
        r.tv_nsec = a.tv_nsec - b.tv_nsec;
        r.tv_sec = a.tv_sec - b.tv_sec;
    }
    return r;
}

static inline bool timespec_gte(struct timespec a, struct timespec b){
    return timespec_lte(b, a);
}

static inline bool timespec_ne(struct timespec a, struct timespec b){
    return !timespec_eq(a, b);
}
