#writable trait

15 messages · Page 1 of 1 (latest)

fringe cape
#

Is there a trait in std that marks things that know how to write themselves to a writer? This includes things that write non-printable bytes. Display doesn't seem at all correct for this, and neither does Debug.

broken kelp
#

std::fmt::Write is for utf-8, which is probably what you saw, but std::io::Write is for bytes.

#

Er, actually you want Read

fringe cape
#

std::io::Write is the trait for things that you can write into. I'm looking for a trait for things that know how to write themselves into a Write

broken kelp
#

If you want something more lightweight, implementing AsRef<[u8]> is usually good enough. Of course that only works if the data isn't being generated.

fringe cape
#

so this is a typical struct that I want to write:

struct BPBytes<'a> {
    version: &'a u8,
    data: &'a[u8],
}
broken kelp
#

Does Read not work for this?

#

Might need an intermediate struct to hold progress info

fringe cape
#

I don't think I'm following. How would implementing Read for this help? I want to write it to a Write. Not read it into a byte slice.

broken kelp
#

If you have a Read and Write, you can use std::io::copy to move one into the other.

fringe cape
#

ah thanks - that makes a bit more sense

#

oh ... ok ... so to implement Read, I need to make a new stateful struct that incrementally and resumably writes my data into the buf: &mut [u8] - this is starting to look more like a project than a quick solutino

broken kelp
#

I think usually you'd do something like:

struct BPBytes<R> {
    version: u8,
    data: R,
}
```where `R` is usually `&mut Read`.
#

You'd make an impl like

impl<R: Read> Read for BPBytes<R>
fringe cape
#

there isn't a derive for Read that I can find