xref: /aosp_15_r20/external/cronet/third_party/anonymous_tokens/src/anonymous_tokens/cpp/shared/proto_utils.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of 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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "anonymous_tokens/cpp/shared/proto_utils.h"
16 
17 #include "absl/status/status.h"
18 #include "absl/status/statusor.h"
19 #include "absl/strings/str_cat.h"
20 #include "absl/strings/string_view.h"
21 #include "absl/time/time.h"
22 
23 namespace anonymous_tokens {
24 
ParseUseCase(absl::string_view use_case)25 absl::StatusOr<AnonymousTokensUseCase> ParseUseCase(
26     absl::string_view use_case) {
27   AnonymousTokensUseCase parsed_use_case;
28   if (!AnonymousTokensUseCase_Parse(std::string(use_case), &parsed_use_case) ||
29       parsed_use_case == ANONYMOUS_TOKENS_USE_CASE_UNDEFINED) {
30     return absl::InvalidArgumentError(
31         "Invalid / undefined use case cannot be parsed.");
32   }
33   return parsed_use_case;
34 }
35 
TimeFromProto(const Timestamp & proto)36 absl::StatusOr<absl::Time> TimeFromProto(
37     const Timestamp& proto) {
38   const auto sec = proto.seconds();
39   const auto ns = proto.nanos();
40   // sec must be [0001-01-01T00:00:00Z, 9999-12-31T23:59:59.999999999Z]
41   if (sec < -62135596800 || sec > 253402300799) {
42     return absl::InvalidArgumentError(absl::StrCat("seconds=", sec));
43   }
44   if (ns < 0 || ns > 999999999) {
45     return absl::InvalidArgumentError(absl::StrCat("nanos=", ns));
46   }
47   return absl::FromUnixSeconds(proto.seconds()) +
48          absl::Nanoseconds(proto.nanos());
49 }
50 
TimeToProto(absl::Time time)51 absl::StatusOr<Timestamp> TimeToProto(absl::Time time) {
52   Timestamp proto;
53   const int64_t seconds = absl::ToUnixSeconds(time);
54   proto.set_seconds(seconds);
55   proto.set_nanos((time - absl::FromUnixSeconds(seconds)) /
56                   absl::Nanoseconds(1));
57   // seconds must be [0001-01-01T00:00:00Z, 9999-12-31T23:59:59.999999999Z]
58   if (seconds < -62135596800 || seconds > 253402300799) {
59     return absl::InvalidArgumentError(absl::StrCat("seconds=", seconds));
60   }
61   const int64_t ns = proto.nanos();
62   if (ns < 0 || ns > 999999999) {
63     return absl::InvalidArgumentError(absl::StrCat("nanos=", ns));
64   }
65   return proto;
66 }
67 
68 }  // namespace anonymous_tokens
69