[][src]Crate tokenlock

Provides a Send-able cell type whose contents can be accessed only via an unforgeable token.

Examples

let mut token = ArcToken::new();

let lock = TokenLock::new(token.id(), 1);
assert_eq!(*lock.read(&token), 1);

let mut guard = lock.write(&mut token);
assert_eq!(*guard, 1);
*guard = 2;

TokenLock implements Send and Sync so it can be shared between threads, but only the thread holding the original Token can access its contents. Token cannot be cloned:

let lock = Arc::new(TokenLock::new(token.id(), 1));

let lock_1 = Arc::clone(&lock);
thread::Builder::new().spawn(move || {
    let lock_1 = lock_1;
    let mut token_1 = token;

    // I have `Token` so I can get a mutable reference to the contents
    lock_1.write(&mut token_1);
}).unwrap();

// can't access the contents; I no longer have `Token`
// lock.write(&mut token);

The lifetime of the returned reference is limited by both of the TokenLock and Token.

This example deliberately fails to compile
let mut token = ArcToken::new();
let lock = TokenLock::new(token.id(), 1);
let guard = lock.write(&mut token);
drop(lock); // compile error: `guard` cannot outlive `TokenLock`
drop(guard);
This example deliberately fails to compile
drop(token); // compile error: `guard` cannot outlive `Token`
drop(guard);

It also prevents from forming a reference to the contained value when there already is a mutable reference to it:

This example deliberately fails to compile
let write_guard = lock.write(&mut token);
let read_guard = lock.read(&token); // compile error
drop(write_guard);

While allowing multiple immutable references:

let read_guard1 = lock.read(&token);
let read_guard2 = lock.read(&token);

Structs

ArcToken

An Arc-based unforgeable token used to access the contents of a TokenLock.

ArcTokenId

Token that cannot be used to access the contents of a TokenLock, but can be used to create a new TokenLock.

BadTokenError

Error type returned when a key (Token) doesn't fit in a keyhole (TokenLock::keyhole).

RcToken

An Rc-based unforgeable token used to access the contents of a TokenLock.

RcTokenId

Token that cannot be used to access the contents of a TokenLock, but can be used to create a new TokenLock.

TokenLock

A mutual exclusive primitive that can be accessed using a Token<I> with a very low over-head.

Traits

Token

Trait for an unforgeable token used to access the contents of a TokenLock.