0

In this simplified version of my code, I would like to sometimes execute the marked line and sometimes not, maybe returning an error instead:

extern crate futures; // 0.1.26
extern crate hyper; // 0.12.25

use hyper::rt::{Future, Stream};
use std::str::FromStr;

struct MyStream {}

impl Stream for MyStream {
    type Item = hyper::Uri;
    type Error = ();

    fn poll(&mut self) -> Result<futures::Async<Option<Self::Item>>, Self::Error> {
        Ok(futures::Async::Ready(Some(
            hyper::Uri::from_str("http://www.google.com/").unwrap(),
        )))
    }
}

fn main() {
    let client = hyper::Client::new();
    let futs = MyStream {}
        .map(move |uri| {
            client
                .get(uri)
                .and_then(|res| {
                    res.into_body().concat2() // <----------------
                })
                .map(|body| {
                    println!("len is {}.", body.len());
                })
                .map_err(|e| {
                    println!("Error: {:?}", e);
                })
        })
        .buffer_unordered(2)
        .for_each(|_| Ok(()));

    hyper::rt::run(futs);
}

I thought I could replace the line with something like this:

let do_i_want_to_get_the_full_page = true;
if do_i_want_to_get_the_full_page {
    res.into_body().concat2().map_err(|_| ())
} else {
    futures::future::err(())
}

since the Error parts of the futures are the same, and the Item part could be inferred. However, it does not work. How could I do it?

This is the error I get:

error[E0308]: if and else have incompatible types
  --> src/main.rs:31:25
   |
28 | /                     if do_i_want_to_get_the_full_page {
29 | |                         res.into_body().concat2().map_err(|_| ())
   | |                         ----------------------------------------- expected because of this
30 | |                     } else {
31 | |                         futures::future::err(())
   | |                         ^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `futures::MapErr`, found struct `futures::FutureResult`
32 | |                     }
   | |_____________________- if and else have incompatible types
   |
   = note: expected type `futures::MapErr<futures::stream::Concat2<hyper::Body>, [closure@src/main.rs:29:59: 29:65]>`
              found type `futures::FutureResult<_, ()>`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

2

The problem is that map_err returns a struct MapErr, while err returns a struct FutureResult.

One way to solve your issue is to unify them like this:

let f = if do_i_want_to_get_the_full_page {
    futures::future::ok(())
} else {
    futures::future::err(())
};
f.and_then (|_| { res.into_body().concat2().map_err(|_| ()) })

Another solution is to box your return value:

if do_i_want_to_get_the_full_page {
    Box::<Future<_, _>>::new (res.into_body().concat2().map_err(|_| ()))
} else {
    Box::<Future<_, _>>::new (futures::future::err(()))
}

A third solution is to always return a MapErr:

if do_i_want_to_get_the_full_page {
    res.into_body().concat2().map_err(|_| ())
} else {
    futures::future::err(()).map_err(|_| ())
}

However, then you get an issue because the error type for client.get(…).and_then(…) must implement From<hyper::Error>:

error[E0271]: type mismatch resolving `<futures::AndThen<futures::FutureResult<(), ()>, futures::MapErr<futures::stream::Concat2<hyper::Body>, [closure@src/main.rs:34:70: 34:76]>, [closure@src/main.rs:34:32: 34:77 res:_]> as futures::IntoFuture>::Error == hyper::Error`
  --> src/main.rs:28:18
   |
28 |                 .and_then(|res| {
   |                  ^^^^^^^^ expected (), found struct `hyper::Error`
   |
   = note: expected type `()`
              found type `hyper::Error`

If you don't care about the error, you can map it away before the and_then:

client
    .get(uri)
    .map_err (|_| ())
    .and_then(|res| {
        let f = if do_i_want_to_get_the_full_page {
            futures::future::ok(())
        } else {
            futures::future::err(())
        };
        f.and_then(|_| res.into_body().concat2().map_err(|_| ()))
    }).map(|body| {
        println!("len is {}.", body.len());
    }).map_err(|e| {
        println!("Error: {:?}", e);
    })

playground

or use a type that implements From<hyper::Error> in your call to futures::future::err.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jmb
  • 18,893
  • 2
  • 28
  • 55