[SOLVED] Is a way encode (rustc-serialize) u8 array same as acsii string?


Is a way encode (use rustc-serialize) u8 array same as acsii string? I think re impl trait Encodable for [u8, 20] maybe working; but I don’t how todo this, can anyone give me some help?


Shouldn’t this just work? The trait you describe is implemented for rustc_serialize::Encodable:

impl Encodable for u8 ... impl<T: Encodable> Encodable for [T; 20]

Here is an example:

extern crate rustc_serialize;
use rustc_serialize::{json, base64};
use rustc_serialize::base64::ToBase64;

fn main() {

    let byte_string = b"Hello there!"; 

    // Serialize using `json::encode`
    let encoded = json::encode(&byte_string).unwrap();
    println!("json encoded: {:?}", encoded);
    println!("base64 encoded: {:?}", byte_string.to_base64(base64::STANDARD));

    // Deserialize using `json::decode`
    let decoded: [u8; 12]= json::decode(&encoded).unwrap();
    println!("decoded: {:?}", decoded);

Here is a playground link.


Thank for you reply; this question is ambiguous not very clear ,because I don’t know how rustc_serialize work at that time.
in short emit_str(unsafe { str::from_utf8_unchecked(&bytes[..]) }) could encode a bytes queue,but rustc_serialize don’t provide 'read_bytes` it couldn’t decode bytes queue without hack;