I want to play with BasicAuth stuff, therefore I need the base64 version of a string. So I needed a function : String to base_64(String).
In the string guides for Rust, most of the time $str is preferred to String. So I wanted to adjust to this idea.
But working with &str is somehow harder than it seems (I know that my problem is related to Question also about as_slice()).
The author of other question could solve his problem by not using as_slice(), is there a way to still work with &str for me?
extern crate serialize;
use serialize::base64::{ToBase64,MIME};
fn generate_base_string (n : &str) -> String {
let mut config = serialize::base64::MIME;
config.line_length = None;
let bytes: & [u8] = n.as_bytes();
return bytes.to_base64(config);
}
fn generate_base<'a> (n : &'a str ) -> &'a str {
let mut config = serialize::base64::MIME;
config.line_length = None;
let bytes: & [u8] = n.as_bytes();
let res2: String = bytes.to_base64(config);
let res1: &'a str = res2.as_slice();
return res1;
}
#[test]
fn right_base64() {
let trig :&str = generate_base("string");
assert!(trig=="c3RyaW5n");
}
// http://doc.rust-lang.org/guide-strings.html
#[test]
fn right_base64_string(){
// A `String` - a heap-allocated string
assert!(generate_base_string("string")=="c3RyaW5n".to_string());
}
These are my first baby steps in Rust so please be not to mean if I do something really wrong.