Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ redis = { version = "0.7.0", optional = true }
r2d2_redis = { version = "0.5.0", optional = true }
r2d2 = { version = "0.7.1", optional = true }

serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }

[features]
redis-backend = ["redis", "r2d2_redis", "r2d2"]
serde-values = ["serde", "serde_json"]

[dev-dependencies]
router = "0.5.0"
Expand Down
23 changes: 23 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ extern crate rand;
#[cfg(feature = "redis-backend")] extern crate redis;
#[cfg(feature = "redis-backend")] extern crate r2d2;
#[cfg(feature = "redis-backend")] extern crate r2d2_redis;
#[cfg(feature = "serde-values")] extern crate serde;
#[cfg(feature = "serde-values")] extern crate serde_json;

use iron::prelude::*;
use iron::middleware::{AroundMiddleware,Handler};
Expand Down Expand Up @@ -79,6 +81,27 @@ pub trait Value: Sized + 'static {
fn from_raw(value: String) -> Option<Self>;
}

pub trait Key {
fn get_key() -> &'static str;
}

#[cfg(feature = "serde-values")]
impl<T> Value for T
where
T: 'static + Key + serde::Serialize + serde::de::DeserializeOwned,
{
fn get_key() -> &'static str {
Self::get_key()
}
fn into_raw(self) -> String {
serde_json::to_string(&self).expect("serializing self must not fail")
}
fn from_raw(value: String) -> Option<Self> {
serde_json::from_str(&value).ok()
}
}


impl Session {
/// Get a `Value` from the session.
pub fn get<T: Value + Sized + 'static>(&self) -> IronResult<Option<T>> {
Expand Down