1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#![feature(unboxed_closures)]
#![feature(fn_traits)]
mod idx;
mod idx_vec;
pub use idx::Idx;
pub use idx_vec::{Enumerated, IndexVec, IntoIdx};
#[cfg(feature = "serde")]
pub use serde::{Deserialize, Serialize};
#[cfg(feature = "serde")]
fn _is_serde<T: Serialize + serde::de::DeserializeOwned>(_: &T) {
}
#[cfg(feature = "serde")]
fn _idx_is_serde() {
newtype_index!(Foo);
_is_serde(&Foo::new(0));
}
#[macro_export]
macro_rules! newtype_index {
(
$(#[$attrs:meta])*
$vis:vis struct $type:ident {
$( $const_vis:vis const $constant:ident = $value:expr; )*
}
) => {
$(#[$attrs])*
#[derive(Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive($crate::Serialize, $crate::Deserialize)]
$vis struct $type {
idx: usize,
}
impl $type {
$( $const_vis const $constant: $type = Self::const_new($value); )*
}
impl $type {
#[allow(unused)]
pub const fn const_new(idx: usize) -> Self {
Self { idx }
}
}
impl Clone for $type {
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl $crate::Idx for $type {
#[inline]
fn new(idx: usize) -> Self {
Self { idx }
}
#[inline]
fn index(self) -> usize {
self.idx
}
}
};
($vis:vis $type:ident) => {
$crate::newtype_index!($vis struct $type {});
};
}
#[cfg(test)]
mod tests;