Struct formatify::Formatify

source ·
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

  1. Placeholder Replacement: Replace placeholders in strings with values from a HashMap.
  2. Length Measurement: Measure lengths of strings and placeholders.
  3. 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

source

pub fn new() -> Self

source

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 with key in the key_value HashMap.
  • Left Alignment: %<(width). Aligns the following placeholder to the left within a field of width characters.
  • Left Alignment with Truncation: %<(width,trunc). Same as left alignment, but truncates the value to fit within the specified width.
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.

source

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"
source

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"]);

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.