Skip to content

Commit

Permalink
[gpr] Replace a call to localtime with a call to absl::FormatTime.
Browse files Browse the repository at this point in the history
localtime is not thread-safe, which means that client libraries can suffer from subtle data races.

PiperOrigin-RevId: 670616652
  • Loading branch information
Joey Raso authored and copybara-github committed Sep 3, 2024
1 parent 4fe0033 commit c0b326b
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/core/util/string.cc
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include <time.h>

#include "absl/strings/str_cat.h"
#include "absl/time/time.h"

#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
Expand All @@ -53,14 +54,14 @@ char* gpr_strdup(const char* src) {
}

std::string gpr_format_timespec(gpr_timespec tm) {
char time_buffer[35];
char ns_buffer[11]; // '.' + 9 digits of precision
struct tm* tm_info = localtime(reinterpret_cast<time_t*>(&tm.tv_sec));
strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%dT%H:%M:%S", tm_info);
snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec);
const std::string time_str =
absl::FormatTime("%Y-%m-%d%ET%H:%M:%S", absl::FromUnixSeconds(tm.tv_sec),
absl::LocalTimeZone());
// This loop trims off trailing zeros by inserting a null character that the
// right point. We iterate in chunks of three because we want 0, 3, 6, or 9
// fractional digits.
char ns_buffer[11]; // '.' + 9 digits of precision
snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec);
for (int i = 7; i >= 1; i -= 3) {
if (ns_buffer[i] == '0' && ns_buffer[i + 1] == '0' &&
ns_buffer[i + 2] == '0') {
Expand All @@ -73,7 +74,7 @@ std::string gpr_format_timespec(gpr_timespec tm) {
break;
}
}
return absl::StrCat(time_buffer, ns_buffer, "Z");
return absl::StrCat(time_str, ns_buffer, "Z");
}

struct dump_out {
Expand Down

0 comments on commit c0b326b

Please sign in to comment.