[−][src]Struct phantom_newtype::Id
Id<Entity, Repr>
provides a type-safe way to keep ids of
entities. Note that there's no default for Repr
type, the type
of the identifier should be always provided explicitly.
Example:
use phantom_newtype::Id; struct User { id: Id<User, u64>, name: String, posts: Vec<Id<Post, u64>>, } struct Post { id: Id<Post, u64>, title: String, }
Enity
doesn't have to be a struct, any type will do. It's just a
marker that differentiate incompatible ids.
use phantom_newtype::Id; enum Recepient {} enum Message {} type RecepientId = Id<Recepient, u64>; type MessageId = Id<Message, u64>; assert_eq!(RecepientId::from(15), MessageId::from(15));
Id
is cheap to copy if Repr
is:
use phantom_newtype::Id; enum Message {} type MessageId = Id<Message, u64>; let x = MessageId::from(5); let y = x; assert_eq!(x, y);
Id
can be used as a key in a hash map as long as Repr
has
this property:
use phantom_newtype::Id; use std::collections::HashMap; #[derive(PartialEq, Debug)] struct User {} type UserId = Id<User, String>; let mut users_by_id = HashMap::new(); let id = UserId::from("john".to_string()); users_by_id.insert(id.clone(), User {}); assert!(users_by_id.get(&id).is_some());
Ids are ordered if the Repr
is. Note that this is mostly useful
e.g. for storing Ids in a BTreeMap
, there is usually little
semantic value in comparing ids.
use std::collections::BTreeMap; use phantom_newtype::Id; #[derive(PartialEq, Debug)] struct User {} type UserId = Id<User, u64>; let mut map = BTreeMap::new(); let id = UserId::from(5); map.insert(id.clone(), User {}); assert!(map.get(&id).is_some());
Ids can be sent between threads if the Repr
allows it, no
matter which Entity
is used.
use phantom_newtype::Id; type Cell = std::cell::RefCell<i64>; type CellId = Id<Cell, i64>; const ID: CellId = CellId::new(42); let id_from_thread = std::thread::spawn(|| &ID).join().unwrap(); assert_eq!(ID, *id_from_thread);
Ids can be serialized and deserialized with serde
. Serialized
forms of Id<Entity, Repr>
and Repr
are identical.
#[cfg(feature = "serde")] { use phantom_newtype::Id; use serde::{Serialize, Deserialize}; use serde_json; enum User {} let repr: u64 = 10; let user_id = Id::<User, u64>::from(repr); assert_eq!(serde_json::to_string(&user_id).unwrap(), serde_json::to_string(&repr).unwrap()); }
Methods
impl<Entity, Repr> Id<Entity, Repr>
[src]
pub const fn get(&self) -> &Repr
[src]
get
returns the underlying representation of the identifier.
use phantom_newtype::Id; enum User {} type UserId = Id<User, u64>; assert_eq!(*UserId::from(15).get(), 15);
pub const fn new(repr: Repr) -> Id<Entity, Repr>
[src]
new
is a synonym for from
that can be evaluated in
compile time. The main use-case of this functions is defining
constants:
use phantom_newtype::Id; enum User {} type UserId = Id<User, u64>; const ADMIN_ID: UserId = UserId::new(42); assert_eq!(*ADMIN_ID.get(), 42);
impl<Entity, Repr> Id<Entity, Repr> where
Entity: DisplayerOf<Id<Entity, Repr>>,
[src]
Entity: DisplayerOf<Id<Entity, Repr>>,
pub fn display(&self) -> DisplayProxy<Self, Entity>
[src]
display
provides a machanism to implement a custom display
for phantom types.
use phantom_newtype::{Id, DisplayerOf}; use std::fmt; enum Message {} type MessageId = Id<Message, [u8; 32]>; impl DisplayerOf<MessageId> for Message { fn display(id: &MessageId, f: &mut fmt::Formatter<'_>) -> fmt::Result { id.get().iter().try_for_each(|b| write!(f, "{:02x}", b)) } } let vec: Vec<_> = (0u8..32u8).collect(); let mut arr: [u8; 32] = [0u8; 32]; (&mut arr[..]).copy_from_slice(&vec[..]); assert_eq!(format!("{}", MessageId::from(arr).display()), "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
Trait Implementations
impl<Entity, Repr> From<Repr> for Id<Entity, Repr>
[src]
impl<Entity, Repr: Clone> Clone for Id<Entity, Repr>
[src]
fn clone(&self) -> Self
[src]
fn clone_from(&mut self, source: &Self)
1.0.0[src]
impl<Entity, Repr: Copy> Copy for Id<Entity, Repr>
[src]
impl<Entity, Repr: Eq> Eq for Id<Entity, Repr>
[src]
impl<Entity, Repr: Ord> Ord for Id<Entity, Repr>
[src]
fn cmp(&self, rhs: &Self) -> Ordering
[src]
fn max(self, other: Self) -> Self
1.21.0[src]
fn min(self, other: Self) -> Self
1.21.0[src]
fn clamp(self, min: Self, max: Self) -> Self
[src]
impl<Entity, Repr: PartialEq> PartialEq<Id<Entity, Repr>> for Id<Entity, Repr>
[src]
impl<Entity, Repr: PartialOrd> PartialOrd<Id<Entity, Repr>> for Id<Entity, Repr>
[src]
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering>
[src]
#[must_use]
fn lt(&self, other: &Rhs) -> bool
1.0.0[src]
#[must_use]
fn le(&self, other: &Rhs) -> bool
1.0.0[src]
#[must_use]
fn gt(&self, other: &Rhs) -> bool
1.0.0[src]
#[must_use]
fn ge(&self, other: &Rhs) -> bool
1.0.0[src]
impl<Entity, Repr: Display> Display for Id<Entity, Repr>
[src]
impl<Entity, Repr: Debug> Debug for Id<Entity, Repr>
[src]
impl<Entity, Repr: Hash> Hash for Id<Entity, Repr>
[src]
fn hash<H: Hasher>(&self, state: &mut H)
[src]
fn hash_slice<H>(data: &[Self], state: &mut H) where
H: Hasher,
1.3.0[src]
H: Hasher,
impl<Entity, Repr> Serialize for Id<Entity, Repr> where
Repr: Serialize,
[src]
Repr: Serialize,
impl<'de, Entity, Repr> Deserialize<'de> for Id<Entity, Repr> where
Repr: Deserialize<'de>,
[src]
Repr: Deserialize<'de>,
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
[src]
Auto Trait Implementations
impl<Entity, Repr> Send for Id<Entity, Repr> where
Entity: Send,
Repr: Send,
Entity: Send,
Repr: Send,
impl<Entity, Repr> Sync for Id<Entity, Repr> where
Entity: Send,
Repr: Sync,
Entity: Send,
Repr: Sync,
impl<Entity, Repr> Unpin for Id<Entity, Repr> where
Entity: Unpin,
Repr: Unpin,
Entity: Unpin,
Repr: Unpin,
impl<Entity, Repr> UnwindSafe for Id<Entity, Repr> where
Repr: UnwindSafe,
Repr: UnwindSafe,
impl<Entity, Repr> RefUnwindSafe for Id<Entity, Repr> where
Repr: RefUnwindSafe,
Repr: RefUnwindSafe,
Blanket Implementations
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T> From<T> for T
[src]
impl<T> From<!> for T
[src]
impl<T> ToOwned for T where
T: Clone,
[src]
T: Clone,
type Owned = T
The resulting type after obtaining ownership.
fn to_owned(&self) -> T
[src]
fn clone_into(&self, target: &mut T)
[src]
impl<T> ToString for T where
T: Display + ?Sized,
[src]
T: Display + ?Sized,
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> DeserializeOwned for T where
T: Deserialize<'de>,
[src]
T: Deserialize<'de>,