dust

Strings

Introduction

dust-framework includes a variety of string manipulation helpers through the Str extension trait, available directly on every &str and String for common tasks like generating URL slugs, formatting field labels, and truncating previews. Because the prelude imports Str, these methods are ready to use throughout your application:

rust
use dust::prelude::*;let slug = "My First Post".slug();                                       // my-first-postlet label = "first_name".headline();                                     // First Namelet table = "BlogPost".snake().plural();                                 // blog_postslet preview = "Thanks for the detailed write-up on queues".limit(20);    // Thanks for the detai...

In a file that does not import the prelude, bring the trait into scope with use dust::str::Str.

All lengths, positions, and widths operate on Unicode characters rather than raw bytes, so "这是一段中文".take(2) returns "这是". Methods that slice part of the input (such as after and take) return a borrowed &str, while methods that transform text return a new String.

Available methods

The tables below list the methods provided by the Str trait, grouped by category.

Case

Use these methods to convert identifiers and titles between naming conventions:

Method Result
"IoRustFramework".snake() io_rust_framework
"IoRustFramework".kebab() io-rust-framework
"io_rust_framework".studly() IoRustFramework
"io_rust_framework".camel() ioRustFramework
"a nice title uses the correct case".title() A Nice Title Uses The Correct Case
"EmailNotificationSent".headline() Email Notification Sent
"taylor otwell".upper_first() Taylor otwell
"Taylor".lower_first() taylor
"ioRust".split_upper() ["io", "Rust"]
"Hello World!".slug() hello-world
"Hello World!".slug_with("_") hello_world
"Ünïcödé".ascii() Unicode

A slug keeps accented letters, so "Café".slug() is café. To drop the accents too, call ascii first.

Plurals

Method Result
"photo".plural() photos
"category".plural() categories
"child".plural() children
"BlogPost".plural() BlogPosts
"blog_posts".singular() blog_post
"people".singular() person

plural and singular use English rules. In a name such as BlogPost, they change the last word and keep its case.

Substrings

These methods cut a string at a search string, a prefix, a suffix, or a number of characters:

