Small fixes to request-local state cache implementation.

This commit is contained in:
Sergio Benitez 2018-07-07 18:51:26 -07:00
parent 97c6b3ace8
commit 351b8f7c37
5 changed files with 15 additions and 17 deletions

View File

@ -22,7 +22,7 @@ members = [
"examples/content_types",
"examples/ranking",
"examples/testing",
"examples/request_state_local_cache",
"examples/request_local_state",
"examples/request_guard",
"examples/stream",
"examples/json",

View File

@ -82,8 +82,8 @@ impl<'r> Request<'r> {
}
/// Retrieves the cached value for type `T` from the request-local cached
/// state of `self`. If no such value has previously been cached for
/// this request, `f` is called to produce the value which is subsequently
/// state of `self`. If no such value has previously been cached for this
/// request, `f` is called to produce the value which is subsequently
/// returned.
///
/// # Example
@ -92,26 +92,24 @@ impl<'r> Request<'r> {
/// # use rocket::http::Method;
/// # use rocket::Request;
/// # struct User;
/// fn current_user() -> User {
/// // Load user...
/// fn current_user(request: &Request) -> User {
/// // Validate request for a given user, load from database, etc.
/// # User
/// }
///
/// # Request::example(Method::Get, "/uri", |request| {
/// let user = request.local_cache(current_user);
/// let user = request.local_cache(|| current_user(request));
/// # });
/// ```
pub fn local_cache<T, F>(&self, f: F) -> &T
where T: Send + Sync + 'static,
F: FnOnce() -> T {
match self.state.cache.try_get() {
Some(cached) => cached,
None => {
where F: FnOnce() -> T,
T: Send + Sync + 'static
{
self.state.cache.try_get()
.unwrap_or_else(|| {
self.state.cache.set(f());
self.state.cache.get()
}
}
})
}
/// Retrieve the method from `self`.

View File

@ -1,5 +1,5 @@
[package]
name = "request_state_local_cache"
name = "request_local_state"
version = "0.0.0"
workspace = "../../"
publish = false

View File

@ -1,5 +1,6 @@
#![feature(plugin, decl_macro)]
#![plugin(rocket_codegen)]
extern crate rocket;
use std::sync::atomic::{AtomicUsize, Ordering};

View File

@ -1,7 +1,6 @@
use std::sync::atomic::{Ordering};
use ::Atomics;
use super::rocket;
use super::{rocket, Atomics};
use rocket::local::Client;
#[test]