Owned container for dynamically-sized types backed by inline memory

Overview

sized-dst

This crate provides Dst, an owned container for dynamically-sized types (DSTs) that's backed by inline memory. The main use-case is owned trait objects without heap allocation. You can think of it as a stack-only version of Box<dyn Trait>.

This crate currently requires nightly, since it relies on Unsize and pointer metadata.

The layout of sized_dst::Dst consists of the DST metadata (for trait objects, this is the vtable pointer) and a fixed block of memory storing the actual object. This allows it to live entirely on the stack or even a static variable. The size and alignment of its memory block are specified by generic parameters, so a sized_dst::Dst can only store objects that fit in its memory block. If the object does not fulfill the size or alignment requirements, the constructor of sized_dst::Dst will emit a compile-time error.

use sized_dst::{Dst, max_size};

trait Draw {
    fn draw(&self);
}

struct Button {
    height: u32,
    width: u32,
    name: &'static str,
}
impl Draw for Button {
    fn draw(&self) { /* draw the button */ }
}

struct Checkbox {
    on: bool,
}
impl Draw for Checkbox {
    fn draw(&self) { /* draw the checkbox */ }
}

struct Text(&'static str);
impl Draw for Text {
    fn draw(&self) { /* draw the text */ }
}

struct Blob([u8; 100]);
impl Draw for Blob {
    fn draw(&self) { /* draw the blob */ }
}

impl Draw for u32 {
    fn draw(&self) { /* draw the u32 */ }
}

fn main() {
    // Each Dst stores a `dyn Draw` up to a fixed capacity, which is set via `max_size` to
    // the size of the biggest trait object we're using.
    let drawables: &[Dst<dyn Draw, { max_size!(Checkbox, Text, Button) }>] = &[
        Dst::new(Checkbox { on: true }),
        Dst::new(Text("lorem ipsum")),
        Dst::new(Button {
            height: 20,
            width: 20,
            name: "PANIC BUTTON",
        }),
        Dst::new(1u32),   // u32 is smaller than the fixed capacity we specified, so we can use it
        // Dst::new(Blob([0; 100]))    This would not compile, because Blob doesn't fit in Dst
    ];

    // Perform dynamic dispatch over the Draw trait
    for d in drawables {
        d.draw();
    }
}

Compared to Box<dyn Trait>, Dst requires no indirection or allocation, making it more cache-friendly and usable in environments with no allocator. In exchange, Dst can only store objects up to a fixed size, making it less flexible than Box<dyn Trait>. In a way, Dst offers a compromise between enums and boxed trait objects.

Optional Features

  • std: Enable implementations of std traits.
You might also like...
Structopt derived ethers-rs types, useful for building Ethereum CLIs

ethers-structopt Provides ethers-compatible Structopt derives, useful for building Ethereum CLIs. Contributing Pull requests are welcome. For major ch

Allows processing of iterators of Result types

try-continue try-continue provides one method, try_continue, which allows you to work with iterators of type ResultT, _, as if they were simply iter

A collection of numeric types and traits for Rust.

num A collection of numeric types and traits for Rust. This includes new types for big integers, rationals (aka fractions), and complex numbers, new t

Utilites for working with `bevy_ecs` when not all types are known at compile time

bevy_ecs_dynamic Utilities for working with bevy_ecs in situations where the types you're dealing with might not be known at compile time (e.g. script

Provide types for angle manipulation in rust.

angulus Provides types for angle manipulation. Features serde : Serialization/deserialization support via serde. Example use angulus::{*, units::*};

Unopinionated low level API bindings focused on soundness, safety, and stronger types over raw FFI.

🔥 firehazard 🔥 Create a fire hazard by locking down your (Microsoft) Windows so nobody can escape (your security sandbox.) Unopinionated low level A

Nederlandse programmeertaal. Geinterpreteerd en met dynamische types. Met bytecode compiler en virtual machine, in Rust.

Nederlang Nederlang is een geinterpreteerde programmeertaal, in het Nederlands! Met als bestandsnaam extensie.... .nl! Het maakt gebruik van dynamisch

Generate Soufflé Datalog types, relations, and facts that represent ASTs from a variety of programming languages.

treeedb treeedb makes it easier to start writing a source-level program analysis in Soufflé Datalog. First, treeedb generates Soufflé types and relati

A tool for determining file types, an alternative to file

file-rs a tool for determining file types, an alternative to file whats done determining file extension determining file type determining file's mime

Owner
Yuhan Lin
Yuhan Lin
Self-contained template system with Handlebars and inline shell scripts

Handlematters Self-contained template system with Handlebars and inline shell scripts Introduction Handlematters is a template system that combines Ha

Keita Urashima 3 Sep 9, 2022
Write simple proc-macros inline with other source code.

script-macro An experimental way to write simple proc-macros inline with other source code. Did you ever end up getting frustrated at the boilerplate

Markus Unterwaditzer 17 Jun 10, 2023
Deadliner helps you keep track of the time left for your deadline by dynamically updating the wallpaper of your desktop with the time left.

Deadliner Watch the YouTube video What's Deadliner? Deadliner is a cross-platform desktop application for setting deadline for a project and keeping t

Deadliner 34 Dec 16, 2022
Encode and decode dynamically constructed values of arbitrary shapes to/from SCALE bytes

scale-value · This crate provides a Value type, which is a runtime representation that is compatible with scale_info::TypeDef. It somewhat analogous t

Parity Technologies 15 Jun 24, 2023
Shared memory - A Rust wrapper around native shared memory for Linux and Windows

shared_memory A crate that allows you to share memory between processes. This crate provides lightweight wrappers around shared memory APIs in an OS a

elast0ny 274 Dec 29, 2022
Demo app duplicated in 5 languages (Go/JavaScript/Python/Ruby/Rust) showing how to go from source code to container image using melange+apko

hello-melange-apko ?? This repo contains an example app duplicated across 5 languages showing how to: Package source code into APKs using melange Buil

Chainguard 16 Jan 23, 2023
A container image builder tool for OCI (distrobox/toolbox, also podman/docker)

Distrobox Boost A container image builder tool for Open Container Initiative (distrobox/toolbox, also podman/docker). Distrobox is good enough in runn

xz-dev 6 Aug 15, 2023
Log-structured, transactional virtual block device backed by S3

mvps Log-structured, transactional virtual block device compatible with the NBD protocol. mvps stands for "multi-versioned page store". MVPS can store

Heyang Zhou 3 Dec 3, 2023
Costless typed identifiers backed by UUID, with kind readable in serialized versions

Why kind ? With kind, you use typed identifiers in Rust, with no overhead over Uuid have the type be human readable and obvious in JSON and any export

Wingback 67 Mar 24, 2024
Count your code by tokens, types of syntax tree nodes, and patterns in the syntax tree. A tokei/scc/cloc alternative.

tcount (pronounced "tee-count") Count your code by tokens, types of syntax tree nodes, and patterns in the syntax tree. Quick Start Simply run tcount

Adam P. Regasz-Rethy 48 Dec 7, 2022