Home

Awesome

<br><p align="center"><img src="https://raw.githubusercontent.com/tnballo/scapegoat/master/img/scapegoat.svg" width="333" alt="scapegoat"></p><br>

scapegoat

crates.io MSRV 1.55+ docs.rs GitHub Actions License: MIT Unsafe-Zero-Percent

Ordered set and map data structures via an arena-based scapegoat tree (memory-efficient, self-balancing binary search tree).

About

Two APIs:

Strives for three properties:

Other features:

Usage

SgMap non-exhaustive, #![no_std] API example (would work almost identically for std::collections::BTreeMap):

use scapegoat::SgMap;
use tinyvec::{array_vec, ArrayVec};

// This const is an argument to each generic constructor below.
// So we'll use *only the bare minimum* memory for 5 elements.
// - Stack RAM usage can be precisely controlled: per map instance (constructor call-site).
// - To save executable RAM/ROM (monomorphization!), stick to a global capacity like this.
const CAPACITY: usize = 5;

let mut example = SgMap::<_, _, CAPACITY>::new(); // BTreeMap::new()
let mut static_str = "your friend the";

// Insert "dynamically" (as if heap)
example.insert(3, "the");
example.insert(2, "don't blame");
example.insert(1, "Please");

// Fallible insert variant
assert!(example.try_insert(4, "borrow checker").is_ok());

// Ordered reference iterator
assert!(example
    .iter()
    .map(|(_, v)| *v)
    .collect::<ArrayVec<[&str; CAPACITY]>>()
    .iter()
    .eq(["Please","don't blame","the","borrow checker"].iter()));

// Container indexing
assert_eq!(example[&3], "the");

// Head removal
let please_tuple = example.pop_first().unwrap();
assert_eq!(please_tuple, (1, "Please"));

// By-predicate removal
example.retain(|_, v| !v.contains("a"));

// Extension
let iterable = array_vec![
    [(isize, &str); CAPACITY] =>
    (1337, "safety!"), (0, "Leverage"), (100, "for")
];
example.extend(iterable.into_iter());

// Value mutation
if let Some(three_val) = example.get_mut(&3) {
    *three_val = &mut static_str;
}

// New message :)
assert!(example
    .into_values()
    .collect::<ArrayVec<[&str; CAPACITY]>>()
    .iter()
    .eq(["Leverage","your friend the","borrow checker","for","safety!"].iter()));

Additional examples here.

Stack Capacity: Important Context

Per the above, const generic type parameters decide collection capacity. And thus also stack usage. That usage is fixed:

use core::mem::size_of_val;
use scapegoat::SgMap;

let small_map: SgMap<u64, u64, 100> = SgMap::new(); // 100 item capacity
let big_map: SgMap<u64, u64, 2_048> = SgMap::new(); // 2,048 item capacity

#[cfg(target_pointer_width = "64")]
#[cfg(not(feature = "low_mem_insert"))]
#[cfg(not(feature = "fast_rebalance"))]
{
    assert_eq!(size_of_val(&small_map), 2_680); // 2.7 KB
    assert_eq!(size_of_val(&big_map), 53_328);  // 53.3 KB
}

The maximum supported capacity is 65_535 (e.g. 0xffff or u16::MAX) items. Please note:

WARNING: Although stack usage is constant (no recursion), a stack overflow can happen at runtime if N (const generic capacity) and/or the stored item type (generic) is too large. Note stack overflow is distinct from buffer overflow (which safe Rust prevents). Regardless, you must test to ensure you don't exceed the stack size limit of your target platform. Rust only supports stack probes on x86/x64, although creative linking solutions have been suggested for other architectures.

For advanced configuration options, please see the documentation here.

Trusted Dependencies

This library has three dependencies, each of which have no dependencies of their own (e.g. exactly three total dependencies).

Because this library and all dependencies are #![forbid(unsafe_code)], no 3rd-party unsafe code is introduced into your project. This maximizes static guarantees for memory safety (enforced via Rust's type system). Robustness and correctness properties beyond memory safety are validated dynamically, via differential fuzzing.

Additional Considerations

General Goals

This project is an exercise in safe, portable data structure design. The goal is to offer embedded developers familiar, ergonomic APIs on resource constrained systems that otherwise don't get the luxury of dynamic collections. Without sacrificing safety.

scapegoat is not as fast or mature as the standard library's BTreeMap/BTreeSet (benchmarks via cargo bench). The standard library has been heavily optimized for cache performance. This library is optimized for low, stack-only memory footprint. It offers:

Algorithmic Complexity

Space complexity is always O(n). Time complexity:

OperationAverage CaseWorst Case
getO(log n)O(log n)
insertO(log n)Amortized O(log n)
removeO(log n)Amortized O(log n)
firstO(1)O(1)
lastO(1)O(1)

Memory Footprint Demos

License and Contributing

Licensed under the MIT license. Contributions are welcome!