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

Add Safety comments to unsafe blocks #2319

Merged
merged 2 commits into from Nov 28, 2022
Merged

Add Safety comments to unsafe blocks #2319

merged 2 commits into from Nov 28, 2022

Conversation

erickt
Copy link
Member

@erickt erickt commented Nov 9, 2022

This makes some small tweaks to the unsafe blocks to make them easier to audit:

  • It changes serde::de::Format::Buf to be a private type since it's already not publicly exposed.
  • It changes Buf::as_str() to be unsafe, since it relies on the caller to only write UTF-8 into the buffer.
  • It adds // Safety: ... comments to the two callsites in de::Visitor that uses Buf to write an error message with i128 and u128 types.
  • It converts a comment into an explicit // Safety: ... comment.

serde::de::format::Buf is a private type, so this makes it explicit by
declaring the type `pub(super)`. In addition, it marks the function
`Buf::as_str` as unsafe, which lets us document the callsites with
`// Safety: ...` comments to explain why it is safe to use.
This changes a comment to be explicit on how it's safe we can avoid
validating UTF-8.
Buf { bytes, offset: 0 }
}

pub fn as_str(&self) -> &str {
pub(super) unsafe fn as_str(&self) -> &str {
Copy link
Member

Choose a reason for hiding this comment

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

  • It changes Buf::as_str() to be unsafe, since it relies on the caller to only write UTF-8 into the buffer.

The API enforces that the caller only wrote UTF-8 into the buffer.

Buf { bytes, offset: 0 }
}

pub fn as_str(&self) -> &str {
pub(super) unsafe fn as_str(&self) -> &str {
Copy link
Member

Choose a reason for hiding this comment

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

I put up #2329 to be able to merge just your Buf visibility change and your // Safety: ... comment change in src/ser/impls.rs, without the as_str() safety change. We can follow up with a separate PR to document the justification for how as_str() is safe.

Thanks!

@dtolnay dtolnay merged commit 1050f6b into master Nov 28, 2022
@dtolnay dtolnay deleted the safety branch November 28, 2022 01:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants