1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-01-31 00:02:53 +01:00
actix-net/src/cell.rs

65 lines
1.2 KiB
Rust
Raw Normal View History

2018-10-02 22:18:07 -07:00
//! Custom cell impl
#[cfg(feature = "cell")]
use std::cell::UnsafeCell;
#[cfg(not(feature = "cell"))]
use std::cell::{Ref, RefCell, RefMut};
use std::fmt;
use std::rc::Rc;
2018-12-03 13:49:46 -08:00
#[doc(hidden)]
pub struct Cell<T> {
2018-10-02 22:18:07 -07:00
#[cfg(feature = "cell")]
inner: Rc<UnsafeCell<T>>,
#[cfg(not(feature = "cell"))]
inner: Rc<RefCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
#[cfg(feature = "cell")]
impl<T> Cell<T> {
2018-12-03 13:49:46 -08:00
pub fn new(inner: T) -> Self {
2018-10-02 22:18:07 -07:00
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
2018-12-03 13:49:46 -08:00
pub fn borrow(&self) -> &T {
2018-10-02 22:18:07 -07:00
unsafe { &*self.inner.as_ref().get() }
}
2018-12-03 13:49:46 -08:00
pub fn borrow_mut(&self) -> &mut T {
2018-10-02 22:18:07 -07:00
unsafe { &mut *self.inner.as_ref().get() }
}
}
#[cfg(not(feature = "cell"))]
impl<T> Cell<T> {
2018-12-03 13:49:46 -08:00
pub fn new(inner: T) -> Self {
2018-10-02 22:18:07 -07:00
Self {
inner: Rc::new(RefCell::new(inner)),
}
}
2018-12-03 13:49:46 -08:00
pub fn borrow(&self) -> Ref<T> {
2018-10-02 22:18:07 -07:00
self.inner.borrow()
}
2018-12-03 13:49:46 -08:00
pub fn borrow_mut(&self) -> RefMut<T> {
2018-10-02 22:18:07 -07:00
self.inner.borrow_mut()
}
}