Search code examples
websocketrustbinarybson

How to convert Vec<u8> into bson::document::Document?


I'm gonna receive tungstenite::Message which will contain the bson document from the client. I can convert tungstenite::Message into Vec<u8> but How can I convert it back into bson::document::Document on the server side?

Something like this:-

if msg.is_binary() {
   let bin = msg.into_data();
   let doc = mongodb::bson::Document::from_reader(&mut bin); //getting error
}

Error:-

error[E0277]: the trait bound `std::vec::Vec<u8>: std::io::Read` is not satisfied
   --> src/main.rs:52:60
    |
52  |             let doc = mongodb::bson::Document::from_reader(&mut bin);
    |                                                            ^^^^^^^^ the trait `std::io::Read` is not implemented for `std::vec::Vec<u8>`
    | 
   ::: /home/voldimot/.cargo/registry/src/github.com-1ecc6299db9ec823/bson-1.0.0/src/document.rs:530:27
    |
530 |     pub fn from_reader<R: Read + ?Sized>(reader: &mut R) -> crate::de::Result<Document> {
    |                           ---- required by this bound in `bson::document::Document::from_reader`

Solution

  • You can use std::io::Cursor:

    if msg.is_binary() {
       let mut bin = std:::io::Cursor::new(msg.into_data());
       let doc = mongodb::bson::Document::from_reader(&mut bin); 
    }