rust


How do I convert a Vector of bytes (u8) to a string


I am trying to write simple TCP/IP client in Rust and I need to print out the buffer I got from the server. How do I convert the u8 vector to a String for printing?
To convert a slice of bytes to a string slice (assuming a UTF-8 encoding):
use std::str;
//
// pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
//
// Assuming buf: &[u8]
//
fn main() {
let buf = &[0x41u8, 0x41u8, 0x42u8];
let s = match str::from_utf8(buf) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
println!("result: {}", s);
}
The conversion is in-place, and does not require an allocation. You can create a String from the slice if necessary.
The library reference for the conversion function:
std::str::from_utf8
I prefer String::from_utf8_lossy:
fn main() {
let buf = &[0x41u8, 0x41u8, 0x42u8];
let s = String::from_utf8_lossy(buf);
println!("result: {}", s);
}
It turns invalid UTF-8 bytes into � and so no error handling is required. It's good for when you don't need that and I hardly need it. You actually get a String from this. It should make printing out what you're getting from the server a little easier.
Sometimes you may need to use the into_owned() method since it's clone on write.
If you actually have a vector of bytes (Vec<u8>) and want to convert to a String, the most efficient is to reuse the allocation with String::from_utf8:
fn main() {
let bytes = vec![0x41, 0x42, 0x43];
let s = String::from_utf8(bytes).expect("Found invalid UTF-8");
println!("{}", s);
}

Related Links

inspect rust traits at runtime
Enums with constructions in Rust
How can I unify the lifetimes between a struct and a trait?
PNaCl support for Rust
Store value in struct through trait
Rust not running helloworld example
Why does #[derive(Show)] not work anymore?
How do lifetime bounds on structs work in Rust?
Rust - how to retrieve a user-defined type from for loop
rust: error: macro undefined: 'fail!'
Match String Tuple in Rust
How can I make a structure with internal references?
Iterating over the contents of an Option, or over a specific value
Why do executables have a dependency on glibc?
How do I create a global, mutable singleton?
How do you create an iterator using a closure in rust?

Categories

HOME
oracle
ontouchlistener
android-fragments
couchdb
softlayer
redmine
google-webmaster-tools
liferay-7
mithril.js
scheduler
roku
mutation-testing
createjs
exchange-server-2010
software-packaging
vuforia
firemonkey-style
strophe.js
android-service
basic-authentication
monitor
mapnik
quick-nimble
sca
restful-architecture
xerces-c
des
cargo
django-smart-selects
opal-framework
code-push
doctrine-extensions
react-intl
bit-shift
jenkins-slave
dredd
icecast
android-5.0-lollipop
password-hash
iptv
android-webservice
algebra
lvalue
dblink
rustdoc
bpms
oracle-fusion-apps
boost-compute
haraka
google-identity-toolkit
s-function
data-management
clp
wininet
android-4.2-jelly-bean
frame-grab
currency-exchange-rates
onepage-checkout
management-studio-express
m4
phpquery
bjam
canopy
360-degrees
dynamics-ax-2012-r2
gflags
shell-extensions
jcheckbox
google-hangouts
dnsjava
igor
object-code
jack
facebook-game-groups
jmenubar
notin
axacropdf
delphi-xe4
linkbutton
popup-blocker
fitch-proofs
netstream
expression-web
glassfish-esb
django-pagination
channelfactory
solandra
data-retrieval
gtktextview
comment-conventions

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App