1- use std:: sync:: atomic:: { AtomicI64 , AtomicU32 , AtomicU64 , Ordering } ;
1+ use std:: sync:: atomic:: {
2+ AtomicI8 , AtomicI16 , AtomicI32 , AtomicI64 , AtomicU8 , AtomicU16 , AtomicU32 , AtomicU64 , Ordering ,
3+ } ;
24
35pub trait TablePrimaryKey {
46 type Generator ;
@@ -16,68 +18,40 @@ pub trait PrimaryKeyGeneratorState {
1618 fn from_state ( state : Self :: State ) -> Self ;
1719}
1820
19- impl < T > PrimaryKeyGenerator < T > for AtomicU32
20- where
21- T : From < u32 > ,
22- {
23- fn next ( & self ) -> T {
24- self . fetch_add ( 1 , Ordering :: Relaxed ) . into ( )
25- }
26- }
27-
28- impl PrimaryKeyGeneratorState for AtomicU32 {
29- type State = u32 ;
30-
31- fn get_state ( & self ) -> Self :: State {
32- self . load ( Ordering :: Relaxed )
33- }
34-
35- fn from_state ( state : Self :: State ) -> Self {
36- AtomicU32 :: from ( state)
37- }
38- }
39-
40- impl < T > PrimaryKeyGenerator < T > for AtomicU64
41- where
42- T : From < u64 > ,
43- {
44- fn next ( & self ) -> T {
45- self . fetch_add ( 1 , Ordering :: Relaxed ) . into ( )
46- }
47- }
48-
49- impl PrimaryKeyGeneratorState for AtomicU64 {
50- type State = u64 ;
51-
52- fn get_state ( & self ) -> Self :: State {
53- self . load ( Ordering :: Relaxed )
54- }
55-
56- fn from_state ( state : Self :: State ) -> Self {
57- AtomicU64 :: from ( state)
58- }
59- }
60-
61- impl < T > PrimaryKeyGenerator < T > for AtomicI64
62- where
63- T : From < i64 > ,
64- {
65- fn next ( & self ) -> T {
66- self . fetch_add ( 1 , Ordering :: Relaxed ) . into ( )
67- }
68- }
69-
70- impl PrimaryKeyGeneratorState for AtomicI64 {
71- type State = i64 ;
72-
73- fn get_state ( & self ) -> Self :: State {
74- self . load ( Ordering :: Relaxed )
75- }
76-
77- fn from_state ( state : Self :: State ) -> Self {
78- AtomicI64 :: from ( state)
79- }
80- }
21+ macro_rules! atomic_primary_key {
22+ ( $ty: ident, $atomic_ty: ident) => {
23+ impl <T > PrimaryKeyGenerator <T > for $atomic_ty
24+ where
25+ T : From <$ty>,
26+ {
27+ fn next( & self ) -> T {
28+ self . fetch_add( 1 , Ordering :: AcqRel ) . into( )
29+ }
30+ }
31+
32+ impl PrimaryKeyGeneratorState for $atomic_ty {
33+ type State = $ty;
34+
35+ fn get_state( & self ) -> Self :: State {
36+ self . load( Ordering :: Acquire )
37+ }
38+
39+ fn from_state( state: Self :: State ) -> Self {
40+ $atomic_ty:: from( state)
41+ }
42+ }
43+ } ;
44+ }
45+
46+ atomic_primary_key ! ( u8 , AtomicU8 ) ;
47+ atomic_primary_key ! ( u16 , AtomicU16 ) ;
48+ atomic_primary_key ! ( u32 , AtomicU32 ) ;
49+ atomic_primary_key ! ( u64 , AtomicU64 ) ;
50+
51+ atomic_primary_key ! ( i8 , AtomicI8 ) ;
52+ atomic_primary_key ! ( i16 , AtomicI16 ) ;
53+ atomic_primary_key ! ( i32 , AtomicI32 ) ;
54+ atomic_primary_key ! ( i64 , AtomicI64 ) ;
8155
8256impl PrimaryKeyGeneratorState for ( ) {
8357 type State = ( ) ;
0 commit comments