Use new std::num::NonZero* types instead of deprecated core::nonzero::NonZero

This commit is contained in:
Simon Sapin 2018-03-29 16:26:07 +02:00
parent 3d6614e314
commit 52dceb3d5f
5 changed files with 114 additions and 143 deletions

View file

@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use euclid::Size2D; use euclid::Size2D;
use nonzero::NonZero; use nonzero::NonZeroU32;
use offscreen_gl_context::{GLContextAttributes, GLLimits}; use offscreen_gl_context::{GLContextAttributes, GLLimits};
use serde_bytes::ByteBuf; use serde_bytes::ByteBuf;
use std::fmt; use std::fmt;
@ -280,13 +280,13 @@ pub enum WebGLCommand {
macro_rules! define_resource_id_struct { macro_rules! define_resource_id_struct {
($name:ident) => { ($name:ident) => {
#[derive(Clone, Copy, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct $name(NonZero<u32>); pub struct $name(NonZeroU32);
impl $name { impl $name {
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[inline] #[inline]
pub unsafe fn new(id: u32) -> Self { pub unsafe fn new(id: u32) -> Self {
$name(NonZero::new_unchecked(id)) $name(NonZeroU32::new_unchecked(id))
} }
#[inline] #[inline]

View file

@ -14,7 +14,7 @@ use ipc_channel::ipc::{self, IpcSharedMemory};
use libc::c_void; use libc::c_void;
use msg::constellation_msg::{PipelineId, PipelineIndex, PipelineNamespaceId}; use msg::constellation_msg::{PipelineId, PipelineIndex, PipelineNamespaceId};
use net_traits::image::base::{Image, PixelFormat}; use net_traits::image::base::{Image, PixelFormat};
use nonzero::NonZero; use nonzero::NonZeroU32;
use profile_traits::time::{self, ProfilerCategory, profile}; use profile_traits::time::{self, ProfilerCategory, profile};
use script_traits::{AnimationState, AnimationTickType, ConstellationMsg, LayoutControlMsg}; use script_traits::{AnimationState, AnimationTickType, ConstellationMsg, LayoutControlMsg};
use script_traits::{MouseButton, MouseEventType, ScrollState, TouchEventType, TouchId}; use script_traits::{MouseButton, MouseEventType, ScrollState, TouchEventType, TouchId};
@ -64,7 +64,7 @@ impl ConvertPipelineIdFromWebRender for webrender_api::PipelineId {
fn from_webrender(&self) -> PipelineId { fn from_webrender(&self) -> PipelineId {
PipelineId { PipelineId {
namespace_id: PipelineNamespaceId(self.0), namespace_id: PipelineNamespaceId(self.0),
index: PipelineIndex(NonZero::new(self.1).expect("Webrender pipeline zero?")), index: PipelineIndex(NonZeroU32::new(self.1).expect("Webrender pipeline zero?")),
} }
} }
} }

View file

@ -5,7 +5,7 @@
//! The high-level interface from script to constellation. Using this abstract interface helps //! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components. //! reduce coupling between these two components.
use nonzero::NonZero; use nonzero::NonZeroU32;
use std::cell::Cell; use std::cell::Cell;
use std::fmt; use std::fmt;
use webrender_api; use webrender_api;
@ -195,9 +195,9 @@ impl PipelineNamespace {
}); });
} }
fn next_index(&mut self) -> NonZero<u32> { fn next_index(&mut self) -> NonZeroU32 {
self.index += 1; self.index += 1;
NonZero::new(self.index).expect("pipeline id index wrapped!") NonZeroU32::new(self.index).expect("pipeline id index wrapped!")
} }
fn next_pipeline_id(&mut self) -> PipelineId { fn next_pipeline_id(&mut self) -> PipelineId {
@ -221,7 +221,7 @@ thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = C
pub struct PipelineNamespaceId(pub u32); pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PipelineIndex(pub NonZero<u32>); pub struct PipelineIndex(pub NonZeroU32);
malloc_size_of_is_0!(PipelineIndex); malloc_size_of_is_0!(PipelineIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)] #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
@ -252,7 +252,7 @@ impl PipelineId {
unsafe { unsafe {
PipelineId { PipelineId {
namespace_id: PipelineNamespaceId(namespace_id), namespace_id: PipelineNamespaceId(namespace_id),
index: PipelineIndex(NonZero::new_unchecked(index)), index: PipelineIndex(NonZeroU32::new_unchecked(index)),
} }
} }
} }
@ -279,7 +279,7 @@ impl fmt::Display for PipelineId {
} }
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct BrowsingContextIndex(pub NonZero<u32>); pub struct BrowsingContextIndex(pub NonZeroU32);
malloc_size_of_is_0!(BrowsingContextIndex); malloc_size_of_is_0!(BrowsingContextIndex);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)] #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize)]
@ -355,13 +355,13 @@ impl PartialEq<BrowsingContextId> for TopLevelBrowsingContextId {
pub const TEST_NAMESPACE: PipelineNamespaceId = PipelineNamespaceId(1234); pub const TEST_NAMESPACE: PipelineNamespaceId = PipelineNamespaceId(1234);
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[cfg(feature = "unstable")] #[cfg(feature = "unstable")]
pub const TEST_PIPELINE_INDEX: PipelineIndex = unsafe { PipelineIndex(NonZero::new_unchecked(5678)) }; pub const TEST_PIPELINE_INDEX: PipelineIndex = unsafe { PipelineIndex(NonZeroU32::new_unchecked(5678)) };
#[cfg(feature = "unstable")] #[cfg(feature = "unstable")]
pub const TEST_PIPELINE_ID: PipelineId = PipelineId { namespace_id: TEST_NAMESPACE, index: TEST_PIPELINE_INDEX }; pub const TEST_PIPELINE_ID: PipelineId = PipelineId { namespace_id: TEST_NAMESPACE, index: TEST_PIPELINE_INDEX };
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[cfg(feature = "unstable")] #[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_INDEX: BrowsingContextIndex = pub const TEST_BROWSING_CONTEXT_INDEX: BrowsingContextIndex =
unsafe { BrowsingContextIndex(NonZero::new_unchecked(8765)) }; unsafe { BrowsingContextIndex(NonZeroU32::new_unchecked(8765)) };
#[cfg(feature = "unstable")] #[cfg(feature = "unstable")]
pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId = pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId =
BrowsingContextId { namespace_id: TEST_NAMESPACE, index: TEST_BROWSING_CONTEXT_INDEX }; BrowsingContextId { namespace_id: TEST_NAMESPACE, index: TEST_BROWSING_CONTEXT_INDEX };

View file

@ -7,135 +7,106 @@
#![cfg_attr(feature = "unstable", feature(nonzero))] #![cfg_attr(feature = "unstable", feature(nonzero))]
#![cfg_attr(feature = "unstable", feature(const_fn))] #![cfg_attr(feature = "unstable", feature(const_fn))]
#![cfg_attr(feature = "unstable", feature(const_nonzero_new))]
#[cfg_attr(not(feature = "unstable"), macro_use)]
extern crate serde; extern crate serde;
pub use imp::*; use std::fmt;
#[cfg(feature = "unstable")] macro_rules! impl_nonzero_fmt {
mod imp { ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
extern crate core; $(
use self::core::nonzero::NonZero as CoreNonZero; impl fmt::$Trait for $Ty {
use serde::{Serialize, Serializer, Deserialize, Deserializer}; #[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
pub use self::core::nonzero::Zeroable; self.get().fmt(f)
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct NonZero<T: Zeroable>(CoreNonZero<T>);
impl<T: Zeroable> NonZero<T> {
#[inline]
pub const unsafe fn new_unchecked(x: T) -> Self {
NonZero(CoreNonZero::new_unchecked(x))
}
#[inline]
pub fn new(x: T) -> Option<Self> {
CoreNonZero::new(x).map(NonZero)
}
#[inline]
pub fn get(self) -> T {
self.0.get()
}
}
// Not using derive because of the additional Clone bound required by the inner impl
impl<T> Serialize for NonZero<T>
where
T: Serialize + Zeroable + Clone,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de, T> Deserialize<'de> for NonZero<T>
where
T: Deserialize<'de> + Zeroable,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
CoreNonZero::deserialize(deserializer).map(NonZero)
}
}
}
#[cfg(not(feature = "unstable"))]
mod imp {
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct NonZero<T: Zeroable>(T);
impl<T: Zeroable> NonZero<T> {
#[inline]
pub unsafe fn new_unchecked(x: T) -> Self {
NonZero(x)
}
#[inline]
pub fn new(x: T) -> Option<Self> {
if x.is_zero() {
None
} else {
Some(NonZero(x))
} }
} )+
#[inline]
pub fn get(self) -> T {
self.0
}
}
/// Unsafe trait to indicate what types are usable with the NonZero struct
pub unsafe trait Zeroable {
/// Whether this value is zero
fn is_zero(&self) -> bool;
}
macro_rules! impl_zeroable_for_pointer_types {
( $( $Ptr: ty )+ ) => {
$(
/// For fat pointers to be considered "zero", only the "data" part needs to be null.
unsafe impl<T: ?Sized> Zeroable for $Ptr {
#[inline]
fn is_zero(&self) -> bool {
// Cast because `is_null` is only available on thin pointers
(*self as *mut u8).is_null()
}
}
)+
}
}
macro_rules! impl_zeroable_for_integer_types {
( $( $Int: ty )+ ) => {
$(
unsafe impl Zeroable for $Int {
#[inline]
fn is_zero(&self) -> bool {
*self == 0
}
}
)+
}
}
impl_zeroable_for_pointer_types! {
*const T
*mut T
}
impl_zeroable_for_integer_types! {
usize u8 u16 u32 u64
isize i8 i16 i32 i64
} }
} }
macro_rules! nonzero_integers {
( $( $Ty: ident($Int: ty); )+ ) => {
$(
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct $Ty(
#[cfg(feature = "unstable")] std::num::$Ty,
#[cfg(not(feature = "unstable"))] $Int,
);
impl $Ty {
#[cfg(feature = "unstable")]
#[inline]
pub const unsafe fn new_unchecked(n: $Int) -> Self {
$Ty(std::num::$Ty::new_unchecked(n))
}
#[cfg(not(feature = "unstable"))]
#[inline]
pub unsafe fn new_unchecked(n: $Int) -> Self {
$Ty(n)
}
#[cfg(feature = "unstable")]
#[inline]
pub fn new(n: $Int) -> Option<Self> {
std::num::$Ty::new(n).map($Ty)
}
#[cfg(not(feature = "unstable"))]
#[inline]
pub fn new(n: $Int) -> Option<Self> {
if n != 0 {
Some($Ty(n))
} else {
None
}
}
#[cfg(feature = "unstable")]
#[inline]
pub fn get(self) -> $Int {
self.0.get()
}
#[cfg(not(feature = "unstable"))]
#[inline]
pub fn get(self) -> $Int {
self.0
}
}
impl_nonzero_fmt! {
(Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
}
impl serde::Serialize for $Ty {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
self.get().serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for $Ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
let value = <$Int>::deserialize(deserializer)?;
match <$Ty>::new(value) {
Some(nonzero) => Ok(nonzero),
None => Err(serde::de::Error::custom("expected a non-zero value")),
}
}
}
)+
}
}
nonzero_integers! {
NonZeroU8(u8);
NonZeroU16(u16);
NonZeroU32(u32);
NonZeroU64(u64);
NonZeroUsize(usize);
}

View file

@ -14,7 +14,7 @@ extern crate nonzero;
#[macro_use] extern crate lazy_static; #[macro_use] extern crate lazy_static;
#[macro_use] extern crate log; #[macro_use] extern crate log;
use nonzero::NonZero; use nonzero::NonZeroUsize;
use std::cell::{Cell, UnsafeCell}; use std::cell::{Cell, UnsafeCell};
use std::ops::Deref; use std::ops::Deref;
use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult}; use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult};
@ -25,7 +25,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
// TODO: can we use the thread-id crate for this? // TODO: can we use the thread-id crate for this?
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ThreadId(NonZero<usize>); pub struct ThreadId(NonZeroUsize);
lazy_static!{ static ref THREAD_COUNT: AtomicUsize = AtomicUsize::new(1); } lazy_static!{ static ref THREAD_COUNT: AtomicUsize = AtomicUsize::new(1); }
@ -33,7 +33,7 @@ impl ThreadId {
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn new() -> ThreadId { fn new() -> ThreadId {
let number = THREAD_COUNT.fetch_add(1, Ordering::SeqCst); let number = THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
ThreadId(NonZero::new(number).unwrap()) ThreadId(NonZeroUsize::new(number).unwrap())
} }
pub fn current() -> ThreadId { pub fn current() -> ThreadId {
THREAD_ID.with(|tls| tls.clone()) THREAD_ID.with(|tls| tls.clone())
@ -57,13 +57,13 @@ impl AtomicOptThreadId {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn load(&self, ordering: Ordering) -> Option<ThreadId> { pub fn load(&self, ordering: Ordering) -> Option<ThreadId> {
let number = self.0.load(ordering); let number = self.0.load(ordering);
NonZero::new(number).map(ThreadId) NonZeroUsize::new(number).map(ThreadId)
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn swap(&self, value: Option<ThreadId>, ordering: Ordering) -> Option<ThreadId> { pub fn swap(&self, value: Option<ThreadId>, ordering: Ordering) -> Option<ThreadId> {
let number = value.map(|id| id.0.get()).unwrap_or(0); let number = value.map(|id| id.0.get()).unwrap_or(0);
let number = self.0.swap(number, ordering); let number = self.0.swap(number, ordering);
NonZero::new(number).map(ThreadId) NonZeroUsize::new(number).map(ThreadId)
} }
} }