Const equivalents of many [`bytemuck`] functions, and a few additional const functions.

Overview

Rust crates-io api-docs

Const equivalents of many bytemuck functions, and a few additional const functions.

constmuck uses bytemuck's traits, so any type that implements those traits can be used with the relevant functions from this crate.

The *_alt functions aren't exactly equivalent to the bytemuck ones, each one describes how it's different.

Examples

These examples use bytemuck's derives to show how users don't need to write unsafe to use this crate, and use the konst crate to make writing the const functions easier.

Contiguous

This example demonstrates constructing an enum from its representation.

use constmuck::{Contiguous, infer};

use konst::{array, try_opt};

fn main() {
    const COLORS: Option<[Color; 5]> = Color::from_array([3, 4, 1, 0, 2]);
    assert_eq!(
        COLORS,
        Some([Color::White, Color::Black, Color::Blue, Color::Red, Color::Green]),
    );

    const NONE_COLORS: Option<[Color; 4]> = Color::from_array([1, 2, 3, 5]);
    assert_eq!(NONE_COLORS, None);
}

#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Contiguous, Copy, Clone)]
pub enum Color {
    Red = 0,
    Blue,
    Green,
    White,
    Black,
}

impl Color {
    pub const fn from_int(n: u8) -> Option<Self> {
        constmuck::contiguous::from_u8(n, infer!())
    }
    pub const fn from_array
   usize>(input: [
   u8; N]) 
   -
   > 
   Option
   <[
   Self; N]
   > {
        
   // `try_opt` returns from `from_array` on `None`,
        
   // because `konst::array::map` allows the passed-in expression
        
   // to return from the surrounding named function.
        
   Some(array
   ::
   map!(input, 
   |n
   | 
   try_opt!(
   Self
   ::
   from_int(n))))
    }
}


  

Wrapper

This example demonstrates a type that wraps a [T], constructed by reference.

use constmuck::TransparentWrapper;
use constmuck::infer_tw;

fn main() {
    const SLICE: &[u32] = &[3, 5, 8, 13, 21];
    const WRAPPER: &SliceWrapper<u32> = SliceWrapper::new(SLICE);

    const SUM: u64 = WRAPPER.sum();
    assert_eq!(SUM, 50);

    const FIRST_EVEN: Option<(usize, u32)> = WRAPPER.find_first_even();
    assert_eq!(FIRST_EVEN, Some((2, 8)));
}

#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, TransparentWrapper)]
pub struct SliceWrapper
   (
   pub [T]);


   impl
    
    SliceWrapper
    
      {
    
     // Using `constmuck` allows safely defining this function as a `const fn`
    
     pub 
     const 
     fn 
     new(reff: 
     &[T]) -> 
     &
     Self {
        constmuck
     ::wrapper
     ::
     wrap_ref!(reff, 
     infer_tw!())
    }
}


     impl 
     SliceWrapper<
     u32> {
    
     pub 
     const 
     fn 
     sum(
     &
     self) -> 
     u64 {
        
     let 
     mut sum 
     = 
     0;
        konst
     ::
     for_range!{i 
     in 
     0..
     self.
     0.
     len() 
     =>
            sum 
     += 
     self.
     0[i] 
     as 
     u64;
        }
        sum
    }
    
     pub 
     const 
     fn 
     find_first_even(
     &
     self) -> 
     Option<(
     usize, 
     u32)> {
        konst
     ::
     for_range!{i 
     in 
     0..
     self.
     0.
     len() 
     =>
            
     if 
     self.
     0[i] 
     % 
     2 
     == 
     0 {
                
     return 
     Some((i, 
     self.
     0[i]));
            }
        }
        
     None
    }
    
}


    
   
  

Features

These are the features of this crate:

  • "derive"(disabled by default): enables bytemuck's "derive" feature and reexports its derives.

  • "debug_checks"(disabled by default): Enables additional checks

Additional checks

The "debug_checks" feature enables additional checks, all of which cause panics when it'd have otherwise been Undefined Behavior (caused by unsound unsafe impls or calling unsafe constructor functions).

Size checks

Functions that transmute values check that the value doesn't change size when transmuted.

Functions that transmute references check that referent (the T in &T) doesn't change size when transmuted.

Macros that transmute references check that reference doesn't change size when transmuted (ie: transmuting &[u8] to &u8). Macros have weaker checking than functions because they allow references to !Sized types (eg: str, [u8], dyn Trait), if you're only casting references to Sized types it's better to use the function equivalents.

