Some more OpenSSL 1.1.0 compat APIs
[folly.git] / folly / portability / SysTime.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/portability/SysTime.h>
18
19 #ifdef _WIN32
20
21 #include <cstdint>
22
23 #include <Windows.h>
24
25 extern "C" {
26 int gettimeofday(timeval* tv, timezone*) {
27   constexpr auto posixWinFtOffset = 116444736000000000ULL;
28
29   if (tv) {
30     FILETIME ft;
31     ULARGE_INTEGER lft;
32     GetSystemTimeAsFileTime(&ft);
33     // As per the docs of FILETIME, don't just do an indirect
34     // pointer cast, to avoid alignment faults.
35     lft.HighPart = ft.dwHighDateTime;
36     lft.LowPart = ft.dwLowDateTime;
37     uint64_t ns = lft.QuadPart;
38     tv->tv_usec = (long)((ns / 10ULL) % 1000000ULL);
39     tv->tv_sec = (long)((ns - posixWinFtOffset) / 10000000ULL);
40   }
41
42   return 0;
43 }
44
45 void timeradd(timeval* a, timeval* b, timeval* res) {
46   res->tv_sec = a->tv_sec + b->tv_sec;
47   res->tv_usec = a->tv_usec + b->tv_usec;
48   if (res->tv_usec >= 1000000) {
49     res->tv_sec++;
50     res->tv_usec -= 1000000;
51   }
52 }
53
54 void timersub(timeval* a, timeval* b, timeval* res) {
55   res->tv_sec = a->tv_sec - b->tv_sec;
56   res->tv_usec = a->tv_usec - b->tv_usec;
57   if (res->tv_usec < 0) {
58     res->tv_sec--;
59     res->tv_usec += 1000000;
60   }
61 }
62 }
63
64 #endif