15 releases

new 0.6.2 Feb 4, 2025
0.5.7 Mar 5, 2024
0.5.6 Jul 4, 2023
0.5.3 Nov 20, 2022
0.1.3 Oct 4, 2020

#57 in Text processing

Download history 48783/week @ 2024-10-19 39984/week @ 2024-10-26 42245/week @ 2024-11-02 36256/week @ 2024-11-09 39906/week @ 2024-11-16 33275/week @ 2024-11-23 34464/week @ 2024-11-30 39903/week @ 2024-12-07 39856/week @ 2024-12-14 17527/week @ 2024-12-21 20573/week @ 2024-12-28 43154/week @ 2025-01-04 50965/week @ 2025-01-11 48772/week @ 2025-01-18 45661/week @ 2025-01-25 42056/week @ 2025-02-01

195,323 downloads per month
Used in 252 crates (62 directly)

MIT license

155KB
4.5K SLoC

const-str

Crates.io MIT licensed Docs Downloads

Compile-time string operations

Documentation: https://docs.rs/const-str/

Contributing

Sponsor

If my open-source work has been helpful to you, please sponsor me.

Every little bit helps. Thank you!


lib.rs:

Compile-time string operations. See the macro list for what you need.

MSRV: Rust 1.77.0

Troubleshoot

You don't have to care about this section unless you come across some compile errors about const evaluation.

error[E0435]: attempt to use a non-constant value in a constant

There are mainly two kinds of macros in this crate, which have different requirements for the arguments.

const-context only

These macros can only be used in const contexts. The expanded code is equivalent to compute new constant items. It implies that the arguments of these macros must be constant values, similar to consteval in C++ world.

The following examples will not work:

const fn foo(a: &str, b: &str) -> &str {
   const_str::concat!(a, b)
}
const C: &str = {
    let a = "Hello";
    let b = "World";
    const_str::concat!(a, b);
};

Instead, this way will work:

const A: &str = "Hello";
const B: &str = "World";
const C: &str = const_str::concat!(A, " ", B);
assert_eq!(C, "Hello World");

const-fn compatible

These macros can be used in const contexts and const functions. The expanded code is equivalent to calling const functions. It implies that the arguments of these macros can be any expressions, similar to constexpr in C++ world.

const fn calc(y: &str, m: &str, d: &str) -> u64 {
    let y = const_str::parse!(y, u64);
    let m = const_str::parse!(m, u64);
    let d = const_str::parse!(d, u64);
    (y * 10000 + m * 100 + d)
}
const TIME: u64 = calc("2025", "01", "26");
assert_eq!(TIME, 20250126);

You can also use these macros in normal functions, but they may be much slower than the runtime equivalents. It's recommended to use them only if you need compile-time evaluation.

Dependencies

~0–750KB
~13K SLoC