Method Result
"app/Http/Kernel".after("/") Http/Kernel
"app/Http/Kernel".after_last("/") Kernel
"app/Http/Kernel".before("/") app
"app/Http/Kernel".before_last("/") app/Http
"[a] and [b]".between("[", "]") a] and [b
"[a] and [b]".between_first("[", "]") a
"https://dust.example".chop_start("https://") dust.example
"Photograph.rs".chop_end(".rs") Photograph
"Build something amazing!".take(5) Build

When the string doesn't contain the search, these methods return the whole string.

Replacing

Method Result
"this/string".start("/") /this/string
"this/string".finish("/") this/string/
"the fox the dog".replace_last("the", "a") the fox a dog
"Hello World".replace_start("Hello", "dust-framework") dust-framework World
"Hello World".replace_end("World", "dust-framework") Hello dust-framework
"Tacos are great!".swap(&[("Tacos", "Burritos"), ("great", "fantastic")]) Burritos are fantastic!

start and finish add the prefix or suffix only when the string doesn't already have it, so "/this/string".start("/") is still /this/string. replace_start and replace_end change the text only when the string starts or ends with the search.

To replace every match, use the standard library's replace. To replace only the first, use replacen(search, replace, 1).

Shortening and wrapping

When you show a long post or comment in a list, you'll want a preview that fits. limit cuts to a number of characters and words cuts to a number of words:

Method Result
"The quick brown fox".limit(9) The quick...
"The quick brown fox".limit_with(9, " →") The quick →
"Perfectly balanced, as all things should be.".words(3) Perfectly balanced, as...
"Perfectly balanced, as all things should be.".words_with(3, " >>>") Perfectly balanced, as >>>
"This is my name".excerpt("my", 3) Some("...is my na...")
"The quick brown fox".word_wrap(10) The quick\nbrown fox
"Hello world".word_count() 2

limit and words add the ending only when they cut the string, and the ending doesn't count toward the limit. excerpt returns the phrase with up to radius characters on each side, or None when the phrase isn't there.

Padding, masking, and cleaning

Method Result
"42".pad_start(5, '0') 00042
"James".pad_end(10, '-') James-----
"James".pad_both(10, '_') __James___
"taylor@example.com".mask('*', 3..) tay***************
"4242424242424242".mask('*', ..12) ************4242
" dust framework ".squish() dust framework
"/docs//strings///methods".deduplicate('/') /docs/strings/methods
"(555) 123-4567".digits() 5551234567

mask takes a range of character positions, counted from the start. To show only the last four digits of a 16-digit card number, mask ..12. When the string is already as wide as the width you pass, the padding methods return it unchanged.

Matching

resembles checks a string against a pattern in which * matches any characters, including none. The match is case-sensitive and must cover the whole string, which makes it useful for checking a path against a list of patterns:

rust
"posts/1/edit".resembles("posts/*");   // true"posts/1/edit".resembles("*/edit");    // true"posts".resembles("posts/*");          // false

For a plain substring, prefix, or suffix, use the standard library's contains, starts_with, and ends_with. For more complex patterns, use the regex crate.

Random strings and identifiers

When generating invitation links, API tokens, or unique identifiers, use the functions in dust::str, which draw from the operating system's cryptographically secure random number generator:

rust
use dust::str::{self, Ulid, Uuid};let token: String = str::random(40);         // 40 letters and digitslet password: String = str::password(16);    // letters, digits, and symbolslet id: Uuid = str::uuid();                  // a version 4 UUIDlet ordered: Uuid = str::uuid7();            // a version 7 UUID, which sorts by timelet ulid: Ulid = str::ulid();                // a ULID, such as 01K7XRWX0E4CMFRGZ8F5T0XFJN

Because uuid7 and ulid embed a creation timestamp at the start, they sort chronologically and append cleanly to database B-tree indexes, making them a better choice for primary keys than random uuid values.

random and password return a String, while uuid, uuid7, and ulid return typed Uuid and Ulid values (call .to_string() when you need a string representation). Both Uuid and Ulid work directly in models, queries, and route parameters. Models with a Uuid or Ulid primary key generate IDs automatically on creation, so call uuid7 or ulid directly only when generating identifiers outside a model key.

Use random for a token you hand out, such as an invitation code, and a hash of it for storage when the token is a bearer secret. Storing the token itself turns a database read into a credential. The hashing guide covers the hash you store.

Unicode and performance

All lengths, positions, and widths count Unicode scalar values, not bytes, so a string with accented letters or emoji is cut at a character boundary. That is what you expect for a preview, but it is not the same as a user-perceived character: an emoji built from several scalars, or a letter with a combining mark, can be split by take or limit. For text that must not split a grapheme, use a Unicode segmentation crate and slice by grapheme boundary.

limit and words allocate a new String only when they cut; when the input already fits, they return a borrowed slice where the method's return type allows it. The case helpers and slug always allocate, because they build a new value. For a hot path that formats the same label on every request, compute it once and store it rather than calling snake or headline in the template.

Common mistakes

Mistake Result Fix
"Café".slug() café, not cafe Call .ascii() first, then .slug().
"a,b".limit(1) a... (the ending is added) Use take(1) when you want no ending.
Masking with a byte range A panic or a wrong cut on non-ASCII Mask by character positions; the range is in characters.
replace for one occurrence Every match changes Use replacen(search, replace, 1) or replace_last.
resembles("*.rs") on a/b.rs true, because * crosses / Check the path segments yourself if / must not match.

The plural rules are English and deliberately small. Product names, acronyms, and irregular nouns in another language need their own mapping; don't route user-facing copy through plural when a wrong form would be visible.