Unsafe assertions that allow for optimizations in release mode.

Overview

assert-unchecked

Unsafe assertions that allow for optimizations in release mode.

build_status Documentation crates.io

These macros use core::hint::unreachable_unchecked, which make it possible to write assertions that simultaneously clarify code as well as hint at optimizations to LLVM.

Usage

Add this to your Cargo.toml

[dependencies]
assert_unchecked = "0.1.2"

Examples

use assert_unchecked::{
    assert_eq_unchecked, assert_ne_unchecked, assert_unchecked, unreachable_unchecked,
};

fn copy(from_arr: &[u8], to_arr: &mut [u8]) {
    assert_eq!(from_arr.len(), to_arr.len());
    for i in 0..to_arr.len() {
        // SAFETY: bounds of to_arr is checked outside of loop
        // Without this line, the compiler isn't smart enough to remove the bounds check
        unsafe { assert_unchecked!(i <= to_arr.len()) };
        to_arr[i] = from_arr[i];
    }
}

fn get_last(len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let mut v = vec![0];
    for i in 1..len {
        v.push(i)
    }
    // SAFETY: `len` elements have been added to v at this point
    // Without this line, the compiler isn't smart enough to remove the bounds check
    unsafe { assert_eq_unchecked!(len, v.len()) };
    v[len - 1]
}

// Modifies `a[0]` and `a[delta]`, and then returns `a[0]`.
// delta must be non-zero and delta < a.len().
unsafe fn modify_start_and_delta(a: &mut [u8], delta: usize) -> u8 {
    // SAFETY: requirements are invariants of the unsafe function.
    assert_unchecked!(delta < a.len());
    // With this assertion, we know that a[delta] does not modify a[0],
    // which means the function can optimize the return value to always be 0.
    // This also means that all bounds checks can be removed.
    assert_ne_unchecked!(delta, 0);
    a[0] = 0;
    a[delta] = 1;
    a[0]
}

fn div_1(a: u32, b: u32) -> u32 {
    // `b.saturating_add(1)` is always positive (not zero),
    // hence `checked_div` will never return `None`.
    // Therefore, the else branch is unreachable.
    a.checked_div(b.saturating_add(1))
        .unwrap_or_else(|| unsafe { unreachable_unchecked!("division by zero isn't possible") })
}
You might also like...
Fastest and safest Rust implementation of parquet. `unsafe` free. Integration-tested against pyarrow

Parquet2 This is a re-write of the official parquet crate with performance, parallelism and safety in mind. The five main differentiators in compariso

Detects usage of unsafe Rust in a Rust crate and its dependencies.
Detects usage of unsafe Rust in a Rust crate and its dependencies.

cargo-geiger ☢️ A program that lists statistics related to the usage of unsafe Rust code in a Rust crate and all its dependencies. This cargo plugin w

☢ Guerrilla (or Monkey) Patching in Rust for (unsafe) fun and profit.

Guerrilla Guerrilla (or Monkey) Patching in Rust for (unsafe) fun and profit. Provides aribtrary monkey patching in Rust. Please do not use this crate

Macro for stating unsafe assumptions in Rust.

assume A macro for stating unsafe assumptions in Rust. Using this macro, one can supply assumptions to the compiler for use in optimization. These ass

Detects usage of unsafe Rust in a Rust crate and its dependencies.
Detects usage of unsafe Rust in a Rust crate and its dependencies.

cargo-geiger ☢️ Looking for maintainer: https://github.com/rust-secure-code/cargo-geiger/issues/210 A program that lists statistics related to the usa

☢ Guerrilla (or Monkey) Patching in Rust for (unsafe) fun and profit.

Guerrilla Guerrilla (or Monkey) Patching in Rust for (unsafe) fun and profit. Provides aribtrary monkey patching in Rust. Please do not use this crate

An unsafe botched job that doesn't rely on types being 'static lifetime.

An unsafe botched job that doesn't rely on types being 'static lifetime. Will panic if provided a 0 field struct. I will fix this when I figure out how.

Rust-only ext4 implementation without unsafe code.

Rust-Ext4 Rust-only ext4 implementation without unsafe code. Supporting features no_std Direct/Indirect Block Addressing (RO) Extent Tree Addressing (

Recipes for avoiding bounds checks in Rust, without unsafe!

Recipes for avoiding bounds checks in Rust This repository showcases various approaches to avoiding bounds checks in Rust code, without unsafe code. E

Unsafe bindings and a safe wrapper for gtk4-layer-shell, automatically generated from a .gir file

gtk4-layer-shell: gtk4-layer-shell-sys: gtk4-layer-shell This is the safe wrapper for gtk4-layer-shell, automatically generated from its .gir file. Fo

DHCP Server programmed in rust with zero dependencies and unsafe.

RustyDHCP A simple and zero-dependency DHCP server written in Rust, with credit to Richard Warburton for contributions to parts of the code. Features

Building blocks for handling potentially unsafe statics.

Grounded Building blocks for handling potentially unsafe statics. This crate aims to provide useful and sound components that serve as building blocks

Rust Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev.
Rust Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev.

Rust Embed Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev. Y

Rust bindings for the latest stable release of PROJ

PROJ Coordinate transformation via bindings to the PROJ v7.2.1 API. Two coordinate transformation operations are currently provided: projection (and i

Rust bindings for the latest stable release of PROJ

PROJ Coordinate transformation via bindings to the PROJ v7.2.1 API. Two coordinate transformation operations are currently provided: projection (and i

A Github Actions based CI release template for Rust binaries
A Github Actions based CI release template for Rust binaries

Rust CI Release Template A Github Actions based CI release template. This repo serves as a live template, and reference for building your own CI power

Minecraft-esque voxel engine prototype made with the bevy game engine. Pending bevy 0.6 release to undergo a full rewrite.
Minecraft-esque voxel engine prototype made with the bevy game engine. Pending bevy 0.6 release to undergo a full rewrite.

vx_bevy A voxel engine prototype made using the Bevy game engine. Goals and features Very basic worldgen Animated chunk loading (ala cube world) Optim

Cargo subcommand `release`: everything about releasing a rust crate.

cargo release Features Ensure you are in a good state for release, including: Right branch Up-to-date with remote Clean tree Supports workspaces using

Rust wrapper for `os-release`

os-release-rs Rust wrapper for /etc/os-release file. Installation Add this to your Cargo.toml: [dependencies] os-release-rs = "0.1.0" Usage use os_rel

Owner
Sebastian Mendez
Software Engineering Intern at Airbnb. Former member of the Viral Communications Team in the MIT MediaLab, working on the SuperGlue project.
Sebastian Mendez
Adds size optimizations to any Perseus app automatically.

Perseus Size Optimization Plugin WARNING: Until Perseus #66 is fixed, this plugin can actually increase overall binary size! Once that issue is fixed

arctic_hen7 6 Aug 14, 2022
An unsafe botched job that doesn't rely on types being 'static lifetime.

An unsafe botched job that doesn't rely on types being 'static lifetime. Will panic if provided a 0 field struct. I will fix this when I figure out how.

twhite 0 Feb 4, 2022
A Github Actions based CI release template for Rust binaries

Rust CI Release Template A Github Actions based CI release template. This repo serves as a live template, and reference for building your own CI power

null 60 Dec 9, 2022
The nightly_crimes!{} macro commits horrible crimes to allow you to enable nightly features on the stable compiler.

The nightly_crimes!{} macro commits horrible crimes to allow you to enable nightly features on the stable compiler.

Mara Bos 151 Dec 16, 2022
A Discord bot focused on addressing the inherent problems with Discord, to allow a more socialist/anarchist organization of servers.

ACABot A Discord bot focused on addressing the inherent problems with Discord, to allow a more socialist/anarchist organization of servers (or "guilds

null 4 May 3, 2022
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 294 Dec 23, 2022
Allow raw pointer access without those pesky unsafe blocks everywhere!

Allow raw pointer access without those pesky unsafe blocks everywhere!

null 1 Jan 23, 2022
Fluent test assertions for Rust.

This is a fork the unmaintained crate spectral. Spectral as not changed for five years and yet is still very usable, the goal of this fork is to add n

Paul Delafosse 24 Dec 20, 2022
Adds size optimizations to any Perseus app automatically.

Perseus Size Optimization Plugin WARNING: Until Perseus #66 is fixed, this plugin can actually increase overall binary size! Once that issue is fixed

arctic_hen7 6 Aug 14, 2022
Detects usage of unsafe Rust in a Rust crate and its dependencies.

cargo-geiger ☢️ A program that lists statistics related to the usage of unsafe Rust code in a Rust crate and all its dependencies. This cargo plugin w

Rust Secure Code Working Group 1.1k Dec 26, 2022