static_str_ops
The static_str_ops crate solves a longstanding issue about how to
perform non-const string operations, e.g., format!(), concat!(), etc.
and return static string, i.e., &'static str.
Internally, the crate uses a global static HashSet to store all the static strings, and return the reference to the string in the HashSet if the string has been staticized before.
[!NOTE] With this crate, the staticized strings will leaked and the reference is hold by the underlying
HashSet. Thedestaticize()method can be used to released the previously added strings.
APIs
This create provides the following macros and functions:
-
staticize(s: &str) -> &'static strConvert a string to a static string. If the string has been staticized before, return the reference to the string in the HashSet. This function is the most basic usage of this crate, e.g.,
Examples:
use staticize; let s: &'static str = staticize; -
is_staticized(s: &str) -> boolCheck if a string has been staticized before.
Examples:
let s: &'static str = staticize; assert!; -
destaticize(s: &str) -> boolRemove a string from the HashSet. Return true if the string was present and is successfully removed, false otherwise.
Examples:
let s: &'static str = staticize; assert!; -
static_concat!(s1: expr, s2: expr, ...) -> &'static strConcatenate multiple strings into a static string. The arguments can be either a string literal. Like
concat!(), but returns a static string.Examples:
let hello_world: &'static str = static_concat!; -
static_format!(s: expr, ...) -> &'static strFormat a string into a static string. The arguments can be whatever the builtin macro
format!()can accept. Likeformat!(), but returns a static string.let name = "John"; let age = 30; let message = static_format!; -
staticize_once!(expr: expr) -> &'static strSimilar to staticize(), but the expr will be evaluated only once. Under the hood,
std::sync::Onceis used.Examples:
let s: &'static str = staticize_once!;The function will be useful if you have a function that want to return a static string, while the generate logic is non-trivial, and you want this process only happen once, e.g.,
use *; let make_string = ; let s1: &'static str = make_string; let s2: &'static str = make_string;When you call
make_string()for multiple times, the body will be guaranteed to be evaluated only once.
License
This project is licensed under the BSD-3 Clause license (LICENSE or http://opensource.org/licenses/BSD-3-Clause).