Alignment checks

All the functions in the wrapper module check that the alignment of the Inner type parameter is the same as the Outer type parameter, in addition to the size checks described in the previous section.

Contiguous checks

The from_* functions in the contiguous module check that the min_value of the passed-in ImplsContiguous is less than its max_value .

No-std support

constmuck is #![no_std], it can be used anywhere Rust can be used.

Minimum Supported Rust Version

constmuck requires Rust 1.56.0, because it uses transmute inside const fns.

You might also like...
This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity.
This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity.

bottom-bot This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity. Ever had this pro

An implementation of Code Generation and Factoring for Fast Evaluation of Low-order Spherical Harmonic Products and Squares

sh_product An implementation of Code Generation and Factoring for Fast Evaluation of Low-order Spherical Harmonic Products and Squares (paper by John

lightweight and customizable rust s-expression (s-expr) parser and printer

s-expr Rust library for S-expression like parsing and printing parser keeps track of spans, and representation (e.g. number base) number and decimal d

Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks.
Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks.

Crates Registry Description Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks. (like Ver

Simplify temporary email management and interaction, including message retrieval and attachment downloads, using Rust.

Tempmail The Tempmail simplifies temporary email management and interaction, including message retrieval and attachment downloads, using the Rust prog

The simplest way to de-Google your life and business: Inbox, Calendar, Files, Contacts & much more
The simplest way to de-Google your life and business: Inbox, Calendar, Files, Contacts & much more

Bloom The all-in-one private workspace Try it for free! You no longer trust tech monopolies with your data? You are done with your privacy invaded by

MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine
MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine

MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine. Both searching and indexing are highly customizable. Features such as typo-tolerance, filters, and synonyms are provided out-of-the-box. For more information about features go to our documentation.

A job queue built on sqlx and PostgreSQL.

sqlxmq A job queue built on sqlx and PostgreSQL. This library allows a CRUD application to run background jobs without complicating its deployment. Th

Modify fonts to remove bitmap and disable gridfit for Windows font rendering.

Since Windows 10 version 1703 (Creators Update), its built-in TrueType renderer now supports vertical anti-aliasing. Despite there are only 30 levels of grayscale shade, it dramatically improves text rendering, especially for CJK languages. Sadly, it is only enabled for selected fonts at selected sizes.

Releases(0.3.0)
  • 0.3.0(Oct 26, 2021)

    This release makes many changes to the API and implementation, without adding any new major functionality.

    Changelog

    0.3.0

    0.3.0

    Renamed all Impls* types to Is*

    Renamed IsPod's fields, impls_copy to is_copy and is_zeroable to impls_zeroable

    Renamed infer_tw macro to IsTW

    Renamed type_size macro to TypeSize

    Renamed TypeSize::with_bound to with_bounds and set_bound to set_bounds.

    Renamed bytes_of to byte_array_of

    Added these macros for constructing Is* types:

    • IsPod: constructs IsPod
    • IsContiguous: constructs IsContiguous
    • IsCopy: constructs IsCopy
    • IsZeroable: constructs IsZeroable

    Added optional $bound type argument to TypeSize macro.

    Swapped TypeSize's' B and T type parameters

    Added IsTransparentWrapper::IDENTITY associated constant

    Added Debug impls for all types.

    Added "rust_latest_stable" feature, to opt into using the latest "rust__" feature (only enabled once it's released in the stable channel).

    Added "rust_1_57" feature

    Removed TransmutableInto, and transmutable module, because they are leaky abstractions.

    Removed the into_inner and from_inner fields in IsTransparentWrapper.

    Changed contiguous::into_integer to take IsContiguous by reference.

    Swapped Inner and Outer type parameters of wrap* and peel* functions to have the same order as IsTransparentWrapper

    Made all type parameters of Is* types and TypeSize invariant, just in case that it's unsound for them to be covariant.

    Removed the "debug_checks" feature, replacing it with the built-in debug_assertions flag.

    Added const_panic 0.1.0 as a dependency, enabled by the "rust_1_57" feature.

    0.2

    0.2.0

    Changed ImplsCopy bound to Pod

    Added join methods to both TransmutableInto and ImplsTransparentWrapper

    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Sep 16, 2021)

    The initial release of constmuck, with const fn equivalents of many bytemuck methods/function.

    Changelog

    0.1.0

    Added bytemuck 1.7.2 as a dependency, with the "min_const_generics" feature.

    Reexported the crate, Contiguous, Pod, PodCastError, TransparentWrapper, and Zeroable from bytemuck.

    Defined the contiguous module with these items:

    • reexport of constmuck::ImplsContiguous
    • FromInteger struct
    • from_i8 function
    • from_i16 function
    • from_i32 function
    • from_i64 function
    • from_i128 function
    • from_isize function
    • from_u8 function
    • from_u16 function
    • from_u32 function
    • from_u64 function
    • from_u128 function
    • from_usize function
    • into_integer function

    Defined the copying module with these items:

    • reexport of constmuck::ImplsCopy
    • copy functions
    • repeat functions

    Defined the transmutable module with these items:

    • reexport of constmuck::TransmutableInto
    • transmute_ref macro
    • transmute_ref function
    • transmute_into function
    • transmute_slice function

    Defined the wrapper module with these items:

    • reexport of constmuck::infer_tw;
    • reexport of constmuck::ImplsTransparentWrapper;
    • peel_ref macro
    • wrap_ref macro
    • peel function
    • peel_ref function
    • peel_slice function
    • wrap function
    • wrap_ref function
    • wrap_slice function

    Defined these macros:

    • infer
    • infer_tw
    • map_bound
    • type_size

    Defined these marker types:

    • ImplsContiguous(not zero-sized)
    • ImplsCopy
    • ImplsPod
    • ImplsTransparentWrapper
    • ImplsZeroable
    • TransmutableInto
    • TypeSize(only zero-sized if its bounds field is)

    Defined the Infer trait

    Defined these functions:

    • bytes_of
    • cast
    • cast_ref_alt
    • cast_slice_alt
    • try_cast
    • try_cast_ref_alt
    • try_cast_slice_alt
    • zeroed
    • zeroed_array
    Source code(tar.gz)
    Source code(zip)
Owner
null
const panic with formatting

For panicking with formatting in const contexts. This library exists because the panic macro was stabilized for use in const contexts in Rust 1.57.0,

null 4 Jul 10, 2022
Rust telegram bot library for many runtimes

Telbot Telbot provides telegram bot types and api wrappers. Specifically, telbot now supports: telbot-types: basic telegram types / requests / respons

kiwiyou 17 Dec 3, 2022
Tells you how many years you need to wait until your subatomic xeon crystal synchronizer has doubled in plasma inversion efficiency on the Goldberg-Moleman scale or whatever.

about Tells you how many years you need to wait until your subatomic xeon crystal synchronizer has doubled in plasma inversion efficiency on the Goldb

null 2 Dec 3, 2021
Annoyed that Rust has many string types? Well it doesn't have to

generic-str The one true string type in Rust! This project intends to be a proof-of-concept for an idea I had a few months back. There is lots of unsa

Conrad Ludgate 40 Apr 9, 2022
A Rust proc-macro crate which derives functions to compile and parse back enums and structs to and from a bytecode representation

Bytecode A simple way to derive bytecode for you Enums and Structs. What is this This is a crate that provides a proc macro which will derive bytecode

null 4 Sep 3, 2022
Rust Keeper bots that run various functions, from liquidations, to orderbook cranks, and more.

The zo-keeper (pronounced "zoo keeper") repository runs large scale instructions that secure the 01 network, and allow it to operate in a fully decentralized manner.

Zero One Global Foundation 61 Dec 16, 2022
Kalker (or "kalk") is a calculator program/website that supports user-defined variables, functions, derivation, and integration

Kalker (or "kalk") is a calculator program/website that supports user-defined variables, functions, derivation, and integration. It runs on Windows, macOS, Linux, Android, and in web browsers (with WebAssembly).

null 1.2k Dec 27, 2022
`grep` but with PEG patterns. Define grammars (e.g. `digit`), functions for matching. No more regex syntax!

PEG peggrep Example file demo_file: THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Ha

IchHabeKeineNamen 3 Apr 18, 2023
A library and tool for automata and formal languages, inspired by JFLAP

Sugarcubes is a library and application for automata and formal languages. It is inspired by JFLAP, and is intended to eventually to be an alternative to JFLAP.

Henry Sloan 22 Nov 2, 2022
A stupid macro that compiles and executes Rust and spits the output directly into your Rust code

inline-rust This is a stupid macro inspired by inline-python that compiles and executes Rust and spits the output directly into your Rust code. There

William 19 Nov 29, 2022