Created
March 28, 2025 09:52
-
-
Save Yoric/0fd531d6ff8f4077e66de7f83116a6e3 to your computer and use it in GitHub Desktop.
Rust comments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async fn insert_with<F>(&self, key: Key, future: F) -> FetchResult | |
where | |
F: Future<Output = FetchResult>, | |
{ | |
// Each `OnceCell` represents a fetch task, either complete, in progress, or (if we create it) about to start. | |
let once = { | |
let mut store = self.store.lock().await; | |
store | |
.entry(key.clone()) | |
.or_insert_with(|| Arc::new(OnceCell::new())) | |
.clone() | |
}; | |
// We're now out of the lock. Other calls to the downloader may affect the store, but any task involving this specific handle will return the same cell. | |
// Case 1: Fetch hasn't started. It will now start. The `await` will only resolve once the fetch is complete. | |
// Case 2: Fetch is in progress. The `await` will merge with the ongoing fetch and resolve once the fetch is complete. | |
// Case 3: Fetch is complete. The `await` will resolve immediately with the result of the fetch. | |
once.get_or_init(|| future).await.clone() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment