xref: /aosp_15_r20/external/pigweed/pw_async_fuchsia/public/pw_async_fuchsia/util.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <lib/zx/time.h>
17 
18 #include "pw_chrono/system_clock.h"
19 
20 namespace pw::async_fuchsia {
21 
ZxTimeToTimepoint(zx::time time)22 constexpr pw::chrono::SystemClock::time_point ZxTimeToTimepoint(zx::time time) {
23   timespec ts = time.to_timespec();
24   auto duration =
25       std::chrono::seconds{ts.tv_sec} + std::chrono::nanoseconds{ts.tv_nsec};
26   return pw::chrono::SystemClock::time_point{duration};
27 }
28 
TimepointToZxTime(pw::chrono::SystemClock::time_point tp)29 constexpr zx::time TimepointToZxTime(pw::chrono::SystemClock::time_point tp) {
30   auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(tp);
31   auto ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(tp) -
32             std::chrono::time_point_cast<std::chrono::nanoseconds>(seconds);
33 
34   return zx::time{timespec{seconds.time_since_epoch().count(), ns.count()}};
35 }
36 
37 }  // namespace pw::async_fuchsia
38