#resources #emulate #type #attributes #manual #traits #send

no-std relevant

A small utility type to emulate must-use types

7 unstable releases (3 breaking)

Uses old Rust 2015

0.4.2 May 23, 2019
0.4.1 Apr 1, 2019
0.4.0 Jan 22, 2019
0.3.0 Dec 1, 2018
0.1.1 Jan 26, 2018

#2907 in Rust patterns

Download history 514/week @ 2024-07-22 429/week @ 2024-07-29 429/week @ 2024-08-05 1250/week @ 2024-08-12 560/week @ 2024-08-19 782/week @ 2024-08-26 640/week @ 2024-09-02 496/week @ 2024-09-09 496/week @ 2024-09-16 747/week @ 2024-09-23 513/week @ 2024-09-30 64/week @ 2024-10-07 419/week @ 2024-10-14 424/week @ 2024-10-21 501/week @ 2024-10-28 422/week @ 2024-11-04

1,769 downloads per month
Used in 58 crates (9 directly)

MIT/Apache

7KB
60 lines

Relevant

A small utility type to emulate must-use types. They are different from #[must_use] attribute in that the one who have an instance must either send it somewhere else or dispose it manually.

This must be desired for types that need manual destruction which can't be implemented with Drop trait. For example resource handler created from some source and that must be returned to the same source.

Usage

The type Relevant is non-droppable. As limitation of current implementation it panics when dropped. To make type non-droppable it must contain non-droppable type (Relevant type for example).

Example


struct SourceOfFoos {
    handle: u64,
}

/// Foo must be destroyed manually.
struct Foo {
   handle: u64,
   relevant: Relevant,
}

/// Function from C library to create `Foo`
/// Access to same source must be synchronized.
extern "C" create_foo(source: u64) -> u64;

/// Function from C library to destroy `Foo`.
/// Access to same source must be synchronized.
extern "C" destroy_foo(source: u64, foo: u64) -> u64;

impl SourceOfFoos {
    fn create_foo(&mut self) -> Foo {
        Foo {
            handle: create_foo(self.handle),
            relevant: Relevant,
        }
    }

    fn destroy_foo(&mut self, foo: Foo) {
        destroy_foo(self.handle, foo.handle);
        foo.relevant.dispose();
    }
}

Now it is not possible to accidentally drop Foo and leak handle. Of course it always possible to explicitly std::mem::forget relevant type. But it will be deliberate leak.

Dependencies

~0–5MB
~14K SLoC