tadman
tadman

Reputation: 211590

Convert &[Box<[u8]>] to String or &str

What's an efficient way to convert a result of type &[Box<[u8]>] into something more readily consumed like String or &str?

An example function is the txt_data() method from trust_dns_proto::rr:rdat::txt::TXT.

I've tried several things that seem to go nowhere, like:

fn main() {
    let raw: &[Box<[u8]>] = &["Hello", " world!"]
        .iter()
        .map(|i| i.as_bytes().to_vec().into_boxed_slice())
        .collect::<Vec<_>>();

    let value = raw.iter().map(|s| String::from(*s)).join("");

    assert_eq!(value, "Hello world!");
}

Where raw is of that type.

Upvotes: 1

Views: 1736

Answers (2)

Stargateur
Stargateur

Reputation: 26727

There is no way to convert an array of octets to str directly cause the data is split up. So a String look like a good candidate.

I would use str::from_utf8() combined with try_fold():

use std::str;

fn main() {
    let raw: &[Box<[u8]>] = &["Hello", " world!"]
        .iter()
        .map(|i| i.as_bytes().to_vec().into_boxed_slice())
        .collect::<Vec<_>>();

    let value = raw
        .iter()
        .map(|i| str::from_utf8(i))
        .try_fold(String::new(), |a, i| {
            i.map(|i| {
                let mut a = a;
                a.push_str(i);
                a
            })
        });

    assert_eq!(value.as_ref().map(|x| x.as_str()), Ok("Hello world!"));
}

Upvotes: 3

tadman
tadman

Reputation: 211590

It looks like the solution is this:

let value: String = raw
    .iter()
    .map(|s| String::from_utf8((*s).to_vec()).unwrap())
    .collect::<Vec<String>>()
    .join("");

Where the key is from_utf8() and the (*s).to_vec() suggested by rustc.

Upvotes: 1

Related Questions