actix-utils-3.0.1/CHANGES.md000064400000000000000000000104431046102023000134670ustar 00000000000000# Changes ## Unreleased - 2022-xx-xx ## 3.0.1 - 2022-10-21 - Minimum supported Rust version (MSRV) is now 1.57. ## 3.0.0 - 2021-04-16 - No significant changes from `3.0.0-beta.4`. ## 3.0.0-beta.4 - 2021-04-01 - Add `future::Either` type. [#305] [#305]: https://github.com/actix/actix-net/pull/305 ## 3.0.0-beta.3 - 2021-04-01 - Moved `mpsc` to own crate `local-channel`. [#301] - Moved `task::LocalWaker` to own crate `local-waker`. [#301] - Remove `timeout` module. [#301] - Remove `dispatcher` module. [#301] - Expose `future` mod with `ready` and `poll_fn` helpers. [#301] [#301]: https://github.com/actix/actix-net/pull/301 ## 3.0.0-beta.2 - 2021-02-06 - Update `actix-rt` to `2.0.0`. [#273] [#273]: https://github.com/actix/actix-net/pull/273 ## 3.0.0-beta.1 - 2020-12-28 - Update `bytes` dependency to `1`. [#237] - Use `pin-project-lite` to replace `pin-project`. [#229] - Remove `condition`,`either`,`inflight`,`keepalive`,`oneshot`,`order`,`stream` and `time` mods. [#229] [#229]: https://github.com/actix/actix-net/pull/229 [#237]: https://github.com/actix/actix-net/pull/237 ## 2.0.0 - 2020-08-23 - No changes from beta 1. ## 2.0.0-beta.1 - 2020-08-19 - Upgrade `tokio-util` to `0.3`. - Remove unsound custom Cell and use `std::cell::RefCell` instead, as well as `actix-service`. - Rename method to correctly spelled `LocalWaker::is_registered`. ## 1.0.6 - 2020-01-08 - Add `Clone` impl for `condition::Waiter`. ## 1.0.5 - 2020-01-08 - Add `Condition` type. - Add `Pool` of one-shot's. ## 1.0.4 - 2019-12-20 - Add methods to check `LocalWaker` registration state. ## 1.0.3 - 2019-12-11 - Revert InOrder service changes ## 1.0.2 - 2019-12-11 - Allow to create `framed::Dispatcher` with custom `mpsc::Receiver`. - Add `oneshot::Sender::is_canceled()` method. ## 1.0.1 - 2019-12-11 - Optimize InOrder service. ## 1.0.0 - 2019-12-11 - Simplify oneshot and mpsc implementations. ## 1.0.0-alpha.3 - 2019-12-07 - Migrate to tokio 0.2. - Fix oneshot. ## 1.0.0-alpha.2 - 2019-12-02 - Migrate to `std::future`. ## 0.4.7 - 2019-10-14 - Re-register task on every framed transport poll. ## 0.4.6 - 2019-10-08 - Refactor `Counter` type. register current task in available method. ## 0.4.5 - 2019-07-19 - Deprecated `CloneableService` as it is not safe. ## 0.4.4 - 2019-07-17 - Undeprecate `FramedTransport` as it is actually useful. ## 0.4.3 - 2019-07-17 - Deprecate `CloneableService` as it is not safe and in general not very useful. - Deprecate `FramedTransport` in favor of `actix-ioframe`. ## 0.4.2 - 2019-06-26 - Do not block on sink drop for FramedTransport. ## 0.4.1 - 2019-05-15 - Change `Either` constructor. ## 0.4.0 - 2019-05-11 - Change `Either` to handle two nexted services. - Upgrade actix-service 0.4. - Removed framed related services. - Removed stream related services. ## 0.3.5 - 2019-04-04 - Allow to send messages to `FramedTransport` via mpsc channel. - Remove `'static` constraint from Clonable service. ## 0.3.4 - 2019-03-12 - `TimeoutService`, `InOrderService`, `InFlightService` accepts generic IntoService services. - Fix `InFlightService::poll_ready()` nested service readiness check. - Fix `InOrderService::poll_ready()` nested service readiness check. ## 0.3.3 - 2019-03-09 - Revert IntoFuture change. - Add generic config param for IntoFramed and TakeOne new services. ## 0.3.2 - 2019-03-04 - Use IntoFuture for new services. ## 0.3.1 - 2019-03-04 - Use new type of transform trait. ## 0.3.0 - 2019-03-02 - Use new `NewService` trait - BoxedNewService` and `BoxedService` types moved to actix-service crate. ## 0.2.4 - 2019-02-21 - Custom `BoxedNewService` implementation. ## 0.2.3 - 2019-02-21 - Add `BoxedNewService` and `BoxedService`. ## 0.2.2 - 2019-02-11 - Add `Display` impl for `TimeoutError`. - Add `Display` impl for `InOrderError`. ## 0.2.1 - 2019-02-06 - Add `InOrder` service. the service yields responses as they become available, in the order that their originating requests were submitted to the service. - Convert `Timeout` and `InFlight` services to a transforms. ## 0.2.0 - 2019-02-01 - Fix framed transport error handling. - Added Clone impl for Either service. - Added Clone impl for Timeout service factory. - Added Service and NewService for Stream dispatcher. - Switch to actix-service 0.2. ## 0.1.0 - 2018-12-09 - Move utils services to separate crate. actix-utils-3.0.1/Cargo.toml0000644000000020260000000000100113010ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "actix-utils" version = "3.0.1" authors = [ "Nikolay Kim ", "Rob Ede ", ] description = "Various utilities used in the Actix ecosystem" keywords = [ "network", "framework", "async", "futures", ] categories = [ "network-programming", "asynchronous", ] license = "MIT OR Apache-2.0" repository = "https://github.com/actix/actix-net" [lib] name = "actix_utils" path = "src/lib.rs" [dependencies.local-waker] version = "0.1" [dependencies.pin-project-lite] version = "0.2" actix-utils-3.0.1/Cargo.toml.orig000064400000000000000000000010051046102023000147560ustar 00000000000000[package] name = "actix-utils" version = "3.0.1" authors = [ "Nikolay Kim ", "Rob Ede ", ] description = "Various utilities used in the Actix ecosystem" keywords = ["network", "framework", "async", "futures"] categories = ["network-programming", "asynchronous"] repository = "https://github.com/actix/actix-net" license = "MIT OR Apache-2.0" edition = "2018" [lib] name = "actix_utils" path = "src/lib.rs" [dependencies] pin-project-lite = "0.2" local-waker = "0.1" actix-utils-3.0.1/LICENSE-APACHE000064400000000000000000000261201046102023000140200ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017-NOW Actix Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. actix-utils-3.0.1/LICENSE-MIT000064400000000000000000000020421046102023000135250ustar 00000000000000Copyright (c) 2017-NOW Actix Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. actix-utils-3.0.1/src/counter.rs000064400000000000000000000044701046102023000147140ustar 00000000000000//! Task-notifying counter. use core::{cell::Cell, fmt, task}; use std::rc::Rc; use local_waker::LocalWaker; /// Simple counter with ability to notify task on reaching specific number /// /// Counter could be cloned, total n-count is shared across all clones. #[derive(Debug, Clone)] pub struct Counter(Rc); impl Counter { /// Create `Counter` instance with max value. pub fn new(capacity: usize) -> Self { Counter(Rc::new(CounterInner { capacity, count: Cell::new(0), task: LocalWaker::new(), })) } /// Create new counter guard, incrementing the counter. #[inline] pub fn get(&self) -> CounterGuard { CounterGuard::new(self.0.clone()) } /// Returns true if counter is below capacity. Otherwise, register to wake task when it is. #[inline] pub fn available(&self, cx: &mut task::Context<'_>) -> bool { self.0.available(cx) } /// Get total number of acquired guards. #[inline] pub fn total(&self) -> usize { self.0.count.get() } } struct CounterInner { count: Cell, capacity: usize, task: LocalWaker, } impl CounterInner { fn inc(&self) { self.count.set(self.count.get() + 1); } fn dec(&self) { let num = self.count.get(); self.count.set(num - 1); if num == self.capacity { self.task.wake(); } } fn available(&self, cx: &mut task::Context<'_>) -> bool { if self.count.get() < self.capacity { true } else { self.task.register(cx.waker()); false } } } impl fmt::Debug for CounterInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Counter") .field("count", &self.count.get()) .field("capacity", &self.capacity) .field("task", &self.task) .finish() } } /// An RAII structure that keeps the underlying counter incremented until this guard is dropped. #[derive(Debug)] pub struct CounterGuard(Rc); impl CounterGuard { fn new(inner: Rc) -> Self { inner.inc(); CounterGuard(inner) } } impl Unpin for CounterGuard {} impl Drop for CounterGuard { fn drop(&mut self) { self.0.dec(); } } actix-utils-3.0.1/src/future/either.rs000064400000000000000000000043471046102023000160320ustar 00000000000000//! A symmetric either future. use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; use pin_project_lite::pin_project; pin_project! { /// Combines two different futures that have the same output type. /// /// Construct variants with [`Either::left`] and [`Either::right`]. /// /// # Examples /// ``` /// use actix_utils::future::{ready, Ready, Either}; /// /// # async fn run() { /// let res = Either::<_, Ready>::left(ready(42)); /// assert_eq!(res.await, 42); /// /// let res = Either::, _>::right(ready(43)); /// assert_eq!(res.await, 43); /// # } /// ``` #[project = EitherProj] #[derive(Debug, Clone)] pub enum Either { /// A value of type `L`. #[allow(missing_docs)] Left { #[pin] value: L }, /// A value of type `R`. #[allow(missing_docs)] Right { #[pin] value: R }, } } impl Either { /// Creates new `Either` using left variant. #[inline] pub fn left(value: L) -> Either { Either::Left { value } } /// Creates new `Either` using right variant. #[inline] pub fn right(value: R) -> Either { Either::Right { value } } } impl Either { /// Unwraps into inner value when left and right have a common type. #[inline] pub fn into_inner(self) -> T { match self { Either::Left { value } => value, Either::Right { value } => value, } } } impl Future for Either where L: Future, R: Future, { type Output = L::Output; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.project() { EitherProj::Left { value } => value.poll(cx), EitherProj::Right { value } => value.poll(cx), } } } #[cfg(test)] mod tests { use super::*; use crate::future::{ready, Ready}; #[actix_rt::test] async fn test_either() { let res = Either::<_, Ready>::left(ready(42)); assert_eq!(res.await, 42); let res = Either::, _>::right(ready(43)); assert_eq!(res.await, 43); } } actix-utils-3.0.1/src/future/mod.rs000064400000000000000000000003021046102023000153140ustar 00000000000000//! Helpers for constructing futures. mod either; mod poll_fn; mod ready; pub use self::either::Either; pub use self::poll_fn::{poll_fn, PollFn}; pub use self::ready::{err, ok, ready, Ready}; actix-utils-3.0.1/src/future/poll_fn.rs000064400000000000000000000055141046102023000162000ustar 00000000000000//! Simple "poll function" future and factory. use core::{ fmt, future::Future, pin::Pin, task::{Context, Poll}, }; /// Creates a future driven by the provided function that receives a task context. /// /// # Examples /// ``` /// # use std::task::Poll; /// # use actix_utils::future::poll_fn; /// # async fn test_poll_fn() { /// let res = poll_fn(|_| Poll::Ready(42)).await; /// assert_eq!(res, 42); /// /// let mut i = 5; /// let res = poll_fn(|cx| { /// i -= 1; /// /// if i > 0 { /// cx.waker().wake_by_ref(); /// Poll::Pending /// } else { /// Poll::Ready(42) /// } /// }) /// .await; /// assert_eq!(res, 42); /// # } /// # actix_rt::Runtime::new().unwrap().block_on(test_poll_fn()); /// ``` #[inline] pub fn poll_fn(f: F) -> PollFn where F: FnMut(&mut Context<'_>) -> Poll, { PollFn { f } } /// Future for the [`poll_fn`] function. pub struct PollFn { f: F, } impl fmt::Debug for PollFn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PollFn").finish() } } impl Future for PollFn where F: FnMut(&mut Context<'_>) -> Poll, { type Output = T; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // SAFETY: we are not moving out of the pinned field // see https://github.com/rust-lang/rust/pull/102737 (unsafe { &mut self.get_unchecked_mut().f })(cx) } } #[cfg(test)] mod tests { use std::marker::PhantomPinned; use super::*; static_assertions::assert_impl_all!(PollFn<()>: Unpin); static_assertions::assert_not_impl_all!(PollFn: Unpin); #[actix_rt::test] async fn test_poll_fn() { let res = poll_fn(|_| Poll::Ready(42)).await; assert_eq!(res, 42); let mut i = 5; let res = poll_fn(|cx| { i -= 1; if i > 0 { cx.waker().wake_by_ref(); Poll::Pending } else { Poll::Ready(42) } }) .await; assert_eq!(res, 42); } // following soundness tests taken from https://github.com/tokio-rs/tokio/pull/5087 #[allow(dead_code)] fn require_send(_t: &T) {} #[allow(dead_code)] fn require_sync(_t: &T) {} trait AmbiguousIfUnpin { fn some_item(&self) {} } impl AmbiguousIfUnpin<()> for T {} impl AmbiguousIfUnpin<[u8; 0]> for T {} const _: fn() = || { let pinned = std::marker::PhantomPinned; let f = poll_fn(move |_| { // Use `pinned` to take ownership of it. let _ = &pinned; std::task::Poll::Pending::<()> }); require_send(&f); require_sync(&f); AmbiguousIfUnpin::some_item(&f); }; } actix-utils-3.0.1/src/future/ready.rs000064400000000000000000000054021046102023000156470ustar 00000000000000//! When `core::future::Ready` has a `into_inner()` method, this can be deprecated. use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; /// Future for the [`ready`] function. /// /// Panic will occur if polled more than once. /// /// # Examples /// ``` /// use actix_utils::future::ready; /// /// // async /// # async fn run() { /// let a = ready(1); /// assert_eq!(a.await, 1); /// # } /// /// // sync /// let a = ready(1); /// assert_eq!(a.into_inner(), 1); /// ``` #[derive(Debug, Clone)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Ready { val: Option, } impl Ready { /// Unwraps the value from this immediately ready future. #[inline] pub fn into_inner(mut self) -> T { self.val.take().unwrap() } } impl Unpin for Ready {} impl Future for Ready { type Output = T; #[inline] fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll { let val = self.val.take().expect("Ready polled after completion"); Poll::Ready(val) } } /// Creates a future that is immediately ready with a value. /// /// # Examples /// ```no_run /// use actix_utils::future::ready; /// /// # async fn run() { /// let a = ready(1); /// assert_eq!(a.await, 1); /// # } /// /// // sync /// let a = ready(1); /// assert_eq!(a.into_inner(), 1); /// ``` #[inline] pub fn ready(val: T) -> Ready { Ready { val: Some(val) } } /// Creates a future that is immediately ready with a success value. /// /// # Examples /// ```no_run /// use actix_utils::future::ok; /// /// # async fn run() { /// let a = ok::<_, ()>(1); /// assert_eq!(a.await, Ok(1)); /// # } /// ``` #[inline] pub fn ok(val: T) -> Ready> { Ready { val: Some(Ok(val)) } } /// Creates a future that is immediately ready with an error value. /// /// # Examples /// ```no_run /// use actix_utils::future::err; /// /// # async fn run() { /// let a = err::<(), _>(1); /// assert_eq!(a.await, Err(1)); /// # } /// ``` #[inline] pub fn err(err: E) -> Ready> { Ready { val: Some(Err(err)), } } #[cfg(test)] mod tests { use std::rc::Rc; use futures_util::task::noop_waker; use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; assert_impl_all!(Ready<()>: Send, Sync, Unpin, Clone); assert_impl_all!(Ready>: Unpin, Clone); assert_not_impl_any!(Ready>: Send, Sync); #[test] #[should_panic] fn multiple_poll_panics() { let waker = noop_waker(); let mut cx = Context::from_waker(&waker); let mut ready = ready(1); assert_eq!(Pin::new(&mut ready).poll(&mut cx), Poll::Ready(1)); // panic! let _ = Pin::new(&mut ready).poll(&mut cx); } } actix-utils-3.0.1/src/lib.rs000064400000000000000000000004441046102023000140000ustar 00000000000000//! Various utilities used in the Actix ecosystem. #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible, missing_docs)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] pub mod counter; pub mod future;