Home > Mobile >  Create array reference to sub slice
Create array reference to sub slice

Time:02-23

I have a slice of data and want to create an array reference for a fixed-size subslice:

let slice: &[u8] = &[1, 2, 3, 4, 5];
let array_ref: &[u8; 2] = &slice[..2];

Unfortunately, this doesn't work because the type of &[..2] is &[u8] instead of &[u8; 2].

I know about <&[u8; 2]>::try_from(slice), but that incurs a runtime check where I would prefer to use an API that doesn't do this runtime check since I know at runtime that the size requirement is fulfilled.

Is there any API that allows this?

CodePudding user response:

In this case, when the slice index is available at compile-time, try_from will be optimized out. We can check this directly in the playground:

pub fn split_two(slice: &[u8]) -> &[u8; 2] {
    slice[..2].try_into().unwrap()
}

Corresponding assembly:

playground::split_two:
    cmpq    $1, %rsi
    jbe .LBB0_1
    movq    %rdi, %rax
    retq

.LBB0_1:
    pushq   %rax
    leaq    .L__unnamed_1(%rip), %rdx
    movl    $2,            
  • Related