Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1257,8 +1257,8 @@ jobs:
needs: changes
strategy:
matrix:
# macos-14 is the arm64 runner; keep it for Rust code changes only.
os: ${{ fromJSON(needs.changes.outputs.rust == 'true' && '["ubuntu-latest","macos-14","macos-latest"]' || '["ubuntu-latest","macos-latest"]') }}
# Keep a pinned arm64 macOS image for Rust code changes.
os: ${{ fromJSON(needs.changes.outputs.rust == 'true' && '["ubuntu-latest","macos-15","macos-latest"]' || '["ubuntu-latest","macos-latest"]') }}
runs-on: ${{ matrix.os }}
timeout-minutes: 45
steps:
Expand Down
3 changes: 1 addition & 2 deletions compiler/fory_compiler/tests/test_python_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ def test_field_names_shadowing_default_helpers_are_escaped():
)
output = generate_python(source)

# The escaped attribute names keep the wire names: pyfory strips the
# trailing underscore when computing the snake_case field name.
# Explicit field IDs preserve wire identity independently of escaped attribute names.
assert "pyfory_: str = pyfory.field(id=1" in output
assert "field_: str = pyfory.field(id=2" in output

Expand Down
45 changes: 45 additions & 0 deletions cpp/fory/serialization/struct_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ struct MaximumFieldTagStruct {
FORY_STRUCT(MaximumFieldTagStruct, (value, fory::F(536870911)));
};

struct FieldNameWriter {
int32_t fooURL;
int32_t tagged;
int32_t extra;

FORY_STRUCT(FieldNameWriter, fooURL, (tagged, fory::F(3)), extra);
};

struct FieldNameReader {
int32_t FooURL = 0;
int32_t foo_url = 0;

FORY_STRUCT(FieldNameReader, (FooURL, fory::F(3)), foo_url);
};

struct HighTagCompatibleWriter {
std::string removed;
int32_t shared;
Expand Down Expand Up @@ -1616,6 +1631,36 @@ TEST(StructComprehensiveTest,
EXPECT_EQ(untagged_remote_for_tagged_local[0].matched_field_id, -1);
}

TEST(StructComprehensiveTest, CanonicalFieldIdentity) {
TypeMeta local_type;
local_type.field_infos = {
make_test_field_info("fooURL", 3, make_test_field_type(TypeId::VARINT32)),
make_test_field_info("foo_url", -1,
make_test_field_type(TypeId::VARINT32))};
std::vector<FieldInfo> remote_fields = {
make_test_field_info("FooURL", -1,
make_test_field_type(TypeId::VARINT32)),
make_test_field_info("renamed", 3,
make_test_field_type(TypeId::VARINT32))};
ASSERT_TRUE(
TypeMeta::assign_local_dispatch_ids(&local_type, remote_fields).ok());
EXPECT_EQ(remote_fields[0].matched_field_id, 2);
EXPECT_EQ(remote_fields[1].matched_field_id, 0);

auto writer =
Fory::builder().xlang(true).compatible(true).track_ref(false).build();
auto reader =
Fory::builder().xlang(true).compatible(true).track_ref(false).build();
ASSERT_TRUE(writer.register_struct<FieldNameWriter>(632).ok());
ASSERT_TRUE(reader.register_struct<FieldNameReader>(632).ok());
auto bytes = writer.serialize(FieldNameWriter{7, 11, 17});
ASSERT_TRUE(bytes.ok()) << bytes.error().to_string();
auto decoded = reader.deserialize<FieldNameReader>(bytes.value());
ASSERT_TRUE(decoded.ok()) << decoded.error().to_string();
EXPECT_EQ(decoded->FooURL, 11);
EXPECT_EQ(decoded->foo_url, 7);
}

TEST(StructComprehensiveTest, CompatibleSignedToUnsignedStructRead) {
auto writer =
Fory::builder().xlang(true).compatible(true).track_ref(false).build();
Expand Down
127 changes: 27 additions & 100 deletions cpp/fory/serialization/type_resolver.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1346,11 +1346,15 @@ TypeMeta::assign_local_dispatch_ids(const TypeMeta *local_type,
Error::invalid("Field tag exceeds the wire TAG_ID range"));
}

// Primary mapping: field name -> sorted index in local schema
// Tagged fields have no name identity and must not hide an untagged field
// with the same canonical name.
std::unordered_map<std::string, size_t> local_field_index_map;
local_field_index_map.reserve(local_fields.size());
for (size_t i = 0; i < local_fields.size(); ++i) {
local_field_index_map.emplace(local_fields[i].field_name, i);
if (local_fields[i].field_id < 0) {
local_field_index_map.emplace(to_snake_case(local_fields[i].field_name),
i);
}
}
// Tag ID mapping when field IDs are explicitly configured.
std::unordered_map<int32_t, size_t> local_field_id_map;
Expand Down Expand Up @@ -1426,18 +1430,14 @@ TypeMeta::assign_local_dispatch_ids(const TypeMeta *local_type,
matched = is_matched;
}
} else {
// 1) Try exact name + type match first (fast path for same-language
// schemas and most C++-only cases). A local tag-ID field's identifier
// 1) Match canonical name and type. A local tag-ID field's identifier
// is the tag ID, not the field name, so it must not match an untagged
// remote field by name in a mixed schema.
auto it = local_field_index_map.find(remote_field.field_name);
auto it =
local_field_index_map.find(to_snake_case(remote_field.field_name));
if (it != local_field_index_map.end()) {
size_t idx = it->second;
const FieldInfo &local_field = local_fields[idx];
if (local_field.field_id < 0) {
FORY_TRY(is_matched, assign_matched_field(remote_field, idx));
matched = is_matched;
}
FORY_TRY(is_matched, assign_matched_field(remote_field, it->second));
matched = is_matched;
}

// 2) Fallback by type signature only when no canonical remote name was
Expand Down Expand Up @@ -1474,79 +1474,6 @@ int64_t TypeMeta::compute_hash(const std::vector<uint8_t> &meta_bytes) {
return compute_type_meta_hash(meta_bytes.data(), meta_bytes.size());
}

namespace {

std::string to_snake_case(const std::string &name) {
bool all_lower = true;
for (char c : name) {
unsigned char uc = static_cast<unsigned char>(c);
if (!(static_cast<bool>(std::islower(uc)) ||
static_cast<bool>(std::isdigit(uc)) || c == '_')) {
all_lower = false;
break;
}
}
if (all_lower) {
return name;
}

std::string result;
result.reserve(name.size() * 2);
std::optional<char> prev;

for (size_t i = 0; i < name.size(); ++i) {
char ch = name[i];
if (ch == '_') {
result.push_back('_');
prev = ch;
continue;
}

if (static_cast<bool>(std::isupper(static_cast<unsigned char>(ch)))) {
bool need_underscore = false;
if (prev.has_value()) {
char prev_ch = *prev;
bool prev_lower_or_digit = static_cast<bool>(
std::islower(static_cast<unsigned char>(prev_ch)) ||
std::isdigit(static_cast<unsigned char>(prev_ch)));
bool prev_upper = static_cast<bool>(
std::isupper(static_cast<unsigned char>(prev_ch)));

bool next_is_lower = false;
if (i + 1 < name.size()) {
char next = name[i + 1];
next_is_lower =
static_cast<bool>(std::islower(static_cast<unsigned char>(next)));
}

if (prev_lower_or_digit || (prev_upper && next_is_lower)) {
need_underscore = true;
}
}
if (need_underscore && !result.empty() && result.back() != '_') {
result.push_back('_');
}
result.push_back(
static_cast<char>(std::tolower(static_cast<unsigned char>(ch))));
} else {
result.push_back(ch);
}
prev = ch;
}

return result;
}

std::string normalize_field_name(const std::string &name) {
std::string normalized = to_snake_case(name);
while (!normalized.empty() && normalized.back() == '_') {
normalized.pop_back();
}
return normalized;
}

} // anonymous namespace

std::string TypeMeta::compute_struct_fingerprint(
const std::vector<FieldInfo> &field_infos) {
// Computes the fingerprint string for a struct type used in schema
Expand All @@ -1569,21 +1496,21 @@ std::string TypeMeta::compute_struct_fingerprint(

// Copy fields and sort by canonical field identifier for fingerprint.
std::vector<FieldInfo> sorted_fields = field_infos;
std::sort(
sorted_fields.begin(), sorted_fields.end(),
[](const FieldInfo &a, const FieldInfo &b) {
if (a.field_id >= 0 && b.field_id >= 0 && a.field_id != b.field_id) {
return a.field_id < b.field_id;
}
std::string a_id = a.field_id >= 0 ? std::to_string(a.field_id)
: normalize_field_name(a.field_name);
std::string b_id = b.field_id >= 0 ? std::to_string(b.field_id)
: normalize_field_name(b.field_name);
if (a_id != b_id) {
return a_id < b_id;
}
return a.field_name < b.field_name;
});
std::sort(sorted_fields.begin(), sorted_fields.end(),
[](const FieldInfo &a, const FieldInfo &b) {
if (a.field_id >= 0 && b.field_id >= 0 &&
a.field_id != b.field_id) {
return a.field_id < b.field_id;
}
std::string a_id = a.field_id >= 0 ? std::to_string(a.field_id)
: to_snake_case(a.field_name);
std::string b_id = b.field_id >= 0 ? std::to_string(b.field_id)
: to_snake_case(b.field_name);
if (a_id != b_id) {
return a_id < b_id;
}
return a.field_name < b.field_name;
});

std::string fingerprint;
// reserve a rough estimate to avoid reallocations
Expand Down Expand Up @@ -1636,7 +1563,7 @@ std::string TypeMeta::compute_struct_fingerprint(
for (const auto &fi : sorted_fields) {
std::string field_id_or_name = fi.field_id >= 0
? std::to_string(fi.field_id)
: normalize_field_name(fi.field_name);
: to_snake_case(fi.field_name);
fingerprint.append(field_id_or_name);
fingerprint.push_back(',');
append_field_type(fingerprint, fi.field_type, true, true);
Expand Down
30 changes: 30 additions & 0 deletions cpp/fory/serialization/xlang_test_main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ struct Item {
FORY_STRUCT(Item, name);
};

struct FieldNames {
int32_t createdAt;
int32_t fooURL;
int32_t URLValue;
int32_t HTTP2Server;
int32_t x2Y;
int32_t ABc;
FORY_STRUCT(FieldNames, createdAt, fooURL, URLValue, HTTP2Server, x2Y, ABc);
};

struct SimpleStruct {
std::map<int32_t, double> f1;
int32_t f2;
Expand Down Expand Up @@ -966,6 +976,7 @@ void run_test_skip_id_custom(const std::string &data_file);
void run_test_skip_name_custom(const std::string &data_file);
void run_test_consistent_named(const std::string &data_file);
void run_test_struct_version_check(const std::string &data_file);
void run_test_field_names(const std::string &data_file, bool compatible);
void run_test_polymorphic_list(const std::string &data_file);
void run_test_polymorphic_map(const std::string &data_file);
void run_test_one_string_field_schema(const std::string &data_file);
Expand Down Expand Up @@ -1072,6 +1083,10 @@ int main(int argc, char **argv) {
run_test_consistent_named(data_file);
} else if (case_name == "test_struct_version_check") {
run_test_struct_version_check(data_file);
} else if (case_name == "test_field_names") {
run_test_field_names(data_file, false);
} else if (case_name == "test_field_names_compatible") {
run_test_field_names(data_file, true);
} else if (case_name == "test_polymorphic_list") {
run_test_polymorphic_list(data_file);
} else if (case_name == "test_polymorphic_map") {
Expand Down Expand Up @@ -2027,6 +2042,21 @@ void run_test_consistent_named(const std::string &data_file) {
write_file(data_file, out);
}

void run_test_field_names(const std::string &data_file, bool compatible) {
auto bytes = read_file(data_file);
auto fory = build_fory(compatible, true, true);
ensure_ok(fory.register_struct<FieldNames>(9201), "register FieldNames");
Buffer buffer = make_buffer(bytes);
auto value = read_next<FieldNames>(fory, buffer);
if (value.createdAt != 7 || value.fooURL != 11 || value.URLValue != 13 ||
value.HTTP2Server != 17 || value.x2Y != 19 || value.ABc != 23) {
fail("FieldNames mismatch");
}
std::vector<uint8_t> out;
append_serialized(fory, value, out);
write_file(data_file, out);
}

void run_test_struct_version_check(const std::string &data_file) {
auto bytes = read_file(data_file);
// Java uses SCHEMA_CONSISTENT mode which does NOT enable meta sharing
Expand Down
12 changes: 12 additions & 0 deletions cpp/fory/util/string_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,18 @@ to_snake_case(std::string_view name) {
constexpr size_t snake_case_length(std::string_view name) {
return detail::snake_case_length(name);
}

inline std::string to_snake_case(std::string_view name) {
std::string result;
result.reserve(detail::snake_case_length(name));
for (size_t i = 0; i < name.size(); ++i) {
if (detail::needs_snake_separator(name, i)) {
result.push_back('_');
}
result.push_back(name[i] == '-' ? '_' : detail::to_lower_ascii(name[i]));
}
return result;
}
#if defined(FORY_HAS_IMMINTRIN)

inline bool is_ascii(const char *data, size_t length) {
Expand Down
20 changes: 20 additions & 0 deletions cpp/fory/util/string_util_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,26 @@ TEST(StringUtilTest, Latin1SizeBoundary) {
}

TEST(StringUtilTest, ToSnakeCaseHandlesCommonPatterns) {
for (const auto &entry : std::vector<std::pair<std::string, std::string>>{
{"createdAt", "created_at"},
{"CreatedAt", "created_at"},
{"fooURL", "foo_url"},
{"URLValue", "url_value"},
{"HTTP2Server", "http2_server"},
{"x2Y", "x2_y"},
{"ABc", "a_bc"},
{"fooÖl", "fooÖl"},
{"ÖValue", "Övalue"},
{"_URL_Value_", "_url_value_"},
{"already__snake", "already__snake"},
{"foo-Bar", "foo_bar"},
{"", ""}}) {
EXPECT_EQ(to_snake_case(entry.first), entry.second);
EXPECT_EQ(to_snake_case(entry.second), entry.second);
auto encoded = to_snake_case<64>(entry.first);
EXPECT_EQ(std::string(encoded.first.data(), encoded.second), entry.second);
EXPECT_EQ(snake_case_length(entry.first), entry.second.size());
}
constexpr std::string_view simple_name{"DisplayName"};
constexpr size_t simple_len = snake_case_length(simple_name);
constexpr auto simple_pair = to_snake_case<simple_len>(simple_name);
Expand Down
14 changes: 7 additions & 7 deletions csharp/src/Fory.Generator/ForyModelGenerator.Analysis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2811,24 +2811,24 @@ private static string ToSnakeCase(string name)
for (int i = 0; i < name.Length; i++)
{
char c = name[i];
if (char.IsUpper(c))
if (c is >= 'A' and <= 'Z')
{
if (i > 0)
{
bool prevUpper = char.IsUpper(name[i - 1]);
bool nextUpperOrEnd = i + 1 >= name.Length || char.IsUpper(name[i + 1]);
bool leadingPascalBoundary = i == 1 && prevUpper && !nextUpperOrEnd;
if ((!prevUpper || !nextUpperOrEnd) && !leadingPascalBoundary)
char previous = name[i - 1];
bool nextLower = i + 1 < name.Length && name[i + 1] is >= 'a' and <= 'z';
if (previous is >= 'a' and <= 'z' or >= '0' and <= '9'
|| (previous is >= 'A' and <= 'Z' && nextLower))
{
sb.Append('_');
}
}

sb.Append(char.ToLowerInvariant(c));
sb.Append((char)(c + ('a' - 'A')));
}
else
{
sb.Append(c);
sb.Append(c == '-' ? '_' : c);
}
}

Expand Down
Loading
Loading