1#pragma once
2
3#define __NEED_struct_timespec
4
5#include "threads_impl.h"
6
7#include <bits/alltypes.h>
8#include <zircon/time.h>
9#include <zircon/types.h>
10
11static inline zx_time_t __duration_timespec_to_deadline(const struct timespec timespec) {
12    zx_duration_t nanos = zx_duration_add_duration(
13        zx_duration_mul_int64(1000000000ll, timespec.tv_sec),
14        timespec.tv_nsec);
15    return _zx_deadline_after(nanos);
16}
17
18static inline int __timespec_to_deadline(const struct timespec* timespec,
19                                         clockid_t clk, zx_time_t* deadline) {
20    struct timespec to;
21
22    if (timespec->tv_nsec >= ZX_SEC(1))
23        return EINVAL;
24    if (__clock_gettime(clk, &to))
25        return EINVAL;
26    to.tv_sec = timespec->tv_sec - to.tv_sec;
27    if ((to.tv_nsec = timespec->tv_nsec - to.tv_nsec) < 0) {
28        to.tv_sec--;
29        to.tv_nsec += ZX_SEC(1);
30    }
31    if (to.tv_sec < 0)
32        return ETIMEDOUT;
33    *deadline = __duration_timespec_to_deadline(to);
34    return 0;
35}
36