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

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`

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);
}

Related

Reusing a moved variable for warp filters [duplicate]

This question already has answers here:
Warp filter moving variable out of its environment [duplicate]
(2 answers)
Is there another option to share an Arc in multiple closures besides cloning it before each closure?
(2 answers)
Closed 2 years ago.
I want to use Rust and Juniper to create a GraphQL server. This server has to access the database.
I've been trying to follow this example code from Juniper but it uses an empty Context to give over to the Schema; I need to send a pool for database connections.
I want to be able to connect to the GraphQL via POST, GET and websockets.
type RepositoryPool = r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
fn graphql(
db_pool: RepositoryPool,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
let state = warp::any().map(move || Context::new(db_pool.clone()));
let root_node = Arc::new(schema());
let graphql_filter = make_graphql_filter(schema(), state.boxed());
let post_filter = warp::post()
.and(warp::body::content_length_limit(1024 * 16))
.and(graphql_filter.clone());
let get_filter = warp::get().and(graphql_filter);
let ws_filter = warp::ws().map(move |ws: warp::ws::Ws| {
let root_node = root_node.clone();
let db_pool = db_pool.clone();
ws.on_upgrade(move |websocket| async move {
serve_graphql_ws(
websocket,
root_node,
ConnectionConfig::new(Context::new(db_pool)),
)
.map(|r| {
if let Err(e) = r {
println!("Websocket error: {}", e);
}
})
.await
})
});
warp::path("graphql").and(get_filter.or(post_filter).or(ws_filter))
}
However, I get an error:
error[E0382]: use of moved value: `db_pool`
--> src\filters.rs:39:34
|
27 | db_pool: RepositoryPool,
| ------- move occurs because `db_pool` has type `r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>`, which does not implement the `Copy` trait
28 | ) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
29 | let state = warp::any().map(move || Context::new(db_pool.clone()));
| ------- ------- variable moved due to use in closure
| |
| value moved into closure here
...
39 | let ws_filter = warp::ws().map(move |ws: warp::ws::Ws| {
| ^^^^^^^^^^^^^^^^^^^^^^^ value used here after move
40 | let root_node = root_node.clone();
41 | let db_pool = db_pool.clone();
| ------- use occurs due to use in closure
I don't understand enough about the way these values are moved to solve this issue. How do I solve issues like this?
Thanks to some comments, I figured out a way that the Rust compiler accepts:
fn graphql(
db_pool: RepositoryPool,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
let db_pool_clone = db_pool.clone();
let state = warp::any().map(move || Context::new(db_pool_clone.clone()));
let root_node = Arc::new(schema());
let graphql_filter = make_graphql_filter(schema(), state.boxed());
let post_filter = warp::post()
.and(warp::body::content_length_limit(1024 * 16))
.and(graphql_filter.clone());
let get_filter = warp::get().and(graphql_filter);
let ws_filter = warp::ws().map(move |ws: warp::ws::Ws| {
let root_node = root_node.clone();
let db_pool = db_pool.clone();
ws.on_upgrade(move |websocket| async move {
serve_graphql_ws(
websocket,
root_node,
ConnectionConfig::new(Context::new(db_pool)),
)
.map(|r| {
if let Err(e) = r {
println!("Websocket error: {}", e);
}
})
.await
})
});
warp::path("graphql").and(get_filter.or(post_filter).or(ws_filter))
}
I don't fully understand why this is necessary, but it works for now.

Rust Lifetime of returned value should be equal to the struct lifetime

Let's suppose I have code like this:
struct Struct0 {
s1: Struct1,
v: Vec<Box<dyn Tr>>
}
impl Struct0 {
fn a(&mut self) {
self.v = self.s1.func();
}
}
struct Struct1 {}
impl<'a> Struct1 {
fn func(&'a self) -> Vec<Box<dyn Tr + 'a>> {
vec![Box::new(Struct2 { some_reference: &self } )]
}
}
trait Tr {
//...
}
struct Struct2<'a> {
some_reference: &'a Struct1
}
impl Tr for Struct2<'_> {
//...
}
fn main() {
}
This gives the following error:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/main.rs:8:26
|
8 | self.v = self.s1.func();
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 7:5...
--> src/main.rs:7:5
|
7 | / fn a(&mut self) {
8 | | self.v = self.s1.func();
9 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:8:18
|
8 | self.v = self.s1.func();
| ^^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/main.rs:8:18
|
8 | self.v = self.s1.func();
| ^^^^^^^^^^^^^^
= note: expected `std::vec::Vec<std::boxed::Box<(dyn Tr + 'static)>>`
found `std::vec::Vec<std::boxed::Box<dyn Tr>>`
I would like to tell the Rust compiler that that the lifetime of the returned value should be the lifetime of the Struct1. That vector (with its values) should live as long as the struct from which that method is called. How can I say that?

"cannot infer an appropriate lifetime" when using a closure to return a reference to an enum variant's content

I have a function that accepts a reference to an enum, which I need to parse by matching the enum and reading its content. One of the variants of the enum (not in the simplified minimal working example below), may contain as value the type of the enum itself, therefore I may need to recursively call the same function to parse its value.
I would like to write a function that acts as a filter and returns an Option::Some containing a reference to the content of the enum variant, or None if the value must be discarded.
What follows is a minimal working (not-really compiling) example:
enum Data<'a> {
Value(&'a String),
Null,
}
fn main() {
let s = String::new();
let d = Data::Value(&s);
let equal = |d: &Data| -> Option<&String> {
if let Data::Value(s) = d {
Some(s)
} else {
None
}
};
parse(&d, equal);
//parse(&d, equal_filter);
}
fn equal_filter<'a>(d: &'a Data) -> Option<&'a String> {
if let Data::Value(s) = d {
Some(s)
} else {
None
}
}
fn parse<'a, F>(data: &Data<'a>, filter: F)
where
F: Fn(&Data<'a>) -> Option<&'a String>,
{
filter(data);
}
Playground.
I tried to compile the code by using a closure first, but in that case I get the error:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:11:33
|
11 | if let Data::Value(s) = d {
| ^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 10:17...
--> src/main.rs:10:17
|
10 | let equal = |d: &Data| -> Option<&String> {
| _________________^
11 | | if let Data::Value(s) = d {
12 | | Some(s)
13 | | } else {
14 | | None
15 | | }
16 | | };
| |_____^
= note: ...so that the types are compatible:
expected &Data<'_>
found &Data<'_>
note: but, the lifetime must be valid for the expression at 18:5...
--> src/main.rs:18:5
|
18 | parse(&d, equal);
| ^^^^^
note: ...so that a type/lifetime parameter is in scope here
--> src/main.rs:18:5
|
18 | parse(&d, equal);
| ^^^^^
So I tried with a function, but a got another error:
error[E0271]: type mismatch resolving `for<'r> <for<'a, 's> fn(&'a Data<'s>) -> std::option::Option<&'a std::string::String> {equal_filter} as std::ops::FnOnce<(&'r Data<'_>,)>>::Output == std::option::Option<&std::string::String>`
--> src/main.rs:19:5
|
19 | parse(&d, equal_filter);
| ^^^^^ expected bound lifetime parameter, found concrete lifetime
|
note: required by `parse`
--> src/main.rs:30:1
|
30 | / fn parse<'a, F>(data: &Data<'a>, filter: F)
31 | | where
32 | | F: Fn(&Data<'a>) -> Option<&'a String>,
33 | | {
34 | | filter(data);
35 | | }
| |_^
I would prefer to solve the issue using the closure, but I don't know how to proceed even by using the function.
Ultimately, this is caused due to limitations in Rust's type inference. Specifically, if a closure is passed immediately to a function that uses it, the compiler can infer what the argument and return types are. Unfortunately, when it is stored in a variable before being used, the compiler does not perform the same level of inference.
Inline your closure and it works:
enum Data<'a> {
Value(&'a String),
Null,
}
fn main() {
let s = String::new();
let d = Data::Value(&s);
parse(&d, |d| match d {
Data::Value(s) => Some(s),
_ => None,
});
}
fn parse<'a, F>(data: &Data<'a>, filter: F)
where
F: Fn(&Data<'a>) -> Option<&'a String>,
{
filter(data);
}
However, I'd encourage you to instead create methods on the enum and participate in the idiomatic set of conversion functions:
enum Data<'a> {
Value(&'a String),
Null,
}
impl<'a> Data<'a> {
fn as_value(&self) -> Option<&'a str> {
match self {
Data::Value(s) => Some(s),
_ => None,
}
}
}
fn main() {
let s = String::new();
let d = Data::Value(&s);
parse(&d, Data::as_value);
}
fn parse<'a, F>(data: &Data<'a>, filter: F)
where
F: Fn(&Data<'a>) -> Option<&'a str>,
{
filter(data);
}
Your function variant doesn't work because you've put the relevant lifetime in the wrong place:
// Wrong
fn equal_filter<'a>(d: &'a Data) -> Option<&'a String>
// Right
fn equal_filter<'a>(d: &Data<'a>) -> Option<&'a String>
Using either #[deny(elided_lifetimes_in_paths)] or #[deny(rust_2018_idioms)] will guide you to this:
error: hidden lifetime parameters in types are deprecated
--> src/main.rs:12:22
|
12 | let equal = |d: &Data| -> Option<&String> {
| ^^^^- help: indicate the anonymous lifetime: `<'_>`
|
error: hidden lifetime parameters in types are deprecated
--> src/main.rs:24:28
|
24 | fn equal_filter<'a>(d: &'a Data) -> Option<&'a String> {
| ^^^^- help: indicate the anonymous lifetime: `<'_>`
See also:
How to declare a lifetime for a closure argument?

Why can't I return an explicitly-typed Result enum from a function?

Simple code as below:
fn main() {
let R1 = TestResult(10, 20);
match R1 {
Ok(value) => println!("{}", value),
Err(error) => println!("{}", error),
}
}
fn TestResult(a1: i32, a2: i32) -> Result<i32, String> {
if a1 > a2 {
//Compile Pass
//Ok(100)
//Compile with error why ?
std::result::Result<i32, std::string::String>::Ok(100)
} else {
Err(String::from("Error Happens!"))
}
}
I get the error
error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `,`
--> src/main.rs:15:32
|
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^ expected one of 8 possible tokens here
error[E0423]: expected value, found enum `std::result::Result`
--> src/main.rs:15:9
|
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^^^^^^^^^^^^^^^^^^^
|
= note: did you mean to use one of the following variants?
- `std::result::Result::Err`
- `std::result::Result::Ok`
error[E0423]: expected value, found builtin type `i32`
--> src/main.rs:15:29
|
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^^^ not a value
error[E0308]: mismatched types
--> src/main.rs:15:9
|
9 | fn TestResult(a1: i32, a2: i32) -> Result<i32, String> {
| ------------------- expected `std::result::Result<i32, std::string::String>` because of return type
...
15 | std::result::Result<i32, std::string::String>::Ok(100)
| ^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found bool
|
= note: expected type `std::result::Result<i32, std::string::String>`
found type `bool`
I'm using Rust 1.26.0.
Because that's a syntax error. The correct syntax uses the turbofish (::<>) on the enum variant:
std::result::Result::Ok::<i32, std::string::String>(100)
You also shouldn't use an explicit type unless you really need it — it's not idiomatic. Rust variables and functions use snake_case.
fn main() {
let r1 = test_result(10, 20);
match r1 {
Ok(value) => println!("{}", value),
Err(error) => println!("{}", error),
}
}
fn test_result(a1: i32, a2: i32) -> Result<i32, String> {
if a1 > a2 {
Ok(100)
} else {
Err(String::from("Error Happens!"))
}
}

What is wrong with borrowing self in classic singly-linked list implementation [duplicate]

This question already has answers here:
"borrowed value does not live long enough" seems to blame the wrong thing
(2 answers)
Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time
(4 answers)
Closed 5 years ago.
I am a newcomer to the huge world of Rust. I have been learning it for a week and got some concept going, however something is a bit wrong with my classic implementation of singly-linked list and it is connected with borrowing and my lack of understanding of lifetimes. Here is the code:
use std::fmt::Display;
#[derive(Debug)]
struct Node<T> {
payload: T,
next: Option<Box<Node<T>>>
}
impl<T> Node<T>
where T: Display + PartialEq {
fn new(payload: T, next: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {
Some(Box::new(Node {
payload,
next
}))
}
fn print_nodes(&mut self) {
let this = self;
loop {
match this.next {
Some(_) => {
print!("{} -> ", &this.payload);
}
None => {
print!("{}", &this.payload);
break;
}
}
this = &mut this.next.unwrap();
}
}
}
fn main() {
let a = Node::new(String::from("hello"), None);
let b = Node::new(String::from("hey"), a);
let mut d = b.unwrap();
d.print_nodes();
}
Here is the error I get:
error[E0597]: borrowed value does not live long enough
--> main.rs:31:43
|
31 | this = &mut this.next.unwrap();
| ------------------^ temporary value dropped here while still borrowed
| |
| temporary value created here
32 | }
33 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
error[E0507]: cannot move out of borrowed content
--> main.rs:31:25
|
31 | this = &mut this.next.unwrap();
| ^^^^ cannot move out of borrowed content
error[E0384]: cannot assign twice to immutable variable `this`
--> main.rs:31:13
|
20 | let this = self;
| ---- first assignment to `this`
...
31 | this = &mut this.next.unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
I would be grateful if somebody could explain my mistake and recommend something to fix this.

Resources