Merge pull request #496 from bernardo-bruning/fix-json-enconde-negative-hours

Fix negative hours when encode to JSON
pull/13171/head
Joshua Haberman 3 years ago committed by GitHub
commit 180ab22cd9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      tests/BUILD
  2. 32
      tests/test_cpp.cc
  3. 3
      upb/json_encode.c

@ -83,6 +83,7 @@ proto_library(
srcs = [
"test_cpp.proto",
],
deps = ["@com_google_protobuf//:timestamp_proto"]
)
upb_proto_library(

@ -38,6 +38,8 @@
#include "gtest/gtest.h"
#include "tests/test_cpp.upb.h"
#include "tests/test_cpp.upbdefs.h"
#include "google/protobuf/timestamp.upb.h"
#include "google/protobuf/timestamp.upbdefs.h"
#include "upb/def.h"
#include "upb/def.hpp"
#include "upb/json_decode.h"
@ -148,3 +150,33 @@ TEST(Cpp, JsonNull) {
EXPECT_EQ(0, strcmp(str_f.default_value().str_val.data, "abc"));
EXPECT_EQ(3, str_f.default_value().str_val.size);
}
TEST(Cpp, TimestampEncoder) {
upb::SymbolTable symtab;
upb::Arena arena;
upb::MessageDefPtr md(google_protobuf_Timestamp_getmsgdef(symtab.ptr()));
google_protobuf_Timestamp* timestamp_upb = google_protobuf_Timestamp_new(arena.ptr());
google_protobuf_Timestamp* timestamp_upb_decoded = google_protobuf_Timestamp_new(arena.ptr());
long timestamps[] = {
253402300799, // 9999-12-31T23:59:59Z
1641006000, // 2022-01-01T03:00:00Z
0, // 1970-01-01T00:00:00Z
-31525200, // 1969-01-01T03:00:00Z
-2208988800, // 1900-01-01T00:00:00Z
-62135596800, // 0000-01-01T00:00:00Z
};
for(long timestamp: timestamps) {
google_protobuf_Timestamp_set_seconds(timestamp_upb, timestamp);
char json[128];
size_t size = upb_JsonEncode(timestamp_upb, md.ptr(), NULL, 0, json, sizeof(json), NULL);
bool result = upb_JsonDecode(json, size, timestamp_upb_decoded, md.ptr(), NULL, 0, arena.ptr(), NULL);
const long timestamp_decoded = google_protobuf_Timestamp_seconds(timestamp_upb_decoded);
ASSERT_TRUE(result);
EXPECT_EQ(timestamp, timestamp_decoded);
}
}

@ -162,7 +162,8 @@ static void jsonenc_timestamp(jsonenc* e, const upb_Message* msg,
* Fliegel, H. F., and Van Flandern, T. C., "A Machine Algorithm for
* Processing Calendar Dates," Communications of the Association of
* Computing Machines, vol. 11 (1968), p. 657. */
L = (int)(seconds / 86400) + 68569 + 2440588;
seconds += 62135596800; // Ensure seconds is positive.
L = (int)(seconds / 86400) - 719162 + 68569 + 2440588;
N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
I = 4000 * (L + 1) / 1461001;

Loading…
Cancel
Save