• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //
3 // Copyright 2020 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include <grpc/support/port_platform.h>
20 
21 #include "src/core/lib/json/json_util.h"
22 
23 #include <grpc/support/string_util.h>
24 
25 #include "src/core/lib/gpr/string.h"
26 
27 namespace grpc_core {
28 
ParseDurationFromJson(const Json & field,grpc_millis * duration)29 bool ParseDurationFromJson(const Json& field, grpc_millis* duration) {
30   if (field.type() != Json::Type::STRING) return false;
31   size_t len = field.string_value().size();
32   if (field.string_value()[len - 1] != 's') return false;
33   grpc_core::UniquePtr<char> buf(gpr_strdup(field.string_value().c_str()));
34   *(buf.get() + len - 1) = '\0';  // Remove trailing 's'.
35   char* decimal_point = strchr(buf.get(), '.');
36   int nanos = 0;
37   if (decimal_point != nullptr) {
38     *decimal_point = '\0';
39     nanos = gpr_parse_nonnegative_int(decimal_point + 1);
40     if (nanos == -1) {
41       return false;
42     }
43     int num_digits = static_cast<int>(strlen(decimal_point + 1));
44     if (num_digits > 9) {  // We don't accept greater precision than nanos.
45       return false;
46     }
47     for (int i = 0; i < (9 - num_digits); ++i) {
48       nanos *= 10;
49     }
50   }
51   int seconds =
52       decimal_point == buf.get() ? 0 : gpr_parse_nonnegative_int(buf.get());
53   if (seconds == -1) return false;
54   *duration = seconds * GPR_MS_PER_SEC + nanos / GPR_NS_PER_MS;
55   return true;
56 }
57 
58 }  // namespace grpc_core
59