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

Remove unsafe code at creditcard.rs #109

Closed
yzhang71 opened this issue Dec 14, 2022 · 4 comments
Closed

Remove unsafe code at creditcard.rs #109

yzhang71 opened this issue Dec 14, 2022 · 4 comments

Comments

@yzhang71
Copy link

yzhang71 commented Dec 14, 2022

Hi team,

From scanning the repo, I detected below unsafe code, and it can be convert to safe version:
unsafe { String::from_utf8_unchecked(bytes) }

unsafe { String::from_utf8_unchecked(bytes) }

Safe version:
String::from_utf8(bytes).unwrap()

@llogiq
Copy link
Collaborator

llogiq commented Dec 19, 2022

We know that the contained values are valid UTF-8, so what does the additional check gain us?

@yzhang71
Copy link
Author

Hi llogiq,

Thanks for replying.

from_utf8() is another function that also converts a slice of bytes to a string slice, but it performs checks on the input to ensure that it is a valid UTF-8 sequence. If the input is not a valid UTF-8 sequence, from_utf8 returns an Err variant of the Result type, which can be handled by the caller.

In general, it is recommended to use from_utf8 over from_utf8_unchecked because it can help catch errors and bugs in your code at runtime. However, if you are certain that the input slice is always going to be a valid UTF-8 sequence, you can use from_utf8_unchecked for a potential performance improvement.

@yzhang71 yzhang71 reopened this Dec 19, 2022
@llogiq
Copy link
Collaborator

llogiq commented Dec 19, 2022

But we do know the string is always valid UTF-8, because it's just digits.

@yzhang71
Copy link
Author

Ok, thanks for confirming. I will close it now.

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

No branches or pull requests

2 participants