xref: /aosp_15_r20/external/federated-compute/fcp/base/time_util.cc (revision 14675a029014e728ec732f129a32e299b2da0601)
1 /*
2  * Copyright 2022 Google LLC
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 #include "fcp/base/time_util.h"
17 
18 #include <limits>
19 
20 #include "absl/time/time.h"
21 
22 namespace fcp {
23 
ConvertAbslToProtoTimestamp(absl::Time t)24 google::protobuf::Timestamp TimeUtil::ConvertAbslToProtoTimestamp(
25     absl::Time t) {
26   google::protobuf::Timestamp proto_timestamp;
27   const int64_t s = absl::ToUnixSeconds(t);
28   proto_timestamp.set_seconds(s);
29   // The nanos field can only range from 0 to 1e9 - 1 so conversion to int32 is
30   // fine.
31   proto_timestamp.set_nanos((t - absl::FromUnixSeconds(s)) /
32                             absl::Nanoseconds(1));
33   return proto_timestamp;
34 }
35 
ConvertProtoToAbslTime(google::protobuf::Timestamp proto)36 absl::Time TimeUtil::ConvertProtoToAbslTime(google::protobuf::Timestamp proto) {
37   return absl::FromUnixSeconds(proto.seconds()) +
38          absl::Nanoseconds(proto.nanos());
39 }
40 
ConvertAbslToProtoDuration(absl::Duration absl_duration)41 google::protobuf::Duration TimeUtil::ConvertAbslToProtoDuration(
42     absl::Duration absl_duration) {
43   google::protobuf::Duration proto_duration;
44   if (absl_duration == absl::InfiniteDuration()) {
45     proto_duration.set_seconds(std::numeric_limits<int64_t>::max());
46     proto_duration.set_nanos(static_cast<int32_t>(999999999));
47   } else if (absl_duration == -absl::InfiniteDuration()) {
48     proto_duration.set_seconds(std::numeric_limits<int64_t>::min());
49     proto_duration.set_nanos(static_cast<int32_t>(-999999999));
50   } else {
51     // s and n may both be negative, per the Duration proto spec.
52     const int64_t s =
53         absl::IDivDuration(absl_duration, absl::Seconds(1), &absl_duration);
54     const int64_t n =
55         absl::IDivDuration(absl_duration, absl::Nanoseconds(1), &absl_duration);
56     proto_duration.set_seconds(s);
57     proto_duration.set_nanos(static_cast<int32_t>(n));
58   }
59   return proto_duration;
60 }
61 
ConvertProtoToAbslDuration(google::protobuf::Duration proto)62 absl::Duration TimeUtil::ConvertProtoToAbslDuration(
63     google::protobuf::Duration proto) {
64   return absl::Seconds(proto.seconds()) + absl::Nanoseconds(proto.nanos());
65 }
66 
67 }  // namespace fcp
68