rune/runtime/ref.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
use core::fmt;
use core::future::Future;
use core::ops::{Deref, DerefMut};
use core::pin::Pin;
use core::ptr::NonNull;
use core::task::{Context, Poll};
#[cfg(feature = "alloc")]
use ::rust_alloc::rc::Rc;
#[cfg(feature = "alloc")]
use ::rust_alloc::sync::Arc;
pub(super) struct RefVtable {
pub(super) drop: DropFn,
}
type DropFn = unsafe fn(NonNull<()>);
/// A strong owned reference to the given type that can be safely dereferenced.
///
/// # Examples
///
/// Constructed from a static value:
///
/// ```rust
/// use rune::Ref;
///
/// let value: Ref<str> = Ref::from_static("hello world");
/// ```
pub struct Ref<T: ?Sized> {
value: NonNull<T>,
guard: RawAnyGuard,
}
#[cfg(feature = "alloc")]
impl<T> From<Rc<T>> for Ref<T> {
/// Construct from an atomically reference-counted value.
///
/// # Examples
///
/// ```
/// use std::rc::Rc;
/// use rune::Ref;
///
/// let value: Ref<String> = Ref::from(Rc::new(String::from("hello world")));
/// assert_eq!(value.as_ref(), "hello world");
/// ```
fn from(value: Rc<T>) -> Ref<T> {
unsafe fn drop_fn<T>(data: NonNull<()>) {
let _ = Rc::from_raw(data.cast::<T>().as_ptr().cast_const());
}
let value = Rc::into_raw(value);
let value = unsafe { NonNull::new_unchecked(value as *mut _) };
let guard = RawAnyGuard::new(value.cast(), &RefVtable { drop: drop_fn::<T> });
Ref::new(value, guard)
}
}
#[cfg(feature = "alloc")]
impl<T> From<Arc<T>> for Ref<T> {
/// Construct from an atomically reference-counted value.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use rune::Ref;
///
/// let value: Ref<String> = Ref::from(Arc::new(String::from("hello world")));
/// assert_eq!(value.as_ref(), "hello world");
/// ```
fn from(value: Arc<T>) -> Ref<T> {
unsafe fn drop_fn<T>(data: NonNull<()>) {
let _ = Arc::from_raw(data.cast::<T>().as_ptr().cast_const());
}
let value = Arc::into_raw(value);
let value = unsafe { NonNull::new_unchecked(value as *mut _) };
let guard = RawAnyGuard::new(value.cast(), &RefVtable { drop: drop_fn::<T> });
Ref::new(value, guard)
}
}
impl<T: ?Sized> Ref<T> {
pub(super) const fn new(value: NonNull<T>, guard: RawAnyGuard) -> Self {
Self { value, guard }
}
/// Construct an owned reference from a static value.
///
/// # Examples
///
/// ```rust
/// use rune::Ref;
///
/// let value: Ref<str> = Ref::from_static("Hello World");
/// assert_eq!(value.as_ref(), "Hello World");
/// ```
pub const fn from_static(value: &'static T) -> Ref<T> {
let value = unsafe { NonNull::new_unchecked((value as *const T).cast_mut()) };
let guard = RawAnyGuard::new(NonNull::dangling(), &RefVtable { drop: |_| {} });
Self::new(value, guard)
}
/// Map the interior reference of an owned mutable value.
///
/// # Examples
///
/// ```
/// use rune::Ref;
/// use rune::runtime::Bytes;
/// use rune::alloc::try_vec;
///
/// let bytes = rune::to_value(Bytes::from_vec(try_vec![1, 2, 3, 4]))?;
/// let bytes: Ref<Bytes> = rune::from_value(bytes)?;
/// let value: Ref<[u8]> = Ref::map(bytes, |vec| &vec[0..2]);
///
/// assert_eq!(&*value, &[1, 2][..]);
/// # Ok::<_, rune::support::Error>(())
/// ```
#[inline]
pub fn map<U: ?Sized, F>(this: Self, f: F) -> Ref<U>
where
F: FnOnce(&T) -> &U,
{
let Self { value, guard } = this;
// Safety: this follows the same safety guarantees as when the managed
// ref was acquired. And since we have a managed reference to `T`, we're
// permitted to do any sort of projection to `U`.
let value = f(unsafe { value.as_ref() });
Ref::new(value.into(), guard)
}
/// Try to map the reference to a projection.
///
/// # Examples
///
/// ```
/// use rune::Ref;
/// use rune::runtime::Bytes;
/// use rune::alloc::try_vec;
///
/// let bytes = rune::to_value(Bytes::from_vec(try_vec![1, 2, 3, 4]))?;
/// let bytes: Ref<Bytes> = rune::from_value(bytes)?;
///
/// let Ok(value) = Ref::try_map(bytes, |bytes| bytes.get(0..2)) else {
/// panic!("Conversion failed");
/// };
///
/// assert_eq!(&value[..], &[1, 2][..]);
/// # Ok::<_, rune::support::Error>(())
/// ```
#[inline]
pub fn try_map<U: ?Sized, F>(this: Self, f: F) -> Result<Ref<U>, Ref<T>>
where
F: FnOnce(&T) -> Option<&U>,
{
let Self { value, guard } = this;
// Safety: this follows the same safety guarantees as when the managed
// ref was acquired. And since we have a managed reference to `T`, we're
// permitted to do any sort of projection to `U`.
unsafe {
let Some(value) = f(value.as_ref()) else {
return Err(Ref::new(value, guard));
};
Ok(Ref::new(value.into(), guard))
}
}
/// Convert into a raw pointer and associated raw access guard.
///
/// # Safety
///
/// The returned pointer must not outlive the associated guard, since this
/// prevents other uses of the underlying data which is incompatible with
/// the current.
pub fn into_raw(this: Self) -> (NonNull<T>, RawAnyGuard) {
(this.value, this.guard)
}
/// Convert a raw reference and guard into a regular reference.
///
/// # Safety
///
/// The caller is responsible for ensuring that the raw reference is
/// associated with the specific pointer.
pub unsafe fn from_raw(value: NonNull<T>, guard: RawAnyGuard) -> Self {
Self { value, guard }
}
}
impl<T: ?Sized> AsRef<T> for Ref<T> {
#[inline]
fn as_ref(&self) -> &T {
self
}
}
impl<T: ?Sized> Deref for Ref<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
// Safety: An owned ref holds onto a hard pointer to the data,
// preventing it from being dropped for the duration of the owned ref.
unsafe { self.value.as_ref() }
}
}
impl<T: ?Sized> fmt::Debug for Ref<T>
where
T: fmt::Debug,
{
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, fmt)
}
}
/// A strong owned mutable reference to the given type that can be safely
/// dereferenced.
///
/// # Examples
///
/// Constructed from a static value:
///
/// ```rust
/// use rune::Mut;
///
/// let value: Mut<[u8]> = Mut::from_static(&mut [][..]);
/// assert_eq!(&value[..], b"");
/// ```
pub struct Mut<T: ?Sized> {
value: NonNull<T>,
guard: RawAnyGuard,
}
impl<T: ?Sized> Mut<T> {
pub(super) const fn new(value: NonNull<T>, guard: RawAnyGuard) -> Self {
Self { value, guard }
}
/// Construct an owned mutable reference from a static value.
///
/// # Examples
///
/// ```rust
/// use rune::Mut;
///
/// let value: Mut<[u8]> = Mut::from_static(&mut [][..]);
/// assert_eq!(&value[..], b"");
/// ```
pub fn from_static(value: &'static mut T) -> Mut<T> {
let value = unsafe { NonNull::new_unchecked((value as *const T).cast_mut()) };
let guard = RawAnyGuard::new(NonNull::dangling(), &RefVtable { drop: |_| {} });
Self::new(value, guard)
}
/// Map the interior reference of an owned mutable value.
///
/// # Examples
///
/// ```
/// use rune::Mut;
/// use rune::runtime::Bytes;
/// use rune::alloc::try_vec;
///
/// let bytes = rune::to_value(Bytes::from_vec(try_vec![1, 2, 3, 4]))?;
/// let bytes: Mut<Bytes> = rune::from_value(bytes)?;
/// let value: Mut<[u8]> = Mut::map(bytes, |bytes| &mut bytes[0..2]);
///
/// assert_eq!(&*value, &mut [1, 2][..]);
/// # Ok::<_, rune::support::Error>(())
/// ```
pub fn map<U: ?Sized, F>(this: Self, f: F) -> Mut<U>
where
F: FnOnce(&mut T) -> &mut U,
{
let Self {
mut value, guard, ..
} = this;
// Safety: this follows the same safety guarantees as when the managed
// ref was acquired. And since we have a managed reference to `T`, we're
// permitted to do any sort of projection to `U`.
let value = f(unsafe { value.as_mut() });
Mut::new(value.into(), guard)
}
/// Try to map the mutable reference to a projection.
///
/// # Examples
///
/// ```
/// use rune::Mut;
/// use rune::runtime::Bytes;
/// use rune::alloc::try_vec;
///
/// let bytes = rune::to_value(Bytes::from_vec(try_vec![1, 2, 3, 4]))?;
/// let bytes: Mut<Bytes> = rune::from_value(bytes)?;
///
/// let Ok(mut value) = Mut::try_map(bytes, |bytes| bytes.get_mut(0..2)) else {
/// panic!("Conversion failed");
/// };
///
/// assert_eq!(&mut value[..], &mut [1, 2][..]);
/// # Ok::<_, rune::support::Error>(())
/// ```
#[inline]
pub fn try_map<U: ?Sized, F>(this: Self, f: F) -> Result<Mut<U>, Mut<T>>
where
F: FnOnce(&mut T) -> Option<&mut U>,
{
let Self {
mut value, guard, ..
} = this;
// Safety: this follows the same safety guarantees as when the managed
// ref was acquired. And since we have a managed reference to `T`, we're
// permitted to do any sort of projection to `U`.
unsafe {
let Some(value) = f(value.as_mut()) else {
return Err(Mut::new(value, guard));
};
Ok(Mut::new(value.into(), guard))
}
}
/// Convert into a raw pointer and associated raw access guard.
///
/// # Safety
///
/// The returned pointer must not outlive the associated guard, since this
/// prevents other uses of the underlying data which is incompatible with
/// the current.
pub fn into_raw(this: Self) -> (NonNull<T>, RawAnyGuard) {
(this.value, this.guard)
}
/// Convert a raw mutable reference and guard into a regular mutable
/// reference.
///
/// # Safety
///
/// The caller is responsible for ensuring that the raw mutable reference is
/// associated with the specific pointer.
pub unsafe fn from_raw(value: NonNull<T>, guard: RawAnyGuard) -> Self {
Self { value, guard }
}
}
impl<T: ?Sized> AsRef<T> for Mut<T> {
#[inline]
fn as_ref(&self) -> &T {
self
}
}
impl<T: ?Sized> AsMut<T> for Mut<T> {
#[inline]
fn as_mut(&mut self) -> &mut T {
self
}
}
impl<T: ?Sized> Deref for Mut<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: An owned mut holds onto a hard pointer to the data,
// preventing it from being dropped for the duration of the owned mut.
unsafe { self.value.as_ref() }
}
}
impl<T: ?Sized> DerefMut for Mut<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// Safety: An owned mut holds onto a hard pointer to the data,
// preventing it from being dropped for the duration of the owned mut.
unsafe { self.value.as_mut() }
}
}
impl<T: ?Sized> fmt::Debug for Mut<T>
where
T: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, fmt)
}
}
impl<F> Future for Mut<F>
where
F: Unpin + Future,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
// NB: inner Future is Unpin.
let this = self.get_mut();
Pin::new(&mut **this).poll(cx)
}
}
/// A raw guard for a [`Ref`] or a [`Mut`] that has been converted into its raw
/// components through [`Ref::into_raw`] or [`Mut::into_raw`].
pub struct RawAnyGuard {
data: NonNull<()>,
vtable: &'static RefVtable,
}
impl RawAnyGuard {
pub(super) const fn new(data: NonNull<()>, vtable: &'static RefVtable) -> Self {
Self { data, vtable }
}
}
impl Drop for RawAnyGuard {
fn drop(&mut self) {
// Safety: type and referential safety is guaranteed at construction
// time, since all constructors are unsafe.
unsafe {
(self.vtable.drop)(self.data);
}
}
}