1pub 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;
31const 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
42pub 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#[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
186pub 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
282pub 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
294pub 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
307pub 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
320fn 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
332pub 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
366pub 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
377pub 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
399pub 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 "\\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 "\\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 "\\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 "\\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 "\\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 "\\z" => bytes.append(&mut lower_case.as_bytes().to_vec()),
453 _ => bytes.push(unescape_control_byte(&lower_case[0..2])?),
455 }
456 Ok(bytes)
457}
458
459fn unescape_control(escaped_str: &str) -> Result<char, RUMString> {
464 match escaped_str {
465 "\\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 _ => Err(rumtk_format!(
480 "Unknown escape sequence? Sequence: {}!",
481 escaped_str
482 )),
483 }
484}
485
486fn unescape_control_byte(escaped_str: &str) -> Result<u8, RUMString> {
491 match escaped_str {
492 "\\t" => Ok(9), "\\b" => Ok(8), "\\n" => Ok(10), "\\r" => Ok(13), "\\f" => Ok(12), "\\s" => Ok(32), "\\\\" => Ok(27), "\\'" => Ok(39), "\\\"" => Ok(34), "\\0" => Ok(0), "\\v" => Ok(11), "\\a" => Ok(7), _ => hex_to_byte(escaped_str),
508 }
509}
510
511fn 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
526fn 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
541fn 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
556fn 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
571fn 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
584fn number_to_char_unchecked(num: &u32) -> RUMString {
590 unsafe { char::from_u32_unchecked(*num).to_string() }
591}
592
593pub fn escape(unescaped_str: &str) -> RUMString {
605 basic_escape(unescaped_str, Some(&vec![("{", ""), ("}", "")]))
606}
607
608pub 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
637pub fn is_ascii_str(unescaped_str: &str) -> bool {
644 unescaped_str.is_ascii()
645}
646
647pub 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
668pub fn is_printable_char(c: &char) -> bool {
672 &MIN_ASCII_READABLE <= c && c <= &MAX_ASCII_READABLE
673}
674
675pub 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
684pub fn filter_non_printable_ascii(unescaped_str: &str) -> RUMString {
688 filter_ascii(unescaped_str, |c: char| is_printable_char(&c))
689}
690
691pub fn string_to_buffer(data: &str) -> RUMBuffer {
708 RUMBuffer::from(data)
709}
710
711pub 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
736pub fn string_to_b64(data: &str) -> String {
745 BASE64_STANDARD.encode(data)
746}
747
748pub 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}