0

I am doing this at the moment, it works but feels very wrong:

    type Writer = Vec::<u8>;

    fn new_writer() -> Writer {
        Vec::<u8>::new()
    }

    pub trait BufferWriter {
        fn write_exact(&mut self, buf: &[u8]);
    }

    impl BufferWriter for Vec::<u8> {
        fn write_exact(&mut self, buf: &[u8]) {
            for byte in buf {
                self.push(*byte);
            }
        }
    }
...
    // Serializing into the buffer is awkward, with too many copies going on...
    use byteorder::{LittleEndian, ByteOrder};
    let mut buf: [u8; 8] = [0; 8];
    <LittleEndian>::write_u64(&mut buf, num);
    w.write_exact(&buf)  

There has to be a better way, right?

1 Answers1

0

Uhm! I think this ia what I need:

http://strymon.systems.ethz.ch/reconstruction/byteorder/trait.WriteBytesExt.html#examples

use byteorder::{BigEndian, WriteBytesExt};

let mut wtr = vec![];
wtr.write_u16::<BigEndian>(517).unwrap();
wtr.write_u16::<BigEndian>(768).unwrap();
assert_eq!(wtr, vec![2, 5, 3, 0]);

That should allow me to simplify the code above and remove the ad-hoc implementation.