Code Monkey home page Code Monkey logo

self-reference's Introduction

Self-Reference

A Self-Refernece Helper (Inspired From Selfie)

this crate provides safe access to its self-reference. the main idea is not initializing references when object not pinned(which is not safe and makes many self-referenial crate more complex) providing only pinned reference makes lot more easier to design self-referential object. on self-reference crate. you only can initialize reference object that has 'static lifetime means always safe.

Safety Note

This crate is tested under miri. Please crate an issue if you find any soundness holes.

Initializing Reference Object

The major difference from other self-referential crate is initializing referential object. you only can initialize reference object that has 'static lifetime

let mut reference: SelfReference<'_, String, Ref<str>> = SelfReference::new(String::new(), || {
    // you can't get reference of object while initialization.
    // only possible cases are reference that has `'static` lifetime.
    ""
});
pin_mut!(reference);

// this is totally SAFE. this lowers `'static` lifetime into some other lifetime.
reference.get_ref();

Reset Mechanism

The only way to initialize reference object is using reset method. remember!! you can use reset method when SelfReference object is pinned.

let mut reference: SelfReference<'_, String, Ref<str>> = SelfReference::new("self-reference".to_string(), || "");
pin_mut!(reference);

// You can reset object to set referencial object to hold object itself.
reference.reset_unpin(|s| &s[..4]);
println!("{}", reference.get_ref()); // prints "self"

self-reference's People

Contributors

artblnd avatar

Stargazers

Jay avatar Daniel Lee avatar  avatar Hyeon Kim (김지현) avatar Jiseok CHOI avatar Iha Shin (신의하) avatar  avatar

Watchers

 avatar

Forkers

theoriartblnd

self-reference's Issues

`get_mut` is unsound

use self_reference::{OptionRef, SelfReference};

fn main() {
    let mut self_ref: SelfReference<&(), OptionRef<Box<usize>>> =
        SelfReference::new(&(), || Box::leak(Box::new(None)).as_ref());
    {
        let x = Box::new(1234usize);
        // Should be disallowed
        *self_ref.get_mut() = Some(&x);
    }
    // Prints dangling pointer
    println!("{:p}", self_ref.get_ref().unwrap().as_ref());
}

get_mut() can shorten the lifetime 'x in R::Type<'x>. This is unsound because T is invariant in &mut T.

https://doc.rust-lang.org/nomicon/subtyping.html#variance

MIRI log
error: Undefined Behavior: trying to retag from <3097> for Unique permission at alloc1467[0x0], but that tag does not exist in the borrow stack for this location
  --> /home/qwaz/.cargo/registry/src/index.crates.io-6f17d22bba15001f/self-reference-0.2.2/src/utils.rs:44:12
   |
44 |     return value;
   |            ^^^^^
   |            |
   |            trying to retag from <3097> for Unique permission at alloc1467[0x0], but that tag does not exist in the borrow stack for this location
   |            this error occurs as part of retag at alloc1467[0x0..0x8]
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <3097> was created by a Unique retag at offsets [0x0..0x8]
  --> src/main.rs:9:10
   |
9  |         *self_ref.get_mut() = Some(&x);
   |          ^^^^^^^^^^^^^^^^^^
help: <3097> was later invalidated at offsets [0x0..0x8] by a Unique retag
  --> src/main.rs:9:10
   |
9  |         *self_ref.get_mut() = Some(&x);
   |          ^^^^^^^^^^^^^^^^^^
   = note: BACKTRACE (of the first span):
   = note: inside `self_reference::utils::detach_lifetime_get_mut::<self_reference::OptionRef<std::boxed::Box<usize>>>` at /home/qwaz/.cargo/registry/src/index.crates.io-6f17d22bba15001f/self-reference-0.2.2/src/utils.rs:44:12: 44:17
   = note: inside `self_reference::SelfReference::<'_, &(), self_reference::OptionRef<std::boxed::Box<usize>>>::get_mut` at /home/qwaz/.cargo/registry/src/index.crates.io-6f17d22bba15001f/self-reference-0.2.2/src/lib.rs:144:18: 144:69
note: inside `main`
  --> src/main.rs:9:10
   |
9  |         *self_ref.get_mut() = Some(&x);
   |          ^^^^^^^^^^^^^^^^^^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to previous error

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.