Skip to content

Commit

Permalink
Merge #7
Browse files Browse the repository at this point in the history
7: Add IntoRawPtr and FromRawPtr impls for &T r=torkleyy a=dbkaplun



Co-authored-by: Dan Kaplun <[email protected]>
  • Loading branch information
bors[bot] and dbkaplun committed May 14, 2018
2 parents d8c7026 + cc7e960 commit 971a2e9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::cell::UnsafeCell;
use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;
use std::mem;
Expand All @@ -28,7 +29,7 @@ where
P: IntoRawPtr + FromRawPtr,
{
inner: AtomicPtr<()>,
data: PhantomData<P>,
data: PhantomData<UnsafeCell<P>>,
}

impl<P> Debug for Atom<P>
Expand Down Expand Up @@ -147,12 +148,12 @@ where

unsafe impl<P> Send for Atom<P>
where
P: IntoRawPtr + FromRawPtr,
P: IntoRawPtr + FromRawPtr + Send,
{
}
unsafe impl<P> Sync for Atom<P>
where
P: IntoRawPtr + FromRawPtr,
P: IntoRawPtr + FromRawPtr + Send,
{
}

Expand Down Expand Up @@ -194,6 +195,21 @@ impl<T> FromRawPtr for Arc<T> {
}
}

// This impl can be useful for stack-allocated and 'static values.
impl<'a, T> IntoRawPtr for &'a T {
#[inline]
fn into_raw(self) -> *mut () {
self as *const _ as *mut ()
}
}

impl<'a, T> FromRawPtr for &'a T {
#[inline]
unsafe fn from_raw(ptr: *mut ()) -> &'a T {
&*(ptr as *mut T)
}
}

/// Transforms lifetime of the second pointer to match the first.
#[inline]
unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S, ptr: &T) -> &'a T {
Expand Down
7 changes: 7 additions & 0 deletions tests/atom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,10 @@ fn lifo_drop() {
drop(atom);
assert_eq!(2, v.load(Ordering::SeqCst));
}

#[test]
fn borrow() {
let a = Atom::new(&5);
assert_eq!(a.swap(&7, Ordering::Relaxed), Some(&5));
assert_eq!(a.take(Ordering::Relaxed), Some(&7));
}

0 comments on commit 971a2e9

Please sign in to comment.