Skip to content

Bound checking elided for [index] but not for [..index] #73396

Closed
@tesuji

Description

@tesuji

I tried this code: https://rust.godbolt.org/z/ihbmwB

pub fn foo(s: &[u8]) -> &[u8] {
    if let Some(idx) = s.iter().position(|b| *b == b'\\') {
        &s[..idx]
    } else {
        s
    }
}

I expected to see this happen: There is no bound check for s[..idx] in line 3.

Instead, this happened: There is bound check.

Note using s[idx] bound check is elided:

pub fn bar(s: &[u8]) -> u8 {
    if let Some(idx) = s.iter().position(|b| *b == b'\\') {
        s[idx]
    } else {
        42
    }
}

cc #30112

Meta

rustc --version --verbose: rustc 1.46.0-nightly (4fb54ed 2020-06-14)

rustc 1.46.0-nightly (4fb54ed48 2020-06-14)
binary: rustc
commit-hash: 4fb54ed484e2239a3e9eff3be17df00d2a162be3
commit-date: 2020-06-14
host: x86_64-unknown-linux-gnu
release: 1.46.0-nightly
LLVM version: 10.0

Metadata

Metadata

Assignees

Labels

A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions