snapview / tungstenite-rs

Lightweight stream-based WebSocket implementation for Rust.
Apache License 2.0
1.87k stars 215 forks source link

Sending bytes with text opcode #418

Closed dominikdosoudil closed 5 months ago

dominikdosoudil commented 6 months ago

Use case:

I am using tungstenite in a proxy. I receive data as bytes (however I know that it's actually an encoded text). I want to forward that data directly to websocket. Therefor I would like to send Text message however with bytes to avoid redundant decode.

Possible solution I think, that there might be added option to Message enum (e.g. BinaryText) that would accept Vec<u8> (or Bytes) which would be handled on https://github.com/snapview/tungstenite-rs/blob/0fa41973b4c075f5d4a9e03a82a26a301ca31ce9/src/protocol/mod.rs#L441 as Message::BinaryText(data) => Frame::message(data, OpCode::Data(OpData::Text), true),.

I think that this approach might save CPU time thanks to avoiding redundant decoding (in proxy).

daniel-abramov commented 5 months ago

Forwarding this data as Message::Binary does not cause an issue. The "decoding" (converting &[u8] into &str) you would need to perform is not redundant—it's the only way to ensure that a slice of bytes is actually a UTF-8 string. If you're confident that the slice of bytes is a UTF-8 and you really want to skip any validation, you would need to use an unsafe version from_utf8_unchecked() that skips the validation step.