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