rust-lang / rust-lang/rust

Converting `Cow<'_, str>` to `Cow<'_, [u8]>` should (?) be a no-op but isn't

Open
#162,793 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-codegen A-LLVM C-optimization I-slow needs-triage
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Godbolt link

Currently,

use std::borrow::Cow;

#[unsafe(no_mangle)]
pub fn str_to_bytes<'a>(x: Cow<'a, str>) -> Cow<'a, [u8]> {
    match x {
        Cow::Owned   (x) => Cow::Owned   (x.into_bytes()),
        Cow::Borrowed(x) => Cow::Borrowed(x.as_bytes  ()),
    }
}

compiles to

str_to_bytes:
        mov     rax, rdi
        cmp     qword ptr [rsi], -1
        je      .LBB0_2
        mov     rcx, qword ptr [rsi + 16]
        mov     qword ptr [rax + 16], rcx
        movups  xmm0, xmmword ptr [rsi]
        movups  xmmword ptr [rax], xmm0
        ret
.LBB0_2:
        movups  xmm0, xmmword ptr [rsi + 8]
        movups  xmmword ptr [rax + 8], xmm0
        mov     qword ptr [rax], -1
        ret

As far as I understand, Cow<'_, str> and Cow<'_, [u8]> have the exact same layout, so the conversion should be effectively a transmute.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the example from the linked Godbolt page and compare the generated assembly for the Cow conversion. Then trace the relevant Rust compiler code-generation or optimization path for Cow to Cow<[u8]>. Done means determining whether the conversion can be emitted as a no-op and recording the resulting behavior in an appropriate regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.