From e5a602e364d5083a4c475747ad08c81ef29897bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20K=C3=A5re=20Alsaker?= Date: Sun, 1 Apr 2018 09:43:19 +0200 Subject: [PATCH] Add OneThread which only allows its inner value to be used in one thread --- src/librustc_data_structures/sync.rs | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/librustc_data_structures/sync.rs b/src/librustc_data_structures/sync.rs index 0f534f0adec4..ad524916f0cb 100644 --- a/src/librustc_data_structures/sync.rs +++ b/src/librustc_data_structures/sync.rs @@ -33,6 +33,8 @@ use std::cmp::Ordering; use std::fmt::Debug; use std::fmt::Formatter; use std::fmt; +use std; +use std::ops::{Deref, DerefMut}; use owning_ref::{Erased, OwningRef}; cfg_if! { @@ -161,6 +163,8 @@ cfg_if! { use parking_lot::Mutex as InnerLock; use parking_lot::RwLock as InnerRwLock; + use std::thread; + pub type MetadataRef = OwningRef, [u8]>; /// This makes locks panic if they are already held. @@ -439,3 +443,54 @@ impl Clone for RwLock { RwLock::new(self.borrow().clone()) } } + +/// A type which only allows its inner value to be used in one thread. +/// It will panic if it is used on multiple threads. +#[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)] +pub struct OneThread { + #[cfg(parallel_queries)] + thread: thread::ThreadId, + inner: T, +} + +unsafe impl std::marker::Sync for OneThread {} +unsafe impl std::marker::Send for OneThread {} + +impl OneThread { + #[inline(always)] + fn check(&self) { + #[cfg(parallel_queries)] + assert_eq!(thread::current().id(), self.thread); + } + + #[inline(always)] + pub fn new(inner: T) -> Self { + OneThread { + #[cfg(parallel_queries)] + thread: thread::current().id(), + inner, + } + } + + #[inline(always)] + pub fn into_inner(value: Self) -> T { + value.check(); + value.inner + } +} + +impl Deref for OneThread { + type Target = T; + + fn deref(&self) -> &T { + self.check(); + &self.inner + } +} + +impl DerefMut for OneThread { + fn deref_mut(&mut self) -> &mut T { + self.check(); + &mut self.inner + } +}