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

Convert PyString append functions to void #6

Merged
merged 3 commits into from
Sep 1, 2023
Merged

Conversation

gatesn
Copy link
Contributor

@gatesn gatesn commented Aug 31, 2023

Instead of returning a new object, the CPython API effectively decref's the LHS and places a new string in its place.
This PR therefore changes our append functions to also mutate the py.PyString's internal pointer. It makes it more obvious that there's nothing to decref.

@gatesn gatesn changed the title Fix str append semantics Convert PyString append functions to void Aug 31, 2023
@gatesn gatesn enabled auto-merge (squash) August 31, 2023 21:36
pub fn asSlice(self: PyString) ![:0]const u8 {
var size: i64 = 0;
const buffer: [*]const u8 = ffi.PyUnicode_AsUTF8AndSize(self.obj.py, &size) orelse return PyError.Propagate;
return @ptrCast(buffer[0..@intCast(size + 1)]);
const buffer: [*:0]const u8 = ffi.PyUnicode_AsUTF8AndSize(self.obj.py, &size) orelse return PyError.Propagate;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can't deallocate this slice so what's the reason this API returns sentinel terminated slice? Or should we prefer that in other APIs as well

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where the slice is indeed null terminated, I think it's more accurate to report it as a null terminated slice. That captures that there are indeed (slice.len + 1) bytes associated with that pointer. If a user needs to pass that slice into some other function that requires null termination, then they know that it already is.

@gatesn gatesn merged commit 4feba07 into develop Sep 1, 2023
@gatesn gatesn deleted the ngates/fix-str-nulls branch September 1, 2023 12:45
@gatesn gatesn mentioned this pull request Sep 4, 2023
gatesn added a commit that referenced this pull request Sep 4, 2023
I was mistaken in #6 - strings are in fact immutable but the
(undocumented) PyUnicode_Append function steals a reference to the LHS.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants