Skip to content

str::into_boxed_bytes

str methods · Strings

Level: reference · for working programmers

One line: Turns a Box<str> into a Box<[u8]> without copying — the same bytes, with the UTF-8 promise dropped.

pub fn into_boxed_bytes(self: Box<Self>) -> Box<[u8]>

Stable since 1.20.0.

Like as_bytes, it costs nothing: a str is already bytes plus a guarantee, and this discards the guarantee. Unlike as_bytes, it is a move — it consumes the Box<str> and hands back ownership of the same allocation.

Defined on Box<str>, so it is boxed.into_boxed_bytes().

The trip back is not free of checks: std::str::from_boxed_utf8_unchecked is unsafe precisely because the promise has to be re-established, and nothing has been validating the bytes in the meantime.

Reach for it when handing owned text to a byte-oriented API — one that wants Box<[u8]> or will convert it to Vec<u8> — without a copy.

Example

str_into_boxed_bytes.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let boxed: Box<str> = String::from("héllo").into_boxed_str();
    println!("{} bytes as str", boxed.len());

    let bytes: Box<[u8]> = boxed.into_boxed_bytes();
    println!("{bytes:?}");
    println!("{} bytes as [u8]", bytes.len());

    // Onward to Vec<u8>, still without copying the contents.
    let v: Vec<u8> = bytes.into_vec();
    println!("{v:?}");

    // The checked trip back.
    println!("{:?}", String::from_utf8(v));

    // The UTF-8 promise really is gone: arbitrary bytes are now representable.
    let invalid: Box<[u8]> = vec![0xff, 0xfe].into_boxed_slice();
    println!("{:?}", std::str::from_utf8(&invalid).is_err());
}

Verified output of str_into_boxed_bytes.rs — regenerated by tools/run_examples.py, never hand-typed.

6 bytes as str
[104, 195, 169, 108, 108, 111]
6 bytes as [u8]
[104, 195, 169, 108, 108, 111]
Ok("héllo")
true

See also

str::into_boxed_bytes in the standard library ↗

Po polsku

into_boxed_bytes nie kopiuje ani jednego bajtu — przejmuje tę samą alokację i zdejmuje z niej jedynie obietnicę, że w środku jest poprawny UTF-8. Przedrostek into_ mówi tu wszystko: to przeniesienie własności (move), a nie pożyczanie jak w as_bytes, więc po wywołaniu Box<str> już nie istnieje i nie da się go użyć ponownie. Najciekawszy jest wydruk z przykładu: „héllo” to pięć znaków, ale sześć bajtów, bo é zajmuje dwa — identyczna pułapka czeka na „ą”, „ś” i „ż”, więc polski tekst prawie nigdy nie ma tylu bajtów, ile liter. Droga powrotna nie jest już darmowa: String::from_utf8 sprawdza bajty i zwraca Result, a std::str::from_boxed_utf8_unchecked jest unsafe, bo obietnicę trzeba odtworzyć na słowo.

Szukaj po polsku: przeniesienie własności · bajty a znaki UTF-8 · rust Box<str> into_boxed_bytes · rust from_boxed_utf8_unchecked