Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encoding to std::io::Write? #258

Open
RandomInsano opened this issue Feb 11, 2025 · 2 comments
Open

Encoding to std::io::Write? #258

RandomInsano opened this issue Feb 11, 2025 · 2 comments

Comments

@RandomInsano
Copy link

I'm providing data directly to a socket. It looks like encode() writes to std::fmt::Write so it must be written to buffer then sent to the socket.

That's serviceable, but seems like a bit of a waste of memory and performance. So, two questions:

  1. Is there a way to write to std::io::Write that I haven't seen? Reviewing the text encoder, it seems like no
  2. Is there any interest in a pull request that would implement this? Maybe as encode_stream() and hide that behind the existing encode() and friends?
@mxinden
Copy link
Member

mxinden commented Feb 12, 2025

I am not aware of an official adapter between the two traits. That said, what is stopping you from writing your own?

use std::io;
use std::fmt;

pub struct IoFmtWriter<W: io::Write>(pub W);

impl<W: io::Write> fmt::Write for IoFmtWriter<W> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.0.write_all(s.as_bytes()).map_err(|_| fmt::Error)
    }
}

If that is indeed an option for you, I would assume others are facing the same issue. If so, would you want to create a pull request with an example to this repository?

@RandomInsano
Copy link
Author

Yeah, that's an excellent idea! I actually moved to using Tokio so I'll include both a sync and asynchronous example. I'll add it to next-week's TODO list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants