Skip to content

Commit 9ea6150

Browse files
authored
Auto merge of #305 - cactter:master, r=emilio
Shrink unsafe block In this function you use the unsafe keyword for almost the entrie function body. We need to mark unsafe operations more precisely using unsafe keyword. Keeping unsafe blocks small can bring many benefits. For example, when mistakes happen, we can locate any errors related to memory safety within an unsafe block. This is the balance between Safe and Unsafe Rust. The separation is designed to make using Safe Rust as ergonomic as possible, but requires extra effort and care when writing Unsafe Rust. Hope this PR can help you. Best regards. **References** https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html
2 parents 53ace36 + d23eb49 commit 9ea6150

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/macros.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -152,22 +152,22 @@ pub fn _cssparser_internal_to_lowercase<'a>(
152152
input: &'a str,
153153
first_uppercase: usize,
154154
) -> &'a str {
155-
unsafe {
155+
156156
// This cast doesn't change the pointer's validity
157157
// since `u8` has the same layout as `MaybeUninit<u8>`:
158-
let input_bytes = &*(input.as_bytes() as *const [u8] as *const [MaybeUninit<u8>]);
158+
let input_bytes = unsafe { &*(input.as_bytes() as *const [u8] as *const [MaybeUninit<u8>]) };
159159

160160
buffer.copy_from_slice(&*input_bytes);
161161

162162
// Same as above re layout, plus these bytes have been initialized:
163-
let buffer = &mut *(buffer as *mut [MaybeUninit<u8>] as *mut [u8]);
163+
let buffer = unsafe { &mut *(buffer as *mut [MaybeUninit<u8>] as *mut [u8]) };
164164

165165
buffer[first_uppercase..].make_ascii_lowercase();
166166
// `buffer` was initialized to a copy of `input`
167167
// (which is `&str` so well-formed UTF-8)
168168
// then ASCII-lowercased (which preserves UTF-8 well-formedness):
169-
::std::str::from_utf8_unchecked(buffer)
170-
}
169+
unsafe { ::std::str::from_utf8_unchecked(buffer) }
170+
171171
}
172172

173173
Some(

0 commit comments

Comments
 (0)