Copy-on-write string utilities for Rust
source link: https://rreverser.com/gh-cow-utils-rs/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Copy-on-write string utilities for Rust
Obsessed D2D programmer (parsers, compilers, tools & specs). Sometimes human.
I wrote variations of these string manipulation utils so many times in various projects, so...
Introducing cow-utils - a helper crate for @rustlang that allows to perform zero-alloc string transformations when no transformation is actually necessary.
Some str
methods
perform destructive transformations and so they allocate, copy into and
return a newString
even
when no modification is necessary.
This crate provides a helper trait CowUtils
with drop-in variants of
such methods, which behave in the same way, but avoid extra copies and
allocations when no modification is necessary.
For now it's only implemented for &str
and returnsstd::borrow::Cow<str>
,
but in the future might be extended to other types where even more
efficient handling is possible (e.g. in-place modifications on mutable
strings).
Performance
The primary motivation for this crate was ability to perform zero-alloc replacements when no match is found, so showing results only for .replace
vs .cow_replace
for now.
The actual results will vary depending on the inputs, but here is a taster based on "a".repeat(40)
as an input and various modes (nothing matched, everything matched and replaced, everything matched from the start and deleted):
params .replace (ns) .cow_replace (ns) difference (%)
("a", "") 408.59 290.27 -29
("b", "c") 98.78 54.00 -45
("a", "b") 985.99 1,000.70 +1
Usage
First, you need to import CowUtils
into the scope:
use cow_utils::CowUtils;
Then you can start invoking following .cow_
-prefixed methods on
strings instead of the regular ones:
.cow_replace
instead ofstr::replace
.cow_replacen
instead ofstr::replacen
.cow_to_ascii_lowercase
instead ofstr::to_ascii_lowercase
.cow_to_ascii_uppercase
instead ofstr::to_ascii_uppercase
.cow_to_lowercase
instead ofstr::to_lowercase
.cow_to_uppercase
instead ofstr::to_uppercase
Check out the docs for detailed examples.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK