Giter VIP home page Giter VIP logo

cactusref's Introduction

CactusRef

GitHub Actions Discord Twitter
Crate API API trunk

Single-threaded, cycle-aware, reference-counting pointers. 'Rc' stands for 'Reference Counted'.

What if, hear me out, we put a hash map in a smart pointer?

CactusRef is a single-threaded, reference-counted smart pointer that can deallocate cycles without having to resort to weak pointers. Rc from std can be difficult to work with because creating a cycle of Rcs will result in a memory leak.

CactusRef is a near drop-in replacement for std::rc::Rc which introduces additional APIs for bookkeeping ownership relationships in a graph of Rcs.

Combining CactusRef's adoption APIs for tracking links in the object graph and driving garbage collection with Rust's drop glue implements a kind of tracing garbage collector. Graphs of CactusRefs detect cycles local to the graph of connected CactusRefs and do not need to scan the whole heap as is typically required in a tracing garbage collector.

Cycles of CactusRefs are deterministically collected and deallocated when they are no longer reachable from outside of the cycle.

Self-referential Data Structures

CactusRef can be used to implement self-referential data structures such as a doubly-linked list without using weak references.

Usage

Add this to your Cargo.toml:

[dependencies]
cactusref = "0.5.0"

CactusRef is mostly a drop-in replacement for std::rc::Rc, which can be used like:

use cactusref::Rc;

let node = Rc::new(123_i32);
let another = Rc::clone(&node);
assert_eq!(Rc::strong_count(&another), 2);

let weak = Rc::downgrade(&node);
assert!(weak.upgrade().is_some());

Or start making self-referential data structures like:

use std::cell::RefCell;
use cactusref::{Adopt, Rc};

struct Node {
    next: Option<Rc<RefCell<Node>>>,
    data: i32,
}

let left = Node { next: None, data: 123 };
let left = Rc::new(RefCell::new(left));

let right = Node { next: Some(Rc::clone(&left)), data: 456 };
let right = Rc::new(RefCell::new(right));

unsafe {
    // bookkeep that `right` has added an owning ref to `left`.
    Rc::adopt_unchecked(&right, &left);
}

left.borrow_mut().next = Some(Rc::clone(&right));

unsafe {
    // bookkeep that `left` has added an owning ref to `right`.
    Rc::adopt_unchecked(&left, &right);
}

let mut node = Rc::clone(&left);
// this loop will print:
//
// > traversing ring and found node with data = 123
// > traversing ring and found node with data = 456
// > traversing ring and found node with data = 123
// > traversing ring and found node with data = 456
// > traversing ring and found node with data = 123
for _ in 0..5 {
    println!("traversing ring and found node with data = {}", node.borrow().data);
    let next = if let Some(ref next) = node.borrow().next {
        Rc::clone(next)
    } else {
        break;
    };
    node = next;
}
assert_eq!(Rc::strong_count(&node), 3);
drop(node);

drop(left);
drop(right);
// All members of the ring are garbage collected and deallocated.

Maturity

CactusRef is experimental. This crate has several limitations:

  • CactusRef is nightly only.
  • Cycle detection requires unsafe code to use.

CactusRef is a non-trivial extension to std::rc::Rc and has not been proven to be safe. Although CactusRef makes a best effort to abort the program if it detects a dangling Rc, this crate may be unsound.

no_std

CactusRef is no_std compatible with an optional and enabled by default dependency on std. CactusRef depends on the alloc crate.

Crate features

All features are enabled by default.

  • std - Enable linking to the Rust Standard Library. Enabling this feature adds Error implementations to error types in this crate.

License

CactusRef is licensed with the MIT License (c) Ryan Lopopolo.

CactusRef is derived from Rc in the Rust standard library @ f586d79d which is dual licensed with the MIT License and Apache 2.0 License.

cactusref's People

Contributors

artichoke-ci avatar dependabot[bot] avatar lopopolo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

cactusref's Issues

`Rc::adopt` requires both `T`s to be the same

Say I'm making a structure that contains something else - this does not work:

impl Container{
	fn new(contained: Rc<Contained>) -> Rc<Self> {
		let new = Rc::new(Self { contained });
		unsafe { Rc::adopt(&new, &new.contained) };
		new
	}
}

That's because Rc::adopt requires both Ts to be the same. Is this intended? I looked at the linked list example, and it looks like it's calling adopt like Rc::adopt(&parent, &child) for every Rc<Node<T>> that contains an Rc<Node<T>>, and that only works because Node<T> is itself.

Add .editorconfig

An .editorconfig is a cross-editor and cross-ide format configuration mechanism which and enforce Artichoke code formatting conventions.

Specify:

  • utf-8 charset
  • strip trailing whitespace except diff and markdown
  • eol = lf
  • spacing

for file types:

  • rs
  • md
  • sh
  • h, c, cc, cpp
  • Makefile, .make
  • diff
  • json
  • js
  • ts
  • css
  • html
  • svg
  • xml
  • yml, yaml
  • erb
  • rb
  • json
  • toml
  • Dockerfile

Add Docs on Unsafety to Crate Root and README

The Rc implementation of Adoptable includes some docs on the safety implications of using these APIs incorrectly. This documentation should exist prominently in the crate root and the README

/// # Safety
///
/// Modifying the object graph by removing links after calling `adopt`
/// requires updating the bookkeeping with [`unadopt`](Adoptable::unadopt).
/// Failure to properly remove links from the object graph may cause `Drop`
/// to detect a cycle is not externally reachable, reulting in prematurely
/// deallocating the entire cycle and turning all reachable [`Rc`]s into
/// dangling pointers. `CactusRef` makes a best-effort attempt to abort the
/// program if an access to a dead `Rc` occurs.

Add tests to assert cycles are fully dropped

Using a custom inner T that increments / decrements an AtomicU64 on new / drop.

To make sure these are useful under LeakSanitizer too โ€“ #102 โ€“ let's shove a String field with something like "abc".repeat(100) into the T as well.

Update to 2021 edition

This library hasn't been updated in almost a year, so it's still on the 2018 edition. 2021 is stable now, so it should be safe to use now.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.