# TryFrom\<Vec\<u8\>\> for Vec\<NonZeroU8\>?

**URL:** <https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752>\
**Category:** libs\
**Created:** [May 21, 2021, 3:33pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752 "2021-05-21T15:33:13Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [May 21, 2021, 3:33pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/1 "2021-05-21T15:33:14Z")

</div>

Could we have this impl of TryFrom? It'd be very useful. Thanks.

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/skifire13/32/7579_2.png) [@SkiFire13](https://internals.rust-lang.org/u/SkiFire13)\
**Post date:** [May 21, 2021, 4:09pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/2 "2021-05-21T16:09:55Z")

</div>

On nightly this is done in place:

```rust
u8_vec.into_iter().map(TryFrom::try_from).collect::<Result<Vec<NonZeroU8>, _>>()

```

> **[Compiler Explorer - Rust (rustc nightly)](https://godbolt.org/z/v8qP9nfvc)**
>
> use std::convert::TryFrom;
> use std::num::{NonZeroU8, TryFromIntError};
> 
> pub fn nzu8\_vec\_try\_from\_u8\_vec(u8\_vec: Vec) -\> Result, TryFromIntError\> {
> u8\_vec.into\_iter().map(TryFrom::try\_from).collect::, \_\>\>()
> }

---

<div class="post-metadata">

**Author:** ![tcsc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tcsc/32/3806_2.png) [@tcsc](https://internals.rust-lang.org/u/tcsc)\
**Post date:** [May 21, 2021, 11:53pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/3 "2021-05-21T23:53:28Z")

</div>

Not particularly good codegen, to be fair. Presumably a TryFrom impl would do more than a byte-at-a-time check (by delegating to memchr, most likely).

---

<div class="post-metadata">

**Author:** ![Lonami](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/lonami/32/6774_2.png) [@Lonami](https://internals.rust-lang.org/u/Lonami)\
**Post date:** [May 22, 2021, 7:21am UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/4 "2021-05-22T07:21:55Z")

</div>

Interestingly enough, even the following compiles down to a byte-by-byte `cmp`:

```rust
pub fn into_nonzero(vec: Vec<u8>) -> Option<Vec<NonZeroU8>> {
    if vec.iter().all(|x| *x != 0) {
        Some(vec.into_iter().map(|x| unsafe {
            NonZeroU8::new_unchecked(x)
        }).collect())
    } else {
        None
    }
}

```

I would have expected the compiler to do better here (I could see the `TryFrom` inhibiting some optimizations, but this is a plain `all` comparison against 0).

---

<div class="post-metadata">

**Author:** ![tcsc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tcsc/32/3806_2.png) [@tcsc](https://internals.rust-lang.org/u/tcsc)\
**Post date:** [May 22, 2021, 7:25am UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/5 "2021-05-22T07:25:06Z")

</div>

Right, I meant libcore would manually call [rust/memchr.rs at master · rust-lang/rust · GitHub](https://github.com/rust-lang/rust/blob/master/library/core/src/slice/memchr.rs).

Autovectorization is inherently unreliable, especially when it has early returns like this... In this case, I suspect that LLVM doesn't want to read past the first zero byte, since it doesn't know the whole slice is dereferenceable — for all it knows the first byte after zero could fault.

---

<div class="post-metadata">

**Author:** ![Lonami](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/lonami/32/6774_2.png) [@Lonami](https://internals.rust-lang.org/u/Lonami)\
**Post date:** [May 22, 2021, 7:29am UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/6 "2021-05-22T07:29:13Z")

</div>

I'm deviating a bit here, but I would expect the following to compile to something better than a byte-by-byte `cmp`:

```rust
pub fn justcheck(vec: &[u8]) -> bool {
    vec.iter().all(|x| *x != 0)
}

```

> **Assembly on rustc 1.54.0-nightly (4de757209 2021-05-01)**
>
> ```rust
> example::justcheck:
> xor ecx, ecx
> .LBB2_1:
> mov rax, rcx
> cmp rsi, rcx
> je .LBB2_3
> lea rcx, [rax + 1]
> cmp byte ptr [rdi + rax], 0
> jne .LBB2_1
> .LBB2_3:
> cmp rsi, rax
> sete al
> ret
> 
> ```

Maybe if this is fixed the original proposed solution would compile to something better as well?

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/skifire13/32/7579_2.png) [@SkiFire13](https://internals.rust-lang.org/u/SkiFire13)\
**Post date:** [May 22, 2021, 9:33am UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/7 "2021-05-22T09:33:10Z")

</div>

A good alternative to `vec.iter().all(|x| *x != 0)` is `!vec.contains(&0)`, which will call `memchr`. This still needs `unsafe` for converting the vec after the check though.

---

<div class="post-metadata">

**Author:** ![quaternic](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quaternic/32/10440_2.png) [@quaternic](https://internals.rust-lang.org/u/quaternic)\
**Post date:** [May 22, 2021, 1:08pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/8 "2021-05-22T13:08:11Z")

</div>

An alternative that might have been vectorized better would be

```rust
vec.iter().min() != Some(0)

```

Taking that as an idea for manually vectorizing leads to something that could potentially be slightly better than what a more general [memchr](https://github.com/BurntSushi/memchr/blob/e42d0516cfd894eb8ae2681caa9f99168b017b2b/src/memchr/x86/avx.rs#L86) might do, at least if optimizing for the case where finding a zero is rare, and you don't care where it was found. The difference is that when looking for a zero (or -1) you get to accumulate a minimum (maximum for -1) instead of figuring out if you saw the byte in each chunk again.

I couldn't help myself from implementing [https://godbolt.org/z/sz7sKzoKa](https://godbolt.org/z/sz7sKzoKa), where the inner loop that processes 64 bytes per iteration ends up looking like:

```rust
.LBB0_3:
        vpminub ymm1, ymm1, ymmword ptr [rax]
        vpminub ymm0, ymm0, ymmword ptr [rax + 32]
        add rax, 64
        cmp rax, rcx
        jb .LBB0_3

```

This will always read the entire array, but short circuiting could be added with varying levels of tradeoff between different probabilities of finding a zero.

---

<div class="post-metadata">

**Author:** ![burntsushi](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/burntsushi/32/279_2.png) [@burntsushi](https://internals.rust-lang.org/u/burntsushi)\
**Post date:** [May 22, 2021, 1:30pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/9 "2021-05-22T13:30:51Z")

</div>

The bytecount crate might be relevant here.

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [May 22, 2021, 1:47pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/10 "2021-05-22T13:47:18Z")

</div>

Umm...

Optimizations aside, we feel like `TryFrom<Vec<u8>> for Vec<NonZeroU8>` is conceptually nicer than these alternatives, and it can even add position information and whatnot a la `std::ffi::NulError` or `std::str::Utf8Error`.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [August 20, 2021, 1:47pm UTC](https://internals.rust-lang.org/t/tryfrom-vec-u8-for-vec-nonzerou8/14752/11 "2021-08-20T13:47:44Z")

</div>

Closed on August 20, 2021, 1:47pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
