### Using textdistance.rs in No-std Rust Environments Source: https://context7.com/life4/textdistance.rs/llms.txt Illustrates the usage of textdistance.rs algorithms (Hamming, Levenshtein) within a no_std Rust environment. This example demonstrates comparing byte sequences, which is common for sensor data or other raw data in embedded systems. Note that some algorithms require the 'std' feature. ```rust #!/usr/bin/env // Works in no_std environment #![no_std] use textdistance::{Algorithm, Hamming, Levenshtein}; fn compare_sensor_data() { let hamming = Hamming::default(); let levenshtein = Levenshtein::default(); // Compare byte sequences from sensors let data1 = [0x01, 0x02, 0x03, 0x04]; let data2 = [0x01, 0x05, 0x03, 0x06]; let result = hamming.for_vec(&data1, &data2); assert_eq!(result.dist(), 2); // Most algorithms available without std // Note: Some algorithms (Jaccard, Cosine, Bag, etc.) require std feature } ``` -------------------------------- ### Advanced Usage with Algorithm Trait (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Illustrates advanced usage of the `Algorithm` trait to access both raw distance and normalized metrics (distance and similarity) from a single calculation. This example demonstrates Hamming and Levenshtein algorithms, including custom cost configurations for Levenshtein. ```rust use textdistance::{Algorithm, Hamming, Levenshtein}; fn main() { // Hamming distance example let hamming = Hamming::default(); let result = hamming.for_str("karolin", "kathrin"); assert_eq!(result.val(), 3); // raw distance value assert_eq!(result.dist(), 3); // absolute distance assert_eq!(result.sim(), 4); // absolute similarity (matching chars) assert_eq!(result.ndist(), 3.0/7.0); // normalized distance assert_eq!(result.nsim(), 4.0/7.0); // normalized similarity // Levenshtein with custom costs let custom_lev = Levenshtein { del_cost: 1, ins_cost: 2, sub_cost: 3, }; let result = custom_lev.for_str("abc", "axc"); assert_eq!(result.val(), 3); // substitution cost } ``` -------------------------------- ### Comparing Vectors of Arbitrary Types (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Demonstrates how to compare vectors of arbitrary types using the `Algorithm` trait, provided the element type implements `Eq` and `Hash`. This example shows comparisons for integer vectors and vectors of custom enum types. ```rust use textdistance::{Algorithm, Hamming}; fn main() { let hamming = Hamming::default(); // Compare integer vectors let vec1 = vec![1, 2, 3, 4]; let vec2 = vec![1, 5, 3, 6]; let result = hamming.for_vec(&vec1, &vec2); assert_eq!(result.dist(), 2); // positions 1 and 3 differ // Compare enum values #[derive(PartialEq, Eq, Hash)] enum Color { Red, Green, Blue } let colors1 = vec![Color::Red, Color::Green, Color::Blue]; let colors2 = vec![Color::Red, Color::Blue, Color::Blue]; let result = hamming.for_vec(&colors1, &colors2); assert_eq!(result.dist(), 1); } ``` -------------------------------- ### Comparing Custom Iterators (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Explains how to compare sequences using custom iterators, which are not limited to strings or vectors. This example showcases comparing number ranges and filtered character iterators from strings. ```rust use textdistance::{Algorithm, Levenshtein}; fn main() { let lev = Levenshtein::default(); // Compare ranges let result = lev.for_iter(1..5, 1..7); assert_eq!(result.val(), 2); // need to add 5 and 6 // Compare filtered iterators let s1 = "hello world"; let s2 = "hola mundo"; let result = lev.for_iter( s1.chars().filter(|c| !c.is_whitespace()), s2.chars().filter(|c| !c.is_whitespace()) ); assert_eq!(result.dist(), 8); } ``` -------------------------------- ### Configuring textdistance.rs for No-std Environments Source: https://context7.com/life4/textdistance.rs/llms.txt Shows how to configure the textdistance.rs crate for use in no_std embedded systems by disabling default features in Cargo.toml. This reduces the binary size and dependency footprint for resource-constrained environments. ```toml # In your Cargo.toml, disable default features [dependencies] textdistance = { version = "1.1", default-features = false } ``` -------------------------------- ### Fast Algorithms for Performance-Critical Code (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Presents fast string comparison algorithms like Hamming, Sift4Simple, and Levenshtein, suitable for performance-critical applications. It highlights their speed and use cases, recommending Hamming or Sift4 for real-time needs and Levenshtein for accuracy. ```rust use textdistance::{Algorithm, Hamming, Sift4Simple, Levenshtein}; fn main() { // Hamming: fastest (19 µs), only detects substitutions let hamming = Hamming::default(); let result = hamming.for_str("abcd", "abxd"); assert_eq!(result.dist(), 1); // very fast, equal length only // Sift4Simple: very fast (144 µs), detects transpositions let sift4 = Sift4Simple::default(); let result = sift4.for_str("abcd", "acbd"); assert!(result.dist() <= 2); // fast and flexible // Levenshtein: moderate speed (4.6 ms), comprehensive let lev = Levenshtein::default(); let result = lev.for_str("kitten", "sitting"); assert_eq!(result.dist(), 3); // accurate, reasonable speed // For real-time/high-volume: prefer Hamming or Sift4 // For accuracy with acceptable latency: use Levenshtein // For comprehensive analysis: consider Jaro or DamerauLevenshtein } ``` -------------------------------- ### Choosing the Right Text Distance Algorithm in Rust Source: https://context7.com/life4/textdistance.rs/llms.txt Demonstrates how to use different text distance algorithms (Hamming, Jaro, Levenshtein, DamerauLevenshtein) in Rust to detect various types of string differences. Each algorithm has different performance characteristics and sensitivity to specific edits (substitutions, transpositions, insertions, deletions). ```rust use textdistance::{Algorithm, Hamming, Jaro, Levenshtein, DamerauLevenshtein}; fn main() { let s1 = "example"; let s2 = "exmaple"; // transposed 'a' and 'm' // Hamming: detects only substitutions (fast) let hamming = Hamming::default(); assert_eq!(hamming.for_str(s1, s2).dist(), 2); // sees as 2 substitutions // Jaro: detects transpositions (fast, for short strings) let jaro = Jaro::default(); let jaro_result = jaro.for_str(s1, s2); assert!(jaro_result.nsim() > 0.95); // recognizes transposition // Levenshtein: insertions, deletions, substitutions (moderate speed) let lev = Levenshtein::default(); assert_eq!(lev.for_str(s1, s2).dist(), 2); // sees as delete + insert // DamerauLevenshtein: all operations including transpositions (slow) let dl = DamerauLevenshtein::default(); assert_eq!(dl.for_str(s1, s2).dist(), 1); // recognizes as 1 transposition } ``` -------------------------------- ### Unicode Grapheme Cluster Support with Levenshtein (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Demonstrates handling Unicode correctly using the `unicode-segmentation` crate with the Levenshtein distance algorithm. It shows how to compare strings based on grapheme clusters for accurate results with accented characters. ```rust use textdistance::{Algorithm, Levenshtein}; // Note: requires unicode-segmentation crate in your Cargo.toml // unicode-segmentation = "1.10" fn main() { use unicode_segmentation::UnicodeSegmentation; let lev = Levenshtein::default(); // Strings with combining characters let s1 = "café"; let s2 = "cafe\u{0301}"; // e + combining acute accent // Using grapheme clusters (treats é as single unit) let g1 = s1.graphemes(true); let g2 = s2.graphemes(true); let result = lev.for_iter(g1, g2); assert_eq!(result.dist(), 0); // considered identical // Compare to char-based (treats combining mark as separate) let char_result = lev.for_str(s1, s2); // This would show a difference } ``` -------------------------------- ### Unicode Grapheme Cluster Comparison with textdistance (Rust) Source: https://github.com/life4/textdistance.rs/blob/master/README.md Demonstrates how to use the `unicode-segmentation` crate in conjunction with `textdistance` to correctly handle Unicode grapheme clusters. This ensures characters like 'é' are treated as single units for distance calculations. ```rust use textdistance::{Algorithm, DamerauLevenshtein}; use unicode_segmentation::UnicodeSegmentation; let s1 = "a̐éö̲\r\n"; let s2 = "éa̐ö̲\r\n"; let g1 = s1.graphemes(true); let g2 = s2.graphemes(true); let a = DamerauLevenshtein::default(); let r = a.for_iter(g1, g2); assert!(r.val() == 1); ``` -------------------------------- ### Advanced Damerau-Levenshtein Algorithm Usage (Rust) Source: https://github.com/life4/textdistance.rs/blob/master/README.md Illustrates advanced usage by instantiating the `DamerauLevenshtein` struct and calling its `for_str` method. This provides access to both the absolute (`val`) and normalized (`nval`) results, as well as distance and similarity metrics. ```rust use textdistance::{Algorithm, DamerauLevenshtein}; let a = DamerauLevenshtein::default(); let r = a.for_str("abc", "acbd"); assert!(r.val() == 2); assert!(r.nval() == 2./4.); ``` -------------------------------- ### Token-Based Algorithms for Set Comparison (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Compares sequences as sets of unique elements using Jaccard, Cosine, and Tversky similarity algorithms. These are useful for comparing collections where order may not be important. ```rust use textdistance::{Algorithm, Jaccard, Cosine, Tversky}; fn main() { // Jaccard similarity (intersection over union) let jaccard = Jaccard::default(); let result = jaccard.for_str("abc", "acbd"); assert_eq!(result.nsim(), 0.75); // {a,b,c} ∩ {a,c,b,d} / {a,b,c,d} // Cosine similarity let cosine = Cosine::default(); let result = cosine.for_str("hello", "hallo"); assert!(result.nsim() > 0.8); // Tversky with custom weights (asymmetric comparison) let tversky = Tversky { alpha: 0.8, // weight for first sequence beta: 0.2, // weight for second sequence bias: 0.0, }; let result = tversky.for_str("prototype", "proto"); assert!(result.nsim() > 0.0); } ``` -------------------------------- ### Word-Based Sequence Comparison (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Illustrates word-based comparison for text analysis, contrasting it with character-level comparison. This is useful for comparing sentences or phrases where the fundamental units are words rather than individual characters. ```rust use textdistance::{Algorithm, Levenshtein}; fn main() { let lev = Levenshtein::default(); // Compare sentences by words let s1 = "the quick brown fox"; let s2 = "the fast brown fox"; let result = lev.for_words(s1, s2); assert_eq!(result.dist(), 1); // only "quick" vs "fast" differs // Character-level would show much larger difference let char_result = lev.for_str(s1, s2); assert_eq!(char_result.dist(), 4); // "quick" → "fast" } ``` -------------------------------- ### Sequence-Based Algorithms for Finding Common Patterns (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Finds common patterns in sequences using Longest Common Subsequence (LCSSeq), Longest Common Substring (LCSStr), and Ratcliff-Obershelp algorithms. These are useful for identifying shared parts of strings. ```rust use textdistance::{Algorithm, LCSSeq, LCSStr, RatcliffObershelp}; fn main() { // Longest Common Subsequence (non-contiguous) let lcs_seq = LCSSeq::default(); let result = lcs_seq.for_str("abcdef", "xbcegf"); assert_eq!(result.val(), 4); // "bcef" is longest common subsequence // Longest Common Substring (contiguous) let lcs_str = LCSStr::default(); let result = lcs_str.for_str("abcdef", "xbcegf"); assert_eq!(result.val(), 2); // "bc" is longest common substring // Ratcliff-Obershelp (Gestalt pattern matching) let ro = RatcliffObershelp::default(); let result = ro.for_str("abc", "acbd"); assert_eq!(result.nval(), 0.5714285714285714); } ``` -------------------------------- ### Jaro-Winkler for Fuzzy Name Matching (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Utilizes the Jaro-Winkler algorithm for comparing strings, particularly effective for names with common prefixes. It supports default configurations and custom weighting for prefix importance and length. ```rust use textdistance::{Algorithm, JaroWinkler}; fn main() { let jw = JaroWinkler::default(); // High similarity for names with common prefixes let result = jw.for_str("martha", "marhta"); assert_eq!(result.nsim(), 0.9611111111111111); // very similar // Custom configuration for different prefix weighting let custom_jw = JaroWinkler { prefix_weight: 0.15, // increase prefix importance max_prefix: 6, // consider longer prefixes ..Default::default() }; let result = custom_jw.for_str("dixon", "dicksonx"); assert!(result.nsim() > 0.8); // good match despite differences } ``` -------------------------------- ### Normalized Distance Calculation for Percentage Comparison (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Shows how to obtain normalized distance values between 0.0 and 1.0 for percentage-based comparisons. This is particularly useful when you need to understand the degree of difference relative to the length of the sequences, handling both identical and different length strings, including empty ones. ```rust use textdistance::nstr::hamming; use textdistance::nstr::levenshtein; fn main() { // 0.0 = identical, 1.0 = completely different let norm_dist = hamming("abcd", "abxd"); assert_eq!(norm_dist, 0.25); // 1 char differs out of 4 = 25% // Compare strings of different lengths let norm_lev = levenshtein("test", "testing"); assert_eq!(norm_lev, 3.0/7.0); // 3 edits needed, longer string is 7 chars // Empty strings comparison assert_eq!(hamming("", ""), 0.0); } ``` -------------------------------- ### Calculate Levenshtein Distance Between Strings (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Demonstrates the use of shortcut functions to quickly calculate the Levenshtein distance between two strings. This is useful for determining the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. ```rust use textdistance::str::levenshtein; fn main() { // Calculate minimum edits needed to transform one string to another let distance = levenshtein("kitten", "sitting"); assert_eq!(distance, 3); // substitute k→s, e→i, add g // Works with any strings assert_eq!(levenshtein("hello", "world"), 4); assert_eq!(levenshtein("abc", "abc"), 0); assert_eq!(levenshtein("", "test"), 4); } ``` -------------------------------- ### Bigram-Based Comparison for Improved Accuracy (Rust) Source: https://context7.com/life4/textdistance.rs/llms.txt Enhances string comparison accuracy by using bigrams (pairs of characters) with Cosine and Jaccard algorithms. This method is more robust for fuzzy matching than standard character-by-character comparison. ```rust use textdistance::{Algorithm, Cosine, Jaccard}; fn main() { let cosine = Cosine::default(); // Regular character comparison let char_result = cosine.for_str("night", "nacht"); // Bigram comparison (more robust) let bigram_result = cosine.for_bigrams("night", "nacht"); // Compares: {ni,ig,gh,ht} vs {na,ac,ch,ht} // Common: "ht", so some similarity detected // Bigrams work well for fuzzy matching let jaccard = Jaccard::default(); let result = jaccard.for_bigrams("testing", "resting"); assert!(result.nsim() > 0.7); // high similarity via bigrams } ``` -------------------------------- ### Calculate Damerau-Levenshtein Distance for Strings (Rust) Source: https://github.com/life4/textdistance.rs/blob/master/README.md Demonstrates the basic usage of the `damerau_levenshtein` function from the `textdistance::str` module to calculate the edit distance between two strings. This is a shortcut for direct string comparisons. ```rust use textdistance::str::damerau_levenshtein; assert!(damerau_levenshtein("abc", "acbd") == 2); ``` -------------------------------- ### Calculate Normalized Damerau-Levenshtein Distance (Rust) Source: https://github.com/life4/textdistance.rs/blob/master/README.md Shows how to compute the normalized Damerau-Levenshtein distance between two strings using the `damerau_levenshtein` function from the `textdistance::nstr` module. The result is a floating-point value between 0.0 and 1.0. ```rust use textdistance::nstr::damerau_levenshtein; assert!(damerau_levenshtein("abc", "acbd") == 2./4.); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.