Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve leading _ for camel/pascal renaming #620

Merged
merged 1 commit into from
Dec 20, 2023
Merged
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
22 changes: 14 additions & 8 deletions msgspec/_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -5140,17 +5140,23 @@ rename_camel_inner(PyObject *field, bool cap_first) {
bool first = true;
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(parts); i++) {
PyObject *part = PyList_GET_ITEM(parts, i);
if (PyUnicode_GET_LENGTH(part) == 0) continue;
if (!first || cap_first) {
/* convert part to title case, inplace in the list */
PyObject *part_title = PyObject_CallMethod(part, "title", NULL);
if (part_title == NULL) goto cleanup;
PyList_SET_ITEM(parts, i, part_title);
if (first && (PyUnicode_GET_LENGTH(part) == 0)) {
/* Preserve leading underscores */
PyList_SET_ITEM(parts, i, underscore);
Py_DECREF(part);
}
first = false;
else {
if (!first || cap_first) {
/* convert part to title case, inplace in the list */
PyObject *part_title = PyObject_CallMethod(part, "title", NULL);
if (part_title == NULL) goto cleanup;
PyList_SET_ITEM(parts, i, part_title);
Py_DECREF(part);
}
first = false;
}
}
empty = PyUnicode_FromString("");
empty = PyUnicode_FromStringAndSize("", 0);
if (empty == NULL) goto cleanup;
out = PyUnicode_Join(empty, parts);

Expand Down
10 changes: 8 additions & 2 deletions tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -1942,12 +1942,14 @@ class Test(Struct, rename="kebab"):
field_two_with_suffix: str
__field_three__: bool
field4: float
_field_five: int

assert Test.__struct_encode_fields__ == (
"field-one",
"field-two-with-suffix",
"field-three",
"field4",
"field-five",
)

def test_rename_camel(self):
Expand All @@ -1956,12 +1958,14 @@ class Test(Struct, rename="camel"):
field_two_with_suffix: str
__field__three__: bool
field4: float
_field_five: int

assert Test.__struct_encode_fields__ == (
"fieldOne",
"fieldTwoWithSuffix",
"fieldThree",
"__fieldThree",
"field4",
"_fieldFive",
)

def test_rename_pascal(self):
Expand All @@ -1970,12 +1974,14 @@ class Test(Struct, rename="pascal"):
field_two_with_suffix: str
__field__three__: bool
field4: float
_field_five: int

assert Test.__struct_encode_fields__ == (
"FieldOne",
"FieldTwoWithSuffix",
"FieldThree",
"__FieldThree",
"Field4",
"_FieldFive",
)

def test_rename_callable(self):
Expand Down
Loading