Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over elements of a struct in Rust?

Tags:

rust

I'm writing a small client/server program for encrypted network communications and have the following struct to allow the endpoints to negotiate capabilities.

struct KeyExchangePacket {
    kexinit: u8,
    replay_cookie: [u8; 32],
    kex_algorithms: String,
    kgen_algorithms: String,
    encryption_algorithms: String,
    mac_algorithms: String,
    compression_algorithms: String,
    supported_languages: String,
}

I need to convert the fields into bytes in order to send them over a TcpStream, but I currently have to convert them one at a time.

send_buffer.extend_from_slice(kex_algorithms.as_bytes());
send_buffer.extend_from_slice(kgen_algorithms.as_bytes());
etc...

Is there a way to iterate over the fields and push their byte values into a buffer for sending?

like image 456
William Murphy Avatar asked Jun 29 '16 23:06

William Murphy


1 Answers

Bincode does this.

let packet = KeyExchangePacket { /* ... */ };
let size_limit = bincode::SizeLimit::Infinite;
let encoded: Vec<u8> = bincode::serde::serialize(&packet, size_limit).unwrap();

From the readme:

The encoding (and thus decoding) proceeds unsurprisingly -- primitive types are encoded according to the underlying Writer, tuples and structs are encoded by encoding their fields one-by-one, and enums are encoded by first writing out the tag representing the variant and then the contents.

like image 132
dtolnay Avatar answered Sep 30 '22 04:09

dtolnay