zero runtime cost default arguments in rust

Overview

Default Arguments in Rust

Github Actions Github Releases crate.io MIT License

Enables default arguments in rust by macro in zero cost. Just wrap function with default_args! and macro with name of function would be automatically generated to be used with default argument. See below for usage

use default_args::default_args;

// this would make a macro named `foo`
// and original function named `foo_`
default_args! {
    fn foo(important_arg: u32, optional: u32 = 100) -> String {
        format!("{}, {}", important_arg, optional)
    }
}

// in other codes ...
assert_eq!(foo!(1), "1, 100"); // foo(1, 100)
assert_eq!(foo!(1, 3), "1, 3"); // foo(1, 3)
assert_eq!(foo!(1, optional = 10), "1, 10"); // foo(1, 10)

// let's make another one
default_args! {
    #[inline]
    pub async unsafe extern "C" fn bar<S1, S2, S3>(a: S1, b: S2 = "b", c: S3 = "c") -> String
    where
        S1: AsRef<str>,
        S2: AsRef<str>,
        S3: AsRef<str>,
    {
        format!("{}, {}, {}", a.as_ref(), b.as_ref(), c.as_ref())
    }
    // that was long signature!
}

// in other codes ...
assert_eq!(unsafe { bar!("a") }.await, "a, b, c");
assert_eq!(unsafe { bar!("a", "d") }.await, "a, d, c");
// you can even mix named & unnamed argument in optional arguments
assert_eq!(unsafe { bar!("a", "d", c = "e") }.await, "a, d, e");
assert_eq!(unsafe { bar!("a", c = "e") }.await, "a, b, e");

See examples for more information.

More Features

Export

Add export in the front of the function and the macro would be exported. (add pub to export function with macro)

default_args! {
    export pub fn foo() {}
}

Above macro will expand as below

pub fn foo_() {}

#[macro_export]
macro_rules! foo { () => {}; }

Path of function

Macro just call the function in name, so you should import both macro and the function to use it. By writing the path of this function, you can just only import the macro. (path should start with crate)

#[macro_use]
pub mod foo {
    default_args! {
        pub fn crate::foo::bar() {}
    }
}

// then it would create `bar!()`
bar!();

Above macro would expand as below

pub mod foo {
    pub fn bar_() {}

    macro_rules! bar {
        () => {
            $crate::foo::bar_()
        };
    }
}

Why do we have to write module?

std::module_path! can resolve the module path of the function where it is declared. However, it can be resolved in runtime, not compile-time. I couldn't find a way to get module path in compile-time.

License

MIT License

You might also like...
zero-dependency 3d math library in rust

dualquat A lightweight, zero-dependency 3d math library for use in Dual Quaternion based physics simulation. Capable of representing and transforming

An Interpreter for Brainfuck programming language implemented in the Rust programming language with zero dependencies.

Brainfuck Hello, Visitor! Hey there, welcome to my project showcase website! It's great to have you here. I hope you're ready to check out some awesom

A very opinionated, zero-configuration shell prompt
A very opinionated, zero-configuration shell prompt

A very opinionated, zero-configuration shell prompt

A zero-dependency crate for writing repetitive code easier and faster.

akin A zero-dependency crate for writing repetitive code easier and faster. Check Syntax for information about how to use it. Why? Example Syntax NONE

A truly zero-dependency crate providing quick, easy, reliable, and scalable access to the name "jordin"

jordin Finally! A truly zero-dependency crate providing quick, easy, reliable, and scalable access to the name "jordin". Additionally, this one-of-a-k

A lightweight, zero-dependency struct diffing library which allows changed fields to be collected and applied

structdiff A lightweight, zero-dependency struct diffing library which allows changed fields to be collected and applied. Derive Difference on a struc

Help your Flipper Zero perform tricks!

backflip: Help your Flipper Zero perform tricks! backflip is a CLI multi-tool to help augment and extend the capabilities of the Flipper Zero. It curr

Following "ZK HACK III - Building On-chain Apps Off-chain Using RISC Zero"

RISC Zero Rust Starter Template Welcome to the RISC Zero Rust Starter Template! This template is intended to give you a starting point for building a

A zero-config leptos component to display markdown
A zero-config leptos component to display markdown

A port of yew-markdown using leptos ! Usage You can use this component to render both static and dynamic markdown. Static markdown use leptos::*; {

Releases(v1.0.0)
Owner
Jaeyong Sung
Student of KAIST, South Korea
Jaeyong Sung
Shellfirm - Intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification

shellfirm Opppppsss you did it again? ?? ?? ?? Protect yourself from yourself! rm -rf * git reset --hard before saving? kubectl delete ns which going

elad 652 Dec 29, 2022
Yet Another Kalman Filter Implementation. As well as Lie Theory (Lie group and algebra) on SE(3). [no_std] is supported by default.

yakf - Yet Another Kalman Filter Yet Another Kalman Filter Implementation, as well as, Lie Theory (Lie group, algebra, vector) on SO(3), SE(3), SO(2),

null 7 Dec 1, 2022
Cost saving K8s controller to scale down and up of resources during non-business hours

Kube-Saver Motivation Scale down cluster nodes by scaling down Deployments, StatefulSet, CronJob, Hpa during non-business hours and save $$, but if yo

Mahesh Rayas 5 Aug 15, 2022
Parse command line arguments by defining a struct.

StructOpt Parse command line arguments by defining a struct. It combines clap with custom derive. Documentation Find it on Docs.rs. You can also check

Guillaume P. 2.6k Jan 5, 2023
parse command-line arguments into a hashmap and vec of positional args

parse command-line arguments into a hashmap and vec of positional args This library doesn't populate custom structs, format help messages, or convert types.

James Halliday 17 Aug 11, 2022
ddi is a wrapper for dd. It takes all the same arguments, and all it really does is call dd in the background

ddi A safer dd Introduction If you ever used dd, the GNU coreutil that lets you copy data from one file to another, then you may have encountered a ty

Tomás Ralph 80 Sep 8, 2022
excss is a small, simple, zero-runtime CSS-in-JS library with just two APIs.

excss excss is a small, simple, zero-runtime CSS-in-JS library with just two APIs.

Taishi Naritomi 12 Sep 12, 2023
Rust library to convert RGB 24-bit colors into ANSI 256 (8-bit) color codes with zero dependencies and at compile-time.

rgb2ansi256 rgb2ansi256 is a small Rust library to convert RGB 24-bit colors into ANSI 256 (8-bit) color codes with zero dependencies and const fn. Th

Linda_pp 7 Nov 17, 2022
A "Hello, Rust!" program for the Flipper Zero

"Hello, Rust!" for the Flipper Zero This is an example of how to build a Rust-based Flipper application that runs from the SD-card. Note: This depends

David Coles 15 Dec 17, 2022
Pure rust library for reading / writing DNG files providing access to the raw data in a zero-copy friendly way.

DNG-rs   A pure rust library for reading / writing DNG files providing access to the raw data in a zero-copy friendly way. Also containing code for re

apertus° - open source cinema 4 Dec 1, 2022