pub struct Formatify;Expand description
Formatify is a struct in the formatify library, a versatile string formatting tool in Rust.
It provides methods for replacing placeholders in a string with values from a HashMap,
measuring the lengths of strings with placeholders, and extracting placeholder keys from a string.
This struct is the core of the library, enabling users to perform various string formatting tasks
efficiently. With methods like replace_placeholders, measure_lengths, and extract_placeholder_keys,
Formatify simplifies the process of dynamic string manipulation, catering to use cases where
template-based string formatting is essential.
Usage
Import the necessary modules and use Formatify for string formatting tasks:
use formatify::Formatify;
use std::collections::HashMap;Features
- Placeholder Replacement: Replace placeholders in strings with values from a
HashMap. - Length Measurement: Measure lengths of strings and placeholders.
- Placeholder Extraction: Extract placeholder keys from a string.
Examples
Replacing Placeholders
let mut key_value: HashMap<&str, String> = HashMap::new();
key_value.insert("name", "Alice".into());
let formatter = Formatify::new();
let formatted_string = formatter.replace_placeholders(&key_value, "Hello, %(name)!");
assert_eq!(formatted_string, "Hello, Alice!");Measuring Lengths
let mut key_value: HashMap<&str, String> = HashMap::new();
key_value.insert("name", "Alice".into());
let formatter = Formatify::new();
let segment_lengths = formatter.measure_lengths(&key_value, "Hello, %(name)! This is a test.");
assert_eq!(segment_lengths, vec![29, 5]); // Total length with "Alice" as the placeholder, length of "Alice"Extracting Placeholder Keys
let mut key_value: HashMap<&str, String> = HashMap::new();
key_value.insert("name", "Alice".into());
let formatter = Formatify::new();
let placeholder_keys = formatter.extract_placeholder_keys(&key_value, "Hello, %(name)! Today is %(day).");
assert_eq!(placeholder_keys, vec!["name"]);Implementations§
source§impl Formatify
impl Formatify
pub fn new() -> Self
sourcepub fn replace_placeholders(
&self,
key_value: &HashMap<&str, String>,
inp: &str
) -> String
pub fn replace_placeholders( &self, key_value: &HashMap<&str, String>, inp: &str ) -> String
Replaces placeholders in the input string with corresponding values from a HashMap.
This method scans the input string inp for placeholders, identified by a specific
syntax, and replaces them with corresponding values from the key_value HashMap. The function
supports various types of placeholders, including simple variable substitution, left alignment,
and optional truncation.
Placeholder Formats
- Simple Variable Substitution:
%(key). Replaces this placeholder with the value associated withkeyin thekey_valueHashMap. - Left Alignment:
%<(width). Aligns the following placeholder to the left within a field ofwidthcharacters. - Left Alignment with Truncation:
%<(width,trunc). Same as left alignment, but truncates the value to fit within the specifiedwidth.
Arguments
key_value- A reference to a HashMap where keys correspond to placeholder identifiers in the input string and values are their replacements.inp- The input string containing placeholders.
Returns
A new String with placeholders replaced by their respective values from the key_value HashMap.
If a placeholder has no corresponding value in the map, it remains unchanged in the output string.
Examples
let mut key_value : HashMap<&str, String> = HashMap::new();
key_value.insert("name", "Alice".into());
key_value.insert("date", "Monday".into());
let formatter = Formatify::new();
let formatted_string = formatter.replace_placeholders(&key_value, "Hello, %(name)! Today is %<(10)%(date).");
assert_eq!(formatted_string, "Hello, Alice! Today is Monday .");This function is essential for dynamic string formatting in the Formatify library. It allows users to create template strings with various types of placeholders, which can be filled with different values at runtime. This is particularly useful for generating customized messages, dynamic user interfaces, or any other text-based content that needs to be generated or modified based on changing data.
sourcepub fn measure_lengths(
&self,
key_value: &HashMap<&str, String>,
inp: &str
) -> Vec<usize>
pub fn measure_lengths( &self, key_value: &HashMap<&str, String>, inp: &str ) -> Vec<usize>
Measures the length of the entire string and the lengths of valid placeholders within it.
This method processes the input string inp, which is analyzed as if it were to be formatted.
Instead of replacing the placeholders, it calculates the overall length of the string with
placeholders hypothetically replaced, followed by the lengths of each valid placeholder. This
is particularly useful for layout planning and understanding the impact of placeholders on the
total length of the string.
Arguments
key_value- A reference to a HashMap containing key-value pairs. The keys represent placeholders in the input string, and the values are their potential replacements.inp- The input string with placeholders to be measured.
Returns
A Vec<usize> where the first element represents the length of the entire string with placeholders
replaced, and subsequent elements represent the lengths of each valid placeholder. Placeholders
are replaced with their corresponding values from the key_value HashMap for these calculations.
Examples
let mut key_value : HashMap<&str, String> = HashMap::new();
key_value.insert("name", "Alice".into());
let formatter = Formatify::new();
let segment_lengths = formatter.measure_lengths(&key_value, "Hello, %(name)! This is a test.");
assert_eq!(segment_lengths, vec![29, 5]); // Total length with "Alice" as the placeholder, length of "Alice"sourcepub fn extract_placeholder_keys(
&self,
key_value: &HashMap<&str, String>,
inp: &str
) -> Vec<String>
pub fn extract_placeholder_keys( &self, key_value: &HashMap<&str, String>, inp: &str ) -> Vec<String>
Extracts and lists all valid placeholder keys from a given string.
This method analyzes the input string inp to identify and collect the keys of all
placeholders defined within it. Placeholders are identified by a specific syntax, typically
denoted by %(key). This function is particularly useful for determining which placeholders
are used in a string without modifying the string itself. It helps in preparing or validating
the necessary keys in a key-value map for subsequent processing, like formatting or replacing
placeholders.
Arguments
key_value- A reference to a HashMap containing key-value pairs. These pairs may be used within the placeholder syntax in the input string.inp- The input string to be analyzed for placeholder keys.
Returns
A Vec<String> containing all distinct placeholder keys found in the input string. If no
placeholders are found, an empty vector is returned.
Examples
let mut key_value : HashMap<&str, String> = HashMap::new();
key_value.insert("name", "Alice".into());
let formatter = Formatify::new();
let placeholder_keys = formatter.extract_placeholder_keys(&key_value, "Hello, %(name)! Today is %(day).");
assert_eq!(placeholder_keys, vec!["name"]);