Skip to content

Commit

Permalink
Merge pull request rust-unofficial#75 from llogiq/unsafe-mods
Browse files Browse the repository at this point in the history
new pattern: Contain Unsafety in Small Modules
  • Loading branch information
lambda-fairy authored Aug 1, 2019
2 parents 0920bba + db86d28 commit 7303763
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ language.
* [Visitor](patterns/visitor.md)
* [Fold](patterns/fold.md)
* [Prefer small crates](patterns/small-crates.md)
* [Contain unsafety in small modules](patterns/unsafe-mods.md)
* TODO extension traits
* TODO destructor bombs (ensure linear typing dynamically, e.g., https://github.com/Munksgaard/session-types/commit/0f25ccb7c3bc9f65fa8eaf538233e8fe344a189a)
* TODO convertible to Foo trait for more generic generics (e.g., http://static.rust-lang.org/doc/master/std/fs/struct.File.html#method.open)
Expand Down
24 changes: 24 additions & 0 deletions patterns/unsafe-mods.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Contain unsafety in small modules

## Description

If you have `unsafe` code, create the smallest possible module that can uphold the needed invariants to build a minimal safe interface upon the unsafety. Embed this into a larger module that contains only safe code and presents an ergonomic interface. Note that the outer module can contain unsafe functions and methods that call directly into the unsafe code. Users may use this to gain speed benefits.

## Advantages

* This restricts the unsafe code that must be audited
* Writing the outer module is much easier, since you can count on the guarantees of the inner module

## Disadvantages

* Sometimes, it may be hard to find a suitable interface.
* The abstraction may introduce inefficiencies.

## Examples

* The [`toolshed`](https://docs.rs/toolshed) crate contains its unsafe operations in submodules, presenting a safe interface to users.
* `std`s `String` class is a wrapper over `Vec<u8>` with the added invariant that the contents must be valid UTF-8. The operations on `String` ensure this behavior. However, users have the option of using an `unsafe` method to create a `String`, in which case the onus is on them to guarantee the validity of the contents.

## See also

* [Ralf Jung's Blog about invariants in unsafe code](https://www.ralfj.de/blog/2018/08/22/two-kinds-of-invariants.html)

0 comments on commit 7303763

Please sign in to comment.