implement serialization for atomic integer types

This commit is contained in:
James Brown 2019-07-11 17:34:53 -07:00
parent ce89adecc1
commit 56d3c8f071
2 changed files with 67 additions and 0 deletions

View File

@ -839,3 +839,55 @@ where
self.0.serialize(serializer)
}
}
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
use std::sync::atomic;
#[cfg(feature = "std")]
macro_rules! atomic_impl {
($ty:path, $method:ident $($cast:tt)*) => {
impl Serialize for $ty {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.$method(self.load(atomic::Ordering::SeqCst) $($cast)*)
}
}
}
}
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicBool, serialize_bool);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicI8, serialize_i8);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicI16, serialize_i16);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicI32, serialize_i32);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicI64, serialize_i64);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicIsize, serialize_i64 as i64);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicU8, serialize_u8);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicU16, serialize_u16);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicU32, serialize_u32);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicU64, serialize_u64);
#[cfg(feature = "std")]
atomic_impl!(atomic::AtomicUsize, serialize_u64 as u64);

View File

@ -10,6 +10,7 @@ use std::ops::Bound;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak as RcWeak};
use std::sync::{Arc, Weak as ArcWeak};
use std::sync::atomic;
use std::time::{Duration, UNIX_EPOCH};
#[cfg(unix)]
@ -483,6 +484,20 @@ declare_tests! {
Token::Str("1a"),
],
}
test_atomic {
atomic::AtomicBool::new(false) => &[Token::Bool(false)],
atomic::AtomicBool::new(true) => &[Token::Bool(true)],
atomic::AtomicI8::new(63i8) => &[Token::I8(63i8)],
atomic::AtomicI16::new(-318i16) => &[Token::I16(-318i16)],
atomic::AtomicI32::new(65792i32) => &[Token::I32(65792i32)],
atomic::AtomicI64::new(-4295032832i64) => &[Token::I64(-4295032832i64)],
atomic::AtomicIsize::new(-65792isize) => &[Token::I64(-65792i64)],
atomic::AtomicU8::new(192u8) => &[Token::U8(192u8)],
atomic::AtomicU16::new(510u16) => &[Token::U16(510u16)],
atomic::AtomicU32::new(131072u32) => &[Token::U32(131072u32)],
atomic::AtomicU64::new(12884901888u64) => &[Token::U64(12884901888u64)],
atomic::AtomicUsize::new(655360usize) => &[Token::U64(655360u64)],
}
}
declare_tests! {