# Why not impl TryFrom\<Vec\<u8\>\> for String?

**URL:** <https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078>\
**Category:** libs\
**Created:** [December 25, 2023, 1:18am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078 "2023-12-25T01:18:50Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![stackinspector](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/stackinspector/32/9487_2.png) [@stackinspector](https://internals.rust-lang.org/u/stackinspector)\
**Post date:** [December 25, 2023, 1:18am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/1 "2023-12-25T01:18:50Z")

</div>

And `TryFrom<&[u8]> for &str`, `TryFrom<Box<[u8]>> for Box<str>`.

---

<div class="post-metadata">

**Author:** ![stackinspector](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/stackinspector/32/9487_2.png) [@stackinspector](https://internals.rust-lang.org/u/stackinspector)\
**Post date:** [December 25, 2023, 1:23am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/2 "2023-12-25T01:23:34Z")

</div>

At first I realized that there is no direct way to convert `Box<[u8]>` to `Box<str>`, although there are `String::from_utf8` and `core::str::from_utf8`. Then I tried to look at TryFrom and found that none of these are implemented.

---

<div class="post-metadata">

**Author:** ![stackinspector](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/stackinspector/32/9487_2.png) [@stackinspector](https://internals.rust-lang.org/u/stackinspector)\
**Post date:** [December 25, 2023, 2:18am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/3 "2023-12-25T02:18:12Z")

</div>

> [@stackinspector](#):
>
> there is no direct way to convert `Box<[u8]>` to `Box<str>`

There is `alloc::str::from_boxed_utf8_unchecked`, but not safe version.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jrose/32/9591_2.png) [@jrose](https://internals.rust-lang.org/u/jrose)\
**Post date:** [December 25, 2023, 2:28am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/4 "2023-12-25T02:28:22Z")

</div>

(Just to make sure you considered it, you can losslessly go Box\<[u8]\> -\> Vec\<u8\> -\> String -\> Box\<str\>. But that certainly isn’t “direct”.)

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [December 25, 2023, 2:45am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/5 "2023-12-25T02:45:17Z")

</div>

Everything in the universe _can_ be implemented with `TryFrom`, but that doesn't mean it _should_ be.

Just like how `&str` -\> `&[u8]` is called [`.as_bytes()`](https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes) not `.into()`, it's intentional that this isn't done via `TryFrom`. In particular, it's important to distinguish between "look for a BOM and try to decode" or various other such things.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [December 25, 2023, 2:45am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/6 "2023-12-25T02:45:25Z")

</div>

There doesn't seem to be a `TryFrom` impl for `Vec<u8> -> String`, either, so that'd be a bit more of an API addition than just another function.

I would think a PR to add a non-unchecked version of `std::str::from_boxed_utf8_unchecked` should be an easy accept and stabilize after riding the trains for a cycle or two.

... Actually, the relevant difference is that a `Box`-converting version wants to return the box on validation failure, whereas the borrowing versions don't need to do this. `FromUtf8Error` returns the bytes as `Vec`, which wouldn't be an unnecessary copy, but it's an extra axis of API complexity to decide on.

I'd probably argue to just use the existing `FromUtf8Error`, e.g.

```rust
pub fn from_boxed_utf8(v: Box<[u8]>) -> Result<&str, FromUtf8Error> {
    match run_utf8_validation(&v) {
        Ok(_) => {
            // SAFETY: validation succeeded.
            Ok(unsafe { from_boxed_utf8_unchecked(v) })
        }
        Err(error) => Err(FromUtf8Error { bytes: v.into(), error }),
    }
}

```

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 25, 2023, 3:10am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/7 "2023-12-25T03:10:41Z")

</div>

> [@scottmcm](#):
>
> Just like how `&str` -\> `&[u8]` is called [`.as_bytes()`](https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes) not `.into()`

[It's also called `.as_ref()`](https://doc.rust-lang.org/std/primitive.str.html#impl-AsRef%3C%5Bu8%5D%3E-for-str). I think that in an ideal world, `AsRef` impls should imply the corresponding `From`. [(Recent Zulip discussion)](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/.60std.60.20conversion.20traits.20are.20a.20mess)

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [December 25, 2023, 4:03am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/8 "2023-12-25T04:03:15Z")

</div>

> [@Jules-Bertholet](#):
>
> I think that in an ideal world, `AsRef` impls should imply the corresponding `From`.

I think that `From` impls should imply the other-direction `TryFrom`, and thus contrapositively since I'm not a fan of `TryFrom<&[u8]> for &str`, I don't think that the other direction should be a `From` either.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [December 25, 2023, 4:39am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/9 "2023-12-25T04:39:33Z")

</div>

The key observation is that while there's only one way to go `&str -> &[u8]` (inspect the bytes), there's multiple ways to go `&[u8] -> String`\[1\] (what encoding are the bytes in?). A `From` implementation should be total and ideally information preserving (injective), but while that implies that a (non-total) inverse function exists, it doesn't necessarily imply that it's a natural mapping the way the forward function is. It certainly suggests that it probably would be, but it's not always the case.

Though this kind of case where you're covering to/from a canonical underlying encoding or various other interchange formats is basically the only case I can think of where one direction is "inherently natural" but the other direction isn't. Most other cases (e.g. the scalar part of a measure vector) are sufficiently ambiguous that a [`Try`]`From` implementation would be questionable in either direction. If `&str` weren't so primitive in exposing its representation directly, and instead it were e.g. `encode_utf8` instead, it'd clearly be the same way, but `&str` _is_ at a fundamental level "just" a fancy `&[u8]`.

* * *

1. There's only one way to go `&[u8] -> &str` due to the "already present data" requirement of borrowing. If you allow creating an owned string, however, it could decode from any encoding, be lossy or not, etc.

---

<div class="post-metadata">

**Author:** ![stackinspector](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/stackinspector/32/9487_2.png) [@stackinspector](https://internals.rust-lang.org/u/stackinspector)\
**Post date:** [December 25, 2023, 11:36am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/10 "2023-12-25T11:36:01Z")

</div>

> [@CAD97](#):
>
> but `&str` _is_ at a fundamental level "just" a fancy `&[u8]`

An additional question: Why `str` a primitive type rather than a simple `struct str { bytes: [u8] }`? It doesn't seem to be anything special or magic, not even as special as [Special types and traits](https://doc.rust-lang.org/reference/special-types-and-traits.html) which can be defined directly in std, and UTF-8 guarantee is at API level (same as String).

---

<div class="post-metadata">

**Author:** ![Nemo157](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nemo157/32/11585_2.png) [@Nemo157](https://internals.rust-lang.org/u/Nemo157)\
**Post date:** [December 25, 2023, 11:56am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/11 "2023-12-25T11:56:11Z")

</div>

That has been tried multiple times, the latest is

> <https://github.com/rust-lang/rust/pull/107939>
>
> Along the same vein as #70911 and #19612, though I only discovered those attempt…s after finishing this one, so the approach is probably slightly different.
> 
> Still somewhat broken, specifically:
> \* \[\] codegen tests need blessing
> \* \[\] symbol mangling code/tests needs discussion, review, and blessing
> \* \[\] Bunch of \`FIXME(str)\` should be addressed or OK'd for later work/librarification efforts
> 
> I wanted to open this mostly to bring back discussion and solicit some early reviews.
> 
> cc @rust-lang/compiler and @rust-lang/libs-api who might care about this being revived
> 
> r? @ghost

The primary blocker afaiu is compiler performance.

---

<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:** [March 24, 2024, 11:56am UTC](https://internals.rust-lang.org/t/why-not-impl-tryfrom-vec-u8-for-string/20078/12 "2024-03-24T11:56:15Z")

</div>

Closed on March 24, 2024, 11:56am UTC

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