#unchecked #performance #unsafe #debug-mode #debugging #require

unchecked-std

some methods from the Rust standard library without some checks

3 releases (stable)

1.0.1 Oct 6, 2024
1.0.0 Aug 12, 2024
0.1.0 May 18, 2024

#195 in Memory management

Download history 57/week @ 2024-08-06 61/week @ 2024-08-13 6/week @ 2024-09-10 4/week @ 2024-09-17 11/week @ 2024-09-24 149/week @ 2024-10-01 33/week @ 2024-10-08

58 downloads per month

0BSD license

15KB
252 lines

unchecked-std

Rust standard library methods with some checks removed for the sake of performance and binary size.

For safety, assertions are present in debug mode.

Most implementations do not rely on corresponding std methods, except for extend_from_slice_unchecked which works based on unreachable_unchecked and has a codegen test to confirm that the capacity check gets elided.

The crate is no_std, but requires alloc.

Example

format! way:

fn hello_format(name: &str) -> String {
    format!("Hello, {name}!")
}

macro-free std way:

fn hello_checked(name: &str) -> String {
    let mut s = String::with_capacity("Hello, !".len() + name.len());
    s.push_str("Hello, ");
    s.push_str(name);
    s.push('!');
    s
}

unchecked-std way:

use unchecked_std::prelude::*;

fn hello_unchecked(name: &str) -> String {
    let mut s = String::with_capacity("Hello, !".len() + name.len());
    // SAFETY: `s` has been initialized with sufficient capacity
    unsafe {
        s.push_str_unchecked("Hello, ");
        s.push_str_unchecked(name);
        s.push_unchecked('!');
    }
    s
}

The benchmark result is:

test bench_hello_format    ... bench:          29.50 ns/iter (+/- 0.74)
test bench_hello_checked   ... bench:          15.47 ns/iter (+/- 0.31)
test bench_hello_unchecked ... bench:          11.45 ns/iter (+/- 0.65)

Feature flags

heapless adds unchecked methods for heapless data structures.

Dependencies

~105KB