summary refs log tree commit diff
path: root/library/std/src
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2021-10-22 21:01:59 +0000
committerbors <bors@rust-lang.org>2021-10-22 21:01:59 +0000
commit514b3877956dc594823106b66c164f8cdbc8b3da (patch)
tree935039e73664f391fb4ccc64ab18240da3666d7b /library/std/src
parent01198792a608b05e624b0127e76dd0753057016c (diff)
parent86c309c27f4632c19a518d6555add44145c2ddac (diff)
downloadrust-514b3877956dc594823106b66c164f8cdbc8b3da.tar.gz
rust-514b3877956dc594823106b66c164f8cdbc8b3da.zip
Auto merge of #90007 - xfix:inline-cstr-from-str, r=kennytm
Inline CStr::from_ptr

Inlining this function is valuable, as it allows LLVM to apply `strlen`-specific optimizations without having to enable LTO.

For instance, the following function:

```rust
pub fn f(p: *const c_char) -> Option<u8> {
    unsafe { CStr::from_ptr(p) }.to_bytes().get(0).copied()
}
```

Looks like this if `CStr::from_ptr` is allowed to be inlined.

```asm
before:
        push    rax
        call    qword ptr [rip + std::ffi::c_str::CStr::from_ptr@GOTPCREL]
        mov     rcx, rax
        cmp     rdx, 1
        sete    dl
        test    rax, rax
        sete    al
        or      al, dl
        jne     .LBB1_2
        mov     dl, byte ptr [rcx]
.LBB1_2:
        xor     al, 1
        pop     rcx
        ret

after:
        mov     dl, byte ptr [rdi]
        test    dl, dl
        setne   al
        ret
```

Note that optimization turned this from O(N) to O(1) in terms of performance, as LLVM knows that it doesn't really need to call `strlen` to determine whether a string is empty or not.
Diffstat (limited to 'library/std/src')
-rw-r--r--library/std/src/ffi/c_str.rs1
1 files changed, 1 insertions, 0 deletions
diff --git a/library/std/src/ffi/c_str.rs b/library/std/src/ffi/c_str.rs
index cb09717bde5..3cb3f480de3 100644
--- a/library/std/src/ffi/c_str.rs
+++ b/library/std/src/ffi/c_str.rs
@@ -1171,6 +1171,7 @@ impl CStr {
     /// }
     /// # }
     /// ```
+    #[inline]
     #[must_use]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {