rc

Reference-counted (Rc) and weak reference (Weak) types for MoonBit

rc
weak
reference-counting
smart-pointer
moon add tonyfettes/rc@0.1.1
Download zip
Version
0.1.1
License
Apache-2.0
Last updated
5 months ago
Downloads
19
README

#tonyfettes/rc

Reference-counted (Rc) and weak reference (Weak) types for MoonBit.

When the last Rc handle to a value is dropped, the inner value is cleared. Weak references can observe this: Weak::get returns None once all Rc handles are gone.

Native target only. This package uses a C FFI finalizer (moonbit_make_external_object) to detect when an Rc is dropped, so it requires preferred-target: "native".

#Installation

moon add tonyfettes/rc

#API

type Rc[T] Rc::new(T) -> Rc[T] // wrap a value Rc::get(Rc[T]) -> T // consume the Rc and extract the value type Weak[T] Weak::new(Rc[T]) -> Weak[T] // create a weak reference Weak::get(Weak[T]) -> T? // Some(value) while any Rc is alive, None after

#Usage

let rc = @rc.Rc::new(42)
let weak = @rc.Weak::new(rc)
assert_eq(weak.get(), Some(42))
ignore(rc) // last Rc dropped — value cleared
assert_eq(weak.get(), None)

#License

Apache-2.0

type Rc[T]

#
Rc::get

fn[T] Rc::get(self : Rc[T]) -> T

#
Rc::new

fn[T] Rc::new(value : T) -> Rc[T]

#
Weak

type Weak[T]

#
Weak::get

fn[T] Weak::get(self : Weak[T]) -> T?

#
Weak::new

fn[T] Weak::new(rc : Rc[T]) -> Weak[T]