Skip to main content

Brc

Struct Brc 

Source
pub struct Brc<T: ?Sized + SupportedPointee, A: Allocator = Global> { /* private fields */ }
Expand description

A thread-safe reference counted object, biased towards a particular thread.

§Differences from Arc

Most differences come from the fact that Self::strong_count is not exact. This means that Brc::get_mut and Brc::try_unwrap can fail spuriously even if the Arc is logically unique. It also means that Brc::into_inner cannot provide the same guarantees as Arc::into_inner.

§Allocator

The Brc is parameterized by an Allocator just like Arc. However, the allocator is stored in the object header and so is shared across all references to a particular object. Although this is mainly due to design limitations, it obliviates the need for an A: Clone bound in some places that Arc requires that. However, it does add an A: Clone bound to Brc::into_raw_with_allocator.

§Deferred Destruction & Deferred Panics

Destruction is not guaranteed to occur immediately when the last reference is dropped. It may be deferred until collect is called on another thread.

Since collect is called implicitly by Brc::clone, Brc::clone and Brc::new, any of these functions could panic while executing the deferred destructor of an unrelated object. If this is unacceptable, either use the Brc::drop_no_collect and Brc::clone_no_collect functions or the nounwind crate.

Implementations§

Source§

impl<T> Brc<[T]>

Source

pub fn clone_from_slice(slice: &[T]) -> Self
where T: Clone,

Create a new Brc, cloning each element from the specified slice.

Equivalent to From<[T]>, but potentially clearer. Prefer using Brc::copy_from_slice wherever possible, as copying is much faster than cloning.

§Panics

Will panic if T::clone does, in addition to the cases that Self::new does.

Source

pub fn copy_from_slice(slice: &[T]) -> Self
where T: Copy,

Create a new Brc, using a memcpy of the specified slice

This is more efficient than Self::clone_from_slice or From<&[T]>, by taking advantage of the T: Copy bound. Even on nightly, this library avoids specialization as it is an “incomplete feature” with soundness issues.

§Panics

This function should only panic in the cases Self::new does.

Source§

impl<T> Brc<T>

Source

pub fn new(value: T) -> Brc<T>

Construct a new Brc with the specified value.

§Panics

This function will trigger an unwinding panic only if collect or std::alloc::handle_alloc_error does.

It may abort if internal state appears corrupted.

Source

pub fn new_with(func: impl FnOnce() -> T) -> Self

Construct a new Brc, using a closure to initialize the specified value.

This can potentially improve performance by allowing values to be constructed in place.

§Panics

This function will panic whenever the closure does, in addition to the cases that Self::new does.

Source

pub fn pin(value: T) -> Pin<Self>

Allocates a Pin<Brc<T>>, as if wrapping Self::new in a Pin.

Source§

impl<T, A: Allocator> Brc<T, A>

Source

pub fn new_in(value: T, alloc: A) -> Self

Construct a new Brc with the specified value, using a particular allocator.

§Panics

May panic in the same cases described by Self::new, or if any method on the allocator panics.

Source

pub fn new_with_in(func: impl FnOnce() -> T, alloc: A) -> Self

Construct a new Brc, using a closure to initialize the specified value, along with using a particular allocator.

This can potentially improve performance by allowing values to be constructed in place.

§Panics

May panic in the same cases as Self::new_with, or if any method on the allocator does.

Source

pub fn try_unwrap(this: Self) -> Result<T, Self>
where T: Sized,

If the Brc is uniquely owned, return the inner value.

Like Self::get_mut, this may fail spuriously (as Self::is_unique can have false positive).

This suffers from the same race condition described in Arc::try_unwrap. In particular, this means that if all threads call Arc::try_unwrap, it is possible that the value is dropped and no thread gets the value. Unfortunately, there is no solution

§Errors

Returns an Err holding the original value, if the value is not known to be unique.

Source

pub fn into_inner(this: Self) -> Option<T>

If the Brc is uniquely owned, return the inner value.

Like Self::get_mut, this may fail spuriously (as Self::is_unique can have false positive).

Unlike Arc::into_inner, this does not currently avoid the race condition present in Self::try_unwrap. This means that if all threads call Arc::try_unwrap, it is possible that the value is dropped and no thread gets the value.

This is because Self::strong_count is not always exact, and dropping from the non-biased thread sometimes requires placing objects in the internal queue. In particular, if many refcounts are incremented on the biased threads, but then have Self::into_inner called on a non-biased thread, then the non-biased thread will not know when the value actually becomes unique, and will have to wait until the object is placed in the queue and later processed.

Source

pub fn pin_in(data: T, alloc: A) -> Pin<Self>

Constructs a Pin<Brc<T>> using the specified allocator.

Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Brc<T, A>

Source

pub fn allocator(this: &Self) -> &A

Return a reference to the underlying allocator.

Mirrors Arc::allocator.

Source

pub fn strong_count(this: &Self) -> Result<usize, ImpreciseRefCountError>

Return the number of strong references to the object, or an error if that value cannot be pricelessly determined.

If this thread is the biased thread, then it can always determine the true reference count. If it is not the biased thread, then it can only approximate the value.

§Errors

Gives an ImpreciseRefCountError if not on the biased thread, and the true reference count cannot be determined.

Source

pub fn weak_count(this: &Self) -> Result<usize, ImpreciseRefCountError>

Returns the number of weak pointers to the object, or an error if that value cannot be precisely determined.

§Errors

Gives an ImpreciseRefCountError if not on the biased thread, and the true reference count cannot be determined.

Source

pub fn is_unique(this: &Self) -> bool

Determine if this Brc is uniquely owned.

Mirrors std::sync::Arc::is_unique.

Due to the nature of biased reference counting, this may have false-negatives when called on a non-biased thread. However, it will never have false positives. See Self::strong_count for details.

Source

pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T

Return a mutable reference to the value in this Brc, unsafely assuming if it is uniquely owned.

See also Self::get_mut which clones the value instead of returning None.

§Safety

This is safe if Self::is_unique returns true, but due to false negatives from this function may be true in other cases.

Trigger immediate undefined behavior if there are any other references to the inner value, as a &mut T reference must always be unique.

Source

pub fn get_mut(this: &mut Self) -> Option<&mut T>

Return a mutable reference to the value in this Brc, or None if it is not uniquely owned.

This may fail spuriously on a non-biased thread, due to inability to determine the true value of the reference count. In other words, Self::is_unique has false negatives.

See also Self::make_mut which clones the value instead of returning None.

Source

pub fn make_mut(this: &mut Self) -> &mut T
where T: Clone, A: Clone,

Return a mutable reference to this Brc if it is uniquely owned, or Clone it to make it unique otherwise.

May Clone the value unnecessarily if uniqueness can not be guaranteed by Self::is_unique.

See also Self::get_mut which returns None instead of cloning the value. This mirrors the Arc::make_mut method, but may involve m

Source

pub fn downgrade(this: &Self) -> Weak<T, A>
where T: SupportedWeakPointee,

Downgrade into a new weak reference.

Mirrors Arc::downgrade.

Source

pub unsafe fn from_raw(ptr: *const T) -> Self

Create a Brc from a raw pointer, originating from Brc::into_raw.

Mirrors Arc::from_raw.

See also Brc::decrement_strong_count, which directly mutates the reference count without creating a owned value. This is subject to roughly the same safety requirements.

Because the Brc stores the allocator in the header (as discussed in the type docs), this function works fine for any allocator. However, a Brc::from_raw_in function is added for completeness.

§Safety

This must correspond exactly to an owned reference count from Brc::into_raw, and is vulnerable to double-free if called multiple times on the same pointer.

This is only valid for the result of Brc::into_raw, not for any other piece of memory.

§Panics

This function is infallible.

Source

pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self

Create a Brc from a raw pointer along with its allocator, originating from Brc::into_raw_with_allocator.

Mirrors Arc::from_raw_in.

This function currently discards the allocator and calls Self::into_raw. For future-proofing and compatibility with Arc, it is required that the allocator is equivalent to calling Self::allocator on the original reference.

§Safety

Same requirements as Brc::from_raw.

§Panics

This function is infallible unless the allocator’s drop function panics.

Source

pub fn into_raw(this: Self) -> *const T

Consumes this Brc, converting it into a raw pointer.

Mirrors Arc::into_raw. Because the allocator is stored in the header, this works well with any allocator.

§Safety

This is perfectly safe, but may leak memory.

§Panics

This function is infallible.

Source

pub fn into_raw_with_allocator(this: Self) -> (*const T, A)
where A: Clone,

Consumes this Brc, converting it into a raw pointer along with a copy of the underlying allocator.

Mirrors Arc::into_raw_with_allocator, but needs to add a A: Clone bound because the allocator is stored in the header (see type-level docs for details) If you just want to call Brc::from_raw_in later, prefer Brc::into_raw and Brc::from_raw which avoid cloning the allocator. Because the allocator is stored in the header, these functions work for any allocator (unlike Arc).

§Safety

This is perfectly safe, but may leak memory.

§Panics

This function is infallible unless the allocator clone function panics.

Source

pub fn as_ptr(this: &Self) -> *const T

Convert this Brc into a raw pointer, without affecting the reference count.

Mirrors Arc::as_ptr.

This will give the same result as Self::into_raw would, but does not consume ownership.

§Panics

This function is infallible.

Source

pub unsafe fn increment_strong_count(ptr: *const T)

Increments the strong reference count on the Brc associated with the specified pointer.

Similarly to Self::clone_no_collect, this does not implicitly call collect. This is a low-level function which leaves that choice to the user.

Mirrors Arc::increment_strong_count

§Panics

See Self::clone_no_collect for details.

§Safety

The pointer must have been obtained through Brc::into_raw or Brc::as_ptr, have the correct type, and still point to valid memory (not dropped).

Source

pub unsafe fn decrement_strong_count(ptr: *const T)

Decrements the strong reference count on the Brc associated with the specified pointer.

Similarly to Self::drop_no_collect, this does not implicitly call collect. This is a low-level function which leaves that choice to the user.

Mirrors Arc::decrement_strong_count.

§Panics

See Self::drop_no_collect for details.

§Safety

The pointer must have been obtained through Brc::into_raw or Brc::as_ptr, have the correct type, and still point to valid memory (not dropped).

Each decrement must match a corresponding increment, or else use after free must occur. Must not decrement the last reference count while other Brc references are active.

Source

pub fn ptr_eq(this: &Self, other: &Self) -> bool

Checks if this points to the same object as the other.

This does not compare pointer metadata for trait objects, just like std::sync::Arc::ptr_eq and core::ptr::addr_eq.

Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Brc<T, A>

Source

pub fn clone_no_collect(this: &Self) -> Self

Clone this reference without invoking collect.

§Panics

Unlike Clone, this function does not call collect and so will never panic. However, it may abort if the reference count overflows or internal state appears corrupted.

Source

pub fn drop_no_collect(this: Self)

Drop this reference without invoking collect.

§Panics

Unlike drop which can panic due to collect, this function only panics if the underlying destructor does. Similarly to drop the destructor may be deferred, meaning a panicking destructor may not happen right away.

This function may abort if internal state appears corrupted.

Source

pub fn clone_shared(this: &Self) -> Self

Clone this reference count by incrementing the shared count.

This function works the same regardless of the thread its called on. Even if this is the biased thread, this still increments the shared count.

Trait Implementations§

Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> AsRef<T> for Brc<T, A>

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Borrow<T> for Brc<T, A>

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Clone for Brc<T, A>

Source§

fn clone(&self) -> Self

Create a new reference to the underlying object.

This implicitly calls collect to help cleanup garbage from other threads. Use Self::clone_no_collect to avoid this.

§Panics

This function will panic only if collect panics.

This function may abort if internal state appears corrupted, or if a reference count overflows.

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, U: ?Sized + SupportedPointee, A: Allocator> CoerciblePtr<U> for Brc<T, A>

Source§

type Pointee = T

The type we point to. This influences which kinds of unsizing are possible.
Source§

type Output = Brc<U, A>

The output type when unsizing the pointee to U.
Source§

fn as_sized_ptr(&mut self) -> *mut Self::Pointee

Get the raw inner pointer.
Source§

unsafe fn replace_ptr(self, new: *mut U) -> Self::Output

Replace the container inner pointer with an unsized version. Read more
Source§

impl<T: ?Sized + SupportedPointee + Debug, A: Allocator> Debug for Brc<T, A>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Deref for Brc<T, A>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &T

Dereferences the value.
Source§

impl<T: ?Sized + SupportedPointee + Display, A: Allocator> Display for Brc<T, A>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Drop for Brc<T, A>

Available on non-crate feature nightly-may-dangle only.
Source§

fn drop(&mut self)

Drops a reference to the underlying object, potentially freeing it if there are otherwise no references.

This implicitly calls collect to help cleanup garbage from other threads. Use Self::drop_no_collect to avoid this.

Due to the nature of biased reference counting, there are some cases where destruction may be deferred.

§Panics

This may panic if the underlying destructor panics, or if collect panics while executing a deferred destructor.

This may abort if internal state appears corrupted.

Source§

impl<T: ?Sized + SupportedPointee + Error, A: Allocator> Error for Brc<T, A>

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl<T: Clone> From<&[T]> for Brc<[T]>

Create a new Brc<[T]> by cloning the contents of the specified slice.

Equivalent to calling Brc::clone_from_slice. Prefer using Brc::copy_from_slice wherever possible, as copying is much faster than cloning.

Source§

fn from(src: &[T]) -> Self

Converts to this type from the input type.
Source§

impl<T: Clone> From<&mut [T]> for Brc<[T]>

Source§

fn from(value: &mut [T]) -> Self

Converts to this type from the input type.
Source§

impl From<&mut str> for Brc<str>

Source§

fn from(value: &mut str) -> Self

Converts to this type from the input type.
Source§

impl From<&str> for Brc<str>

Source§

fn from(value: &str) -> Self

Converts to this type from the input type.
Source§

impl<T, const N: usize> From<[T; N]> for Brc<[T]>

Source§

fn from(src: [T; N]) -> Self

Converts to this type from the input type.
Source§

impl<T: ?Sized + SupportedPointee> From<Box<T>> for Brc<T>

Convert from a Box to a Brc.

This conversion is guaranteed not to copy values to the stack, which means large values cannot trigger stack overflow.

However, this cannot reuse the allocation as a Box has no room to hold the reference count.

Source§

fn from(value: Box<T>) -> Self

Converts to this type from the input type.
Source§

impl From<String> for Brc<str>

Source§

fn from(value: String) -> Self

Converts to this type from the input type.
Source§

impl<T> From<T> for Brc<T>

Source§

fn from(value: T) -> Self

Converts to this type from the input type.
Source§

impl<T> From<Vec<T>> for Brc<[T]>

Source§

fn from(src: Vec<T>) -> Self

Converts to this type from the input type.
Source§

impl<T> FromIterator<T> for Brc<[T]>

Source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<T: ?Sized + SupportedPointee + Hash, A: Allocator> Hash for Brc<T, A>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T: ?Sized + SupportedPointee + Ord, A: Allocator> Ord for Brc<T, A>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T: ?Sized + SupportedPointee + PartialEq, A: Allocator> PartialEq for Brc<T, A>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &Self) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: ?Sized + SupportedPointee + PartialOrd, A: Allocator> PartialOrd for Brc<T, A>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
Source§

fn lt(&self, other: &Self) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
Source§

fn gt(&self, other: &Self) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
Source§

fn le(&self, other: &Self) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
Source§

fn ge(&self, other: &Self) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> CloneStableDeref for Brc<T, A>

Source§

impl<T: ?Sized + SupportedPointee + Eq, A: Allocator> Eq for Brc<T, A>

Source§

impl<T: ?Sized + SupportedPointee + Sync + Send, A: Allocator + Send + Sync> Send for Brc<T, A>

Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> StableDeref for Brc<T, A>

Source§

impl<T: ?Sized + SupportedPointee + Sync + Send, A: Allocator + Send + Sync> Sync for Brc<T, A>

Source§

impl<T: ?Sized + SupportedPointee, A: Allocator> Unpin for Brc<T, A>

Source§

impl<T> ZeroableInOption for Brc<T>

A Brc is just a NonNull pointer, so Option<Self> can be safely zero-initialized

This requires T: Sized because not all pointer metadata is safe to zero-initialize.

Auto Trait Implementations§

§

impl<T, A> Freeze for Brc<T, A>
where <T as Pointee>::Metadata: Sized, T: ?Sized,

§

impl<T, A> RefUnwindSafe for Brc<T, A>

§

impl<T, A> UnsafeUnpin for Brc<T, A>
where <T as Pointee>::Metadata: Sized, T: ?Sized,

§

impl<T, A> UnwindSafe for Brc<T, A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T, U> CoerceUnsize<U> for T
where T: CoerciblePtr<U>, U: ?Sized,

Source§

fn unsize<F>(self, with: Coercion<Self::Pointee, U, F>) -> Self::Output
where F: FnOnce(*const Self::Pointee) -> *const U,

Convert a pointer, as if with unsize coercion. Read more
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.