Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce strongly-typed Context keys
- Loading branch information
Showing
4 changed files
with
133 additions
and
28 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
use std::marker::PhantomData; | ||
use std::fmt; | ||
|
||
/// `Key` provides strongly typed access to data | ||
/// inside `Context`. | ||
pub struct Key<T> { | ||
// These fields are public so that `config_key` | ||
// macro works outside of this crate. It should be | ||
// replaced with `const fn`, once it is stable. | ||
#[doc(hidden)] | ||
pub __name: &'static str, | ||
#[doc(hidden)] | ||
pub __phantom: PhantomData<T>, | ||
} | ||
|
||
// We need explicit `impl Copy` because derive won't work if `T: !Copy`. | ||
impl<T> Copy for Key<T> {} | ||
#[allow(expl_impl_clone_on_copy)] | ||
impl<T> Clone for Key<T> { | ||
fn clone(&self) -> Self { | ||
Key { | ||
__name: self.__name, | ||
__phantom: self.__phantom, | ||
} | ||
} | ||
} | ||
|
||
impl<T> fmt::Debug for Key<T> { | ||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||
write!(fmt, "Key({:?})", self.__name) | ||
} | ||
} | ||
|
||
impl<T> Key<T> { | ||
/// Name of this key. | ||
pub fn name(&self) -> &str { | ||
self.__name | ||
} | ||
} | ||
|
||
#[macro_export] | ||
macro_rules! config_key { | ||
($name:expr) => {{ | ||
Key { | ||
__name: $name, | ||
__phantom: ::std::marker::PhantomData | ||
} | ||
}} | ||
} | ||
|
||
#[test] | ||
fn key_is_really_copy() { | ||
const K: Key<Vec<String>> = config_key!("k"); | ||
let x = K; | ||
let y = x; | ||
assert_eq!(x.name(), y.name()); | ||
} |
This file contains 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