Вышла Futures 0.3.0-alpha.1 с поддержкой async/await

3 лайка

Есть ли TLDR для тех кто не очень сильно в контексте футур ориентируется - как в третьей версии решили проблемы второй версии футур, которую отозвали?

Ну это не то чтобы “как именно решили проблемы”, но там есть

Changes from 0.2

Note: Changes between 0.1 and 0.2 are outlined in the 0.2 notes.

Aside from some minor structural changes, there are two major changes from the 0.2 release:

  • Using pinned types to support borrowing within async blocks.
  • Factoring out the Error type into separate traits (TryFuture and TryStream).

Both of these changes are described and motivated in detail in the companion RFC.

The RFC, however, covers only the core Future trait and executor system. The bulk of the work in 0.3.0-alpha.1 has been pushing through these ideas through the rest of the crates, adapting the combinators and other traits to fit with pinning and the ability to borrow across yield points. For example, the revised AsyncReadExt trait now provides a read method that operates on borrowed data, just like in the Read trait in std:

trait AsyncReadExt: AsyncRead {
    /// Tries to read some bytes directly into the given `buf` in asynchronous
    /// manner, returning a future type.
    ///
    /// The returned future will resolve to the number of bytes read once the read
    /// operation is completed.
    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self> {
        Read::new(self, buf)
    }
}

In contrast, the 0.1-style API must operate on owned buffers, which are threaded through the futures code. You can learn more about how this all works in this blog post on borrowing and async/await.

А ещё может @Pzixel пояснит :slight_smile:

1 лайк

Ну по сути они просто продолжили идеи 0.2. Фраз вроде “вот такое мы огребли в 0.2, в 0.3 поправили” они не произносили. 0.2 походу не советуют из-за отсутствия async/await, без которых борровить значения в футурах руками становится крайне сложно.

Что-то мне кажется, что все эти сложности с заимствованием в футурах из-за того что во время Leakpocalypse вместе с водой выплеснули младенца - scoped threads :

The problem is that the future you get back contains borrowed values, which today will prevent it from being used in most futures-based code, due to there being a 'static requirement to ultimately execute futures.

Вот обсуждение утечки JoinGuard на гитхабе. Там в самом начале предлагают сделать специальный маркерный типаж для Rc:

I think the best way to fix this would be to add a Leak OIBIT and make Rc/Arc require it. We may want to make it a by-default bound (like Sized), through, to prevent massive annotation burden.

Но потом на это забили и просто выпилили scoped threads. Вроде как предполагалось что это временно:

Scoped threads are very useful. They will be back as soon as there is a safe way to implement (and use) their API in Rust.

Возможно этот вопрос еще где-то обсуждался, но я не нашел где.

По-моему было бы достаточно с помощью этого маркерного типажа запретить пихать JoinGuard и Futures c любым временем жизни кроме 'static в Rc и задать ограничения для mem::forget().

Так ведь их и запилили обратно, в crossbeam например есть.

Это же внешний крейт. А Futures как раз собираются ввести в std. Т.е. если нормальное заимствование и будет в футурах то тоже через внешние крейты.