Skip to main content

rumtk_core/
strings.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2024  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20use crate::base::{is_unique, RUMResult, RUMVec};
21use crate::buffers::RUMBuffer;
22use base64::prelude::*;
23use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
24use encoding_rs::Encoding;
25pub use rumtk_arena::base::RUMString;
26pub use rumtk_arena::mem::traits::*;
27use std::cmp::min;
28pub use std::format as rumtk_format;
29pub use std::primitive::str;
30use unicode_segmentation::UnicodeSegmentation;
31/**************************** Constants**************************************/
32const ESCAPED_STRING_WINDOW: usize = 6;
33const ASCII_ESCAPE_CHAR: char = '\\';
34pub const ASCII_READABLE_MIN: char = ' ';
35pub const ASCII_READABLE_MAX: char = '~';
36pub const ASCII_ESCAPE_PREFIX_LOWER: &str = "\\x";
37pub const ASCII_ESCAPE_PREFIX_UPPER: &str = "\\X";
38pub const ASCII_ESCAPE_PREFIX_DEFAULT: &str = ASCII_ESCAPE_PREFIX_LOWER;
39pub const ASCII_ALLOWED_NONPRINT: &[char; 2] = &[
40    '\n',    //Line Feed
41    '\r'     //Carriage Return
42];
43pub const EMPTY_STRING: &str = "";
44pub static EMPTY_RUMSTRING: RUMString = RUMString::default();
45pub const DOT_STR: &str = ".";
46pub const EMPTY_STRING_OPTION: Option<&str> = Some("");
47pub const READABLE_ASCII: &str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
48
49/**************************** Types *****************************************/
50pub type StringReplacementPair<'a> = [(&'a str, &'a str)];
51pub type Grapheme<'a> = &'a str;
52pub type GraphemeStringView<'a> = RUMVec<Grapheme<'a>>;
53pub type GraphemePattern<'a> = &'a [Grapheme<'a>];
54pub type GraphemeSlice<'b, 'a> = &'b [Grapheme<'a>];
55pub type GraphemePatternPair<'a> = (GraphemePattern<'a>, GraphemePattern<'a>);
56
57///
58/// The equivalent to a `stringview` but at the grapheme level. Meaning, we can use this view to
59/// iterate through a string at the full `UTF8` implementation
60///
61#[derive(Default, Debug, PartialEq, Clone)]
62pub struct GraphemeStr<'a> {
63    view: GraphemeStringView<'a>,
64    start: usize,
65    end: usize,
66}
67
68impl<'a> GraphemeStr<'a> {
69    pub fn from(string: &'a str) -> Self {
70        let view = string.graphemes(true).collect::<GraphemeStringView>();
71        Self::from_view(view)
72    }
73
74    pub fn from_view(view: GraphemeStringView<'a>) -> Self {
75        let start = 0;
76        let end = view.len();
77        Self { view, start, end }
78    }
79
80    pub fn at(&self, index: usize) -> Grapheme<'a> {
81        self.view[index]
82    }
83
84    pub fn trim(&self, pattern: &GraphemePatternPair<'a>) -> Self {
85        let (left_pattern, right_pattern) = pattern;
86        self.trim_left(left_pattern).trim_right(right_pattern)
87    }
88
89    pub fn trim_left(&self, pattern: &GraphemePattern<'a>) -> Self {
90        let new_offset = self.find(pattern, self.start);
91        Self {
92            view: self.view.clone(),
93            start: new_offset,
94            end: self.end,
95        }
96    }
97
98    pub fn trim_right(&self, pattern: &GraphemePattern<'a>) -> Self {
99        let new_offset = self.rfind(pattern, self.end);
100        Self {
101            view: self.view.clone(),
102            start: self.start,
103            end: new_offset,
104        }
105    }
106
107    pub fn splice(&self, skip_pattern: &GraphemePatternPair<'a>) -> Self {
108        let (left_pattern, right_pattern) = skip_pattern;
109        let mut new_view = GraphemeStringView::with_capacity(self.end - self.start);
110        let mut offset = self.start;
111        let l_pattern_s = left_pattern.len();
112
113        while offset < self.end {
114            let target_s = self.find(left_pattern, offset) + l_pattern_s;
115            for i in offset..target_s {
116                new_view.push(self.view[i]);
117            }
118            offset = self.find(right_pattern, target_s);
119        }
120
121        GraphemeStr::from_view(new_view)
122    }
123
124    pub fn find(&self, pattern: &GraphemePattern<'a>, offset: usize) -> usize {
125        let pattern_s = pattern.len();
126        let mut new_offset = offset;
127        let mut pattern_end = new_offset + pattern_s;
128
129        while new_offset < self.end && pattern_end < self.end {
130            if self.view[new_offset..pattern_end] == **pattern {
131                break;
132            }
133
134            new_offset += 1;
135            pattern_end = new_offset + pattern_s;
136        }
137
138        new_offset
139    }
140
141    pub fn rfind(&self, pattern: &GraphemePattern<'a>, offset: usize) -> usize {
142        let pattern_s = pattern.len();
143        let mut new_offset = offset;
144        while new_offset > self.start {
145            if self.view[new_offset - pattern_s..new_offset] == **pattern {
146                break;
147            }
148
149            new_offset -= 1;
150        }
151
152        new_offset
153    }
154
155    pub fn len(&self) -> usize {
156        self.end - self.start
157    }
158
159    pub fn get_graphemes(&self) -> GraphemeSlice<'_, 'a> {
160        &self.view[self.start..self.end]
161    }
162
163    pub fn truncate(&self, size: usize) -> Self {
164        let end = min(size, self.end);
165        Self {
166            view: self.view.clone(),
167            start: self.start,
168            end,
169        }
170    }
171
172    pub fn is_unique(&self) -> bool {
173        is_unique(&self.view)
174    }
175}
176
177impl ToString for GraphemeStr<'_> {
178    fn to_string(&self) -> String {
179        let mut new_string = String::with_capacity(self.len());
180
181        for grapheme in self.view[self.start..self.end].iter() {
182            new_string.push_str(grapheme);
183        }
184
185        new_string
186    }
187}
188
189impl RUMStringConversions for GraphemeStr<'_> {}
190
191/**************************** Traits ****************************************/
192
193pub trait StringLike {
194    fn with_capacity(capacity: usize) -> Self;
195    fn push_str(&mut self, string: &str);
196}
197
198pub trait AsString {
199    fn as_string(&self) -> RUMString;
200}
201
202pub trait AsStr {
203    fn as_str(&self) -> &str;
204    fn as_grapheme_str(&self) -> GraphemeStr {
205        GraphemeStr::from(self.as_str())
206    }
207}
208
209pub trait RUMStringConversions: ToString {
210    #[inline(always)]
211    fn to_raw(&self) -> RUMVec<u8> {
212        self.to_string().as_bytes().to_vec()
213    }
214
215    #[inline(always)]
216    fn to_buffer(&self) -> RUMBuffer {
217        string_to_buffer(self.to_string().as_str())
218    }
219}
220
221pub trait StringUtils: AsStr + RUMStringConversions {
222    #[inline(always)]
223    fn duplicate(&self, count: usize) -> RUMString {
224        let mut duplicated = RUMString::with_capacity(count);
225        for i in 0..count {
226            duplicated += &self.as_str();
227        }
228        duplicated
229    }
230
231    fn truncate(&self, count: usize) -> RUMString {
232        self.as_grapheme_str().truncate(count).to_string()
233    }
234}
235
236impl AsStr for String {
237    fn as_str(&self) -> &str {
238        self.as_str()
239    }
240}
241
242impl RUMStringConversions for RUMString {}
243impl StringUtils for RUMString {}
244
245impl RUMStringConversions for str {}
246
247impl AsStr for str {
248    fn as_str(&self) -> &str {
249        self
250    }
251}
252
253impl StringUtils for str {}
254
255impl RUMStringConversions for char {}
256
257pub trait RUMArrayConversions {
258    fn to_string(&self) -> RUMResult<RUMString>;
259}
260
261impl RUMArrayConversions for Vec<u8> {
262    #[inline(always)]
263    fn to_string(&self) -> RUMResult<RUMString> {
264        match RUMString::from_utf8(self.to_owned()) {
265            Ok(s) => Ok(s),
266            Err(e) => Err(rumtk_format!("Failure to parse incoming UTF-8 string: {}", e))
267        }
268    }
269}
270
271impl RUMArrayConversions for &[u8] {
272    #[inline(always)]
273    fn to_string(&self) -> RUMResult<RUMString> {
274        match RUMString::from_utf8(self.to_vec()) {
275            Ok(s) => Ok(s),
276            Err(e) => Err(rumtk_format!("Failure to parse incoming UTF-8 string: {}", e))
277        }
278    }
279}
280
281impl AsString for u8 {
282    fn as_string(&self) -> RUMString {
283        RUMString::from(char::from_u32((*self).into()).unwrap_or_default())
284    }
285}
286
287/**************************** Helpers ***************************************/
288
289pub fn count_tokens_ignoring_pattern(vector: &Vec<&str>, string_token: &RUMString) -> usize {
290    let mut count: usize = 0;
291    for tok in vector.iter() {
292        if string_token != tok {
293            count += 1;
294        }
295    }
296    count
297}
298
299///
300/// Implements decoding this string from its auto-detected encoding to UTF-8.
301/// Failing that we assume the string was encoded in UTF-8 and return a copy.
302///
303/// Note => Decoding is facilitated via the crates chardet-ng and encoding_rs.
304///
305pub fn string_try_decode(src: &[u8]) -> RUMResult<RUMString> {
306    let mut detector = EncodingDetector::new(Iso2022JpDetection::Allow);
307    detector.feed(&src, true);
308    let encoding = detector.guess(None, Utf8Detection::Allow);
309    decode(src, encoding)
310}
311
312///
313/// Implements decoding this string from a specific encoding to UTF-8.
314///
315/// Note => Decoding is facilitated via the crates chardet-ng and encoding_rs.
316///
317pub fn string_try_decode_with(src: &[u8], encoding_name: &str) -> RUMResult<RUMString> {
318    let encoding = match Encoding::for_label(encoding_name.as_bytes()) {
319        Some(v) => v,
320        None => return Ok(EMPTY_RUMSTRING.clone()),
321    };
322    decode(src, encoding)
323}
324
325///
326/// Implements decoding of input with encoder.
327///
328/// Note => Decoding is facilitated via the crate encoding_rs.
329///
330fn decode(src: &[u8], encoding: &'static Encoding) -> RUMResult<RUMString> {
331    Ok(match encoding.decode_without_bom_handling_and_without_replacement(&src) {
332        Some(res) => RUMString::from(res),
333        None => src.to_string()?,
334    })
335}
336
337///
338/// This function will scan through an escaped string and unescape any escaped characters.
339/// We collect these characters as a byte vector.
340/// Finally, we do a decode pass on the vector to re-encode the bytes **hopefully right** into a
341/// valid UTF-8 string.
342///
343/// This function focuses on reverting the result of [escape], whose output is meant for HL7.
344///
345pub fn unescape_string(escaped_str: &str) -> RUMResult<RUMString> {
346    let graphemes = escaped_str.graphemes(true).collect::<Vec<&str>>();
347    let str_size = graphemes.len();
348    let mut result: Vec<u8> = Vec::with_capacity(escaped_str.len());
349    let mut i = 0;
350    while i < str_size {
351        let seq_start = graphemes[i];
352        match seq_start {
353            "\\" => {
354                let escape_seq = get_grapheme_string(&graphemes, " ", i);
355                let mut c = match unescape(&escape_seq) {
356                    Ok(c) => c,
357                    Err(_why) => Vec::from(escape_seq.as_bytes()),
358                };
359                result.append(&mut c);
360                i += &escape_seq.as_grapheme_str().len();
361            }
362            _ => {
363                result.append(&mut Vec::from(seq_start.as_bytes()));
364                i += 1;
365            }
366        }
367    }
368    Ok(string_try_decode(result.as_slice())?)
369}
370
371///
372/// Get the grapheme block and concatenate it into a newly allocated [`RUMString`].
373///
374pub fn get_grapheme_string<'a>(
375    graphemes: &Vec<&'a str>,
376    end_grapheme: &str,
377    start_index: usize,
378) -> RUMString {
379    get_grapheme_collection(graphemes, end_grapheme, start_index).join("")
380}
381
382///
383/// Return vector of graphemes from starting spot up until we find the end grapheme.
384///
385/// Because a grapheme may take more than one codepoint characters, these have to be treated as
386/// references to strings.
387///
388pub fn get_grapheme_collection<'a>(
389    graphemes: &Vec<&'a str>,
390    end_grapheme: &str,
391    start_index: usize,
392) -> Vec<&'a str> {
393    let mut result: Vec<&'a str> = Vec::new();
394    for grapheme in graphemes.iter().skip(start_index) {
395        let item = *grapheme;
396        if item == end_grapheme {
397            break;
398        }
399        result.push(item);
400    }
401    result
402}
403
404///
405/// Turn escaped character sequence into the equivalent UTF-8 character
406/// This function accepts \o, \x and \u formats.
407/// This function will also attempt to unescape the common C style control characters.
408/// Anything else needs to be expressed as hex or octal patterns with the formats above.
409///
410/// If I did this right, I should get the "raw" byte sequence out of the escaped string.
411/// We can then use the bytes and attempt a decode() to figure out the string encoding and
412/// get the correct conversion to UTF-8. **Fingers crossed**
413///
414pub fn unescape(escaped_str: &str) -> Result<Vec<u8>, RUMString> {
415    let lower_case = escaped_str.to_lowercase();
416    let mut bytes: Vec<u8> = Vec::with_capacity(3);
417    match &lower_case[0..2] {
418        // Hex notation case. Assume we are getting xxyy bytes
419        "\\x" => {
420            let byte_str = number_to_char_unchecked(&hex_to_number(&lower_case[2..6])?);
421            bytes.append(&mut byte_str.as_bytes().to_vec());
422        }
423        // Unicode notation case, we need to do an extra step or we will lose key bytes.
424        "\\u" => {
425            let byte_str = number_to_char_unchecked(&hex_to_number(&lower_case[2..6])?);
426            bytes.append(&mut byte_str.as_bytes().to_vec());
427        }
428        // Single byte notation case
429        "\\c" => {
430            let byte_str = number_to_char_unchecked(&hex_to_number(&lower_case[2..6])?);
431            bytes.append(&mut byte_str.as_bytes().to_vec());
432        }
433        // Unicode notation case
434        "\\o" => {
435            let byte_str = number_to_char_unchecked(&octal_to_number(&lower_case[2..6])?);
436            bytes.append(&mut byte_str.as_bytes().to_vec());
437        }
438        // Multibyte notation case
439        "\\m" => match lower_case.as_grapheme_str().len() {
440            8 => {
441                bytes.push(hex_to_byte(&lower_case[2..4])?);
442                bytes.push(hex_to_byte(&lower_case[4..6])?);
443                bytes.push(hex_to_byte(&lower_case[6..8])?);
444            }
445            6 => {
446                bytes.push(hex_to_byte(&lower_case[2..4])?);
447                bytes.push(hex_to_byte(&lower_case[4..6])?);
448            }
449            _ => {
450                return Err(rumtk_format!(
451                    "Unknown multibyte sequence. Cannot decode {}",
452                    lower_case
453                ))
454            }
455        },
456        // Custom encoding
457        "\\z" => bytes.append(&mut lower_case.as_bytes().to_vec()),
458        // Single byte codes.
459        _ => bytes.push(unescape_control_byte(&lower_case[0..2])?),
460    }
461    Ok(bytes)
462}
463
464///
465/// Unescape basic character
466/// We use pattern matching to map the basic escape character to its corresponding integer value.
467///
468fn unescape_control(escaped_str: &str) -> Result<char, RUMString> {
469    match escaped_str {
470        // Common control sequences
471        "\\t" => Ok('\t'),
472        "\\b" => Ok('\x08'),
473        "\\n" => Ok('\n'),
474        "\\r" => Ok('\r'),
475        "\\f" => Ok('\x14'),
476        "\\s" => Ok('\x20'),
477        "\\\\" => Ok(ASCII_ESCAPE_CHAR),
478        "\\'" => Ok('\''),
479        "\\\"" => Ok('"'),
480        "\\0" => Ok('\0'),
481        "\\v" => Ok('\x0B'),
482        "\\a" => Ok('\x07'),
483        // Control sequences by
484        _ => Err(rumtk_format!(
485            "Unknown escape sequence? Sequence: {}!",
486            escaped_str
487        )),
488    }
489}
490
491///
492/// Unescape basic character
493/// We use pattern matching to map the basic escape character to its corresponding integer value.
494///
495fn unescape_control_byte(escaped_str: &str) -> Result<u8, RUMString> {
496    match escaped_str {
497        // Common control sequences
498        "\\t" => Ok(9),   // Tab/Character Tabulation
499        "\\b" => Ok(8),   // Backspace
500        "\\n" => Ok(10),  // New line/ Line Feed character
501        "\\r" => Ok(13),  // Carriage Return character
502        "\\f" => Ok(12),  // Form Feed
503        "\\s" => Ok(32),  // Space
504        "\\\\" => Ok(27), // Escape
505        "\\'" => Ok(39),  // Single quote
506        "\\\"" => Ok(34), // Double quote
507        "\\0" => Ok(0),   // Null character
508        "\\v" => Ok(11),  // Vertical Tab/Line Tabulation
509        "\\a" => Ok(7),   // Alert bell
510        // Control sequences by hex
511        //Err(rumtk_format!("Unknown escape sequence? Sequence: {}!", escaped_str))
512        _ => hex_to_byte(escaped_str),
513    }
514}
515
516///
517/// Turn hex string to number (u32)
518///
519fn hex_to_number(hex_str: &str) -> Result<u32, RUMString> {
520    match u32::from_str_radix(&hex_str, 16) {
521        Ok(result) => Ok(result),
522        Err(val) => Err(rumtk_format!(
523            "Failed to parse string with error {}! Input string {} \
524        is not hex string!",
525            val,
526            hex_str
527        )),
528    }
529}
530
531///
532/// Turn hex string to byte (u8)
533///
534fn hex_to_byte(hex_str: &str) -> Result<u8, RUMString> {
535    match u8::from_str_radix(&hex_str, 16) {
536        Ok(result) => Ok(result),
537        Err(val) => Err(rumtk_format!(
538            "Failed to parse string with error {}! Input string {} \
539        is not hex string!",
540            val,
541            hex_str
542        )),
543    }
544}
545
546///
547/// Turn octal string to number (u32)
548///
549fn octal_to_number(hoctal_str: &str) -> Result<u32, RUMString> {
550    match u32::from_str_radix(&hoctal_str, 8) {
551        Ok(result) => Ok(result),
552        Err(val) => Err(rumtk_format!(
553            "Failed to parse string with error {}! Input string {} \
554        is not an octal string!",
555            val,
556            hoctal_str
557        )),
558    }
559}
560
561///
562/// Turn octal string to byte (u32)
563///
564fn octal_to_byte(hoctal_str: &str) -> Result<u8, RUMString> {
565    match u8::from_str_radix(&hoctal_str, 8) {
566        Ok(result) => Ok(result),
567        Err(val) => Err(rumtk_format!(
568            "Failed to parse string with error {}! Input string {} \
569        is not an octal string!",
570            val,
571            hoctal_str
572        )),
573    }
574}
575
576///
577/// Turn number to UTF-8 char
578///
579fn number_to_char(num: &u32) -> Result<RUMString, RUMString> {
580    match char::from_u32(*num) {
581        Some(result) => Ok(result.to_string()),
582        None => Err(rumtk_format!(
583            "Failed to cast number to character! Number {}",
584            num
585        )),
586    }
587}
588
589///
590/// Turn number to UTF-8 char. Normally, calling from_u32 checks if the value is a valid character.
591/// This version uses the less safe from_u32_unchecked() function because we want to get the bytes
592/// and deal with validity at a higher layer.
593///
594fn number_to_char_unchecked(num: &u32) -> RUMString {
595    unsafe { char::from_u32_unchecked(*num).to_string() }
596}
597
598///
599/// Escape UTF-8 characters in UTF-8 string that are beyond ascii range
600///
601/// # Example
602/// ```
603///  use rumtk_core::strings::{string_escape, ASCII_ESCAPE_PREFIX_DEFAULT};
604///  let message = "I ❤ my wife!";
605///  let expected = "I \\x2764 my wife!";
606///  let escaped_message = string_escape(&message, ASCII_ESCAPE_PREFIX_DEFAULT);
607///  assert_eq!(expected, &escaped_message, "Did not get expected escaped string! Got {}!", &escaped_message);
608///```
609#[inline(always)]
610pub fn string_escape(unescaped_str: &str, prefix: &str) -> RUMString {
611    unescaped_str
612        .chars()
613        .map(
614            |b| {
615                if (b < ASCII_READABLE_MIN && !ASCII_ALLOWED_NONPRINT.contains(&b)) || b > ASCII_READABLE_MAX {
616                    // Allow for proper escaping of multibyte unicode characters that might need
617                    // more than 2 byte representations.
618                    let n = b as u32;
619                    let significant_bits = 32 - n.leading_zeros();
620                    let significant_bytes = (significant_bits + 7) / 8;
621
622                    match significant_bytes {
623                        3 => rumtk_format!("{}{:06X}", prefix, n),
624                        4 => rumtk_format!("{}{:08X}", prefix, n),
625                        _ => rumtk_format!("{}{:04X}", prefix, n)
626                    }
627                } else {
628                    rumtk_format!("{}", b)
629                }
630            }
631        )
632        .collect::<RUMString>()
633}
634
635
636///
637/// Checks if a given string is fully ASCII or within the ASCII range.
638///
639/// Remember: all strings are UTF-8 encoded in Rust, but most ASCII strings fit within the UTF-8
640/// encoding scheme.
641///
642pub fn is_ascii_str(unescaped_str: &str) -> bool {
643    unescaped_str.is_ascii()
644}
645
646///
647/// Checks if an input string is already escaped.
648/// The idea is to avoid escaping the escaped string thus making it a nightmare to undo the
649/// escaping later on.
650///
651/// Basically, if you were to blindly escape the input string, back slashes keep getting escaped.
652/// For example `\r -> \\r -> \\\\r -> ...`.
653///
654pub fn is_escaped_str(unescaped_str: &str) -> bool {
655    if !is_ascii_str(unescaped_str) {
656        return false;
657    }
658
659    for c in unescaped_str.chars() {
660        if !is_printable_char(c) {
661            return false;
662        }
663    }
664    true
665}
666
667///
668/// Returns whether a character is in the ASCII printable range.
669///
670pub fn is_printable_char(c: char) -> bool {
671    ASCII_READABLE_MIN <= c && c <= ASCII_READABLE_MAX
672}
673
674///
675/// Removes all non ASCII and all non printable characters from string.
676///
677pub fn filter_ascii(unescaped_str: &str, closure: fn(char) -> bool) -> RUMString {
678    let mut filtered = unescaped_str.to_string();
679    filtered.retain(closure);
680    filtered
681}
682
683///
684/// Removes all non ASCII and all non printable characters from string.
685///
686pub fn filter_non_printable_ascii(unescaped_str: &str) -> RUMString {
687    filter_ascii(unescaped_str, |c: char| is_printable_char(c))
688}
689
690///
691/// Convert buffer to string.
692///
693/// ## Example
694/// ```
695/// use rumtk_core::buffers::{buffer_to_string};
696/// use rumtk_core::strings::{string_to_buffer};
697/// use rumtk_core::buffers::*;
698///
699/// const expected: &str = "Hello World!";
700/// let expected_bufferr = RUMBuffer::from(expected.as_bytes());
701/// let result = string_to_buffer(expected);
702///
703/// assert_eq!(result, expected_bufferr, "str to RUMBuffer conversion failed!");
704/// ```
705///
706pub fn string_to_buffer(data: &str) -> RUMBuffer {
707    RUMBuffer::from(data)
708}
709
710///
711/// Given a set of keys and replacements, transform the input string.
712///
713/// ## Example
714/// ```
715/// use rumtk_core::strings::string_format;
716/// use rumtk_core::buffers::*;
717///
718/// const expected: &str = "Hello World!";
719/// const template: &str = "Hello {}!";
720/// let result = string_format(template, &[("{}", "World")]);
721///
722/// assert_eq!(result.as_str(), expected, "Formatting of string failed!");
723/// ```
724///
725pub fn string_format(input: &str, formatting: &StringReplacementPair) -> RUMString {
726    let mut output = String::from(input);
727
728    for item in formatting.iter() {
729        output = output.as_str().replace(item.0, item.1);
730    }
731
732    output.to_string()
733}
734
735///
736/// Convenience function for transforming a string into a `base64` encoded string.
737///
738/// ## Example
739/// ```
740///
741/// ```
742///
743pub fn string_to_b64(data: &str) -> String {
744    BASE64_STANDARD.encode(data)
745}
746
747///
748/// Convenience function for transforming a `base64` encoded string back to its original form.
749///
750/// ## Example
751/// ```
752/// ```
753///
754pub fn b64_to_string(data: &String) -> RUMResult<RUMVec<u8>> {
755    match BASE64_STANDARD.decode(data) {
756        Ok(result) => Ok(result),
757        Err(e) => Err(rumtk_format!("Failed to decode base64 string: {}", e)),
758    }
759}
760
761///
762/// Escape UTF-8 string to ensure it is within printable ASCII
763///
764/// # Examples
765/// ## Lower Case
766/// ```
767///  use rumtk_core::rumtk_string_escape;
768///  let message = "I ❤ my wife!";
769///  let expected = "I \\x2764 my wife!";
770///  let escaped_message = rumtk_string_escape!(&message);
771///  assert_eq!(expected, &escaped_message, "Did not get expected escaped string! Got {}!", &escaped_message);
772///```
773/// ## Upper Case
774/// ```
775///  use rumtk_core::rumtk_string_escape;
776///  use rumtk_core::strings::ASCII_ESCAPE_PREFIX_DEFAULT;
777///  let message = "I ❤ my wife!";
778///  let expected = "I \\x2764 my wife!";
779///  let escaped_message = rumtk_string_escape!(&message, ASCII_ESCAPE_PREFIX_DEFAULT);
780///  assert_eq!(expected, &escaped_message, "Did not get expected escaped string! Got {}!", &escaped_message);
781///```
782/// ## Upper Case & NON-PRINTABLE ASCII
783/// ```
784///  use rumtk_core::rumtk_string_escape;
785///  use rumtk_core::strings::ASCII_ESCAPE_PREFIX_UPPER;
786///  let message = "I ❤ my wife!\t";
787///  let expected = "I \\X2764 my wife!\\X0009";
788///  let escaped_message = rumtk_string_escape!(&message, ASCII_ESCAPE_PREFIX_UPPER);
789///  assert_eq!(expected, &escaped_message, "Did not get expected escaped string! Got {}!", &escaped_message);
790///```
791/// ## Lower Case & NON-PRINTABLE ASCII & 3-byte character
792/// ```
793///  use rumtk_core::rumtk_string_escape;
794///  use rumtk_core::strings::ASCII_ESCAPE_PREFIX_UPPER;
795///  let message = "I ❤ my wife!\t漢";
796///  let expected = "I \\X2764 my wife!\\X0009\\X6F22";
797///  let escaped_message = rumtk_string_escape!(&message, ASCII_ESCAPE_PREFIX_UPPER);
798///  assert_eq!(expected, &escaped_message, "Did not get expected escaped string! Got {}!", &escaped_message);
799///```
800///
801#[macro_export]
802macro_rules! rumtk_string_escape {
803    ( $msg:expr ) => {{
804        use $crate::strings::{string_escape, ASCII_ESCAPE_PREFIX_DEFAULT};
805
806        string_escape($msg, ASCII_ESCAPE_PREFIX_DEFAULT)
807    }};
808    ( $msg:expr, $prefix:expr ) => {{
809        use $crate::strings::string_escape;
810
811        string_escape($msg, &$prefix)
812    }};
813}