1use 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;
31const 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', '\r' ];
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
49pub 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#[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
191pub 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
287pub 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
299pub 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
312pub 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
325fn 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
337pub 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
371pub 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
382pub 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
404pub 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 "\\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 "\\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 "\\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 "\\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 "\\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 "\\z" => bytes.append(&mut lower_case.as_bytes().to_vec()),
458 _ => bytes.push(unescape_control_byte(&lower_case[0..2])?),
460 }
461 Ok(bytes)
462}
463
464fn unescape_control(escaped_str: &str) -> Result<char, RUMString> {
469 match escaped_str {
470 "\\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 _ => Err(rumtk_format!(
485 "Unknown escape sequence? Sequence: {}!",
486 escaped_str
487 )),
488 }
489}
490
491fn unescape_control_byte(escaped_str: &str) -> Result<u8, RUMString> {
496 match escaped_str {
497 "\\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),
513 }
514}
515
516fn 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
531fn 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
546fn 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
561fn 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
576fn 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
589fn number_to_char_unchecked(num: &u32) -> RUMString {
595 unsafe { char::from_u32_unchecked(*num).to_string() }
596}
597
598#[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 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
636pub fn is_ascii_str(unescaped_str: &str) -> bool {
643 unescaped_str.is_ascii()
644}
645
646pub 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
667pub fn is_printable_char(c: char) -> bool {
671 ASCII_READABLE_MIN <= c && c <= ASCII_READABLE_MAX
672}
673
674pub 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
683pub fn filter_non_printable_ascii(unescaped_str: &str) -> RUMString {
687 filter_ascii(unescaped_str, |c: char| is_printable_char(c))
688}
689
690pub fn string_to_buffer(data: &str) -> RUMBuffer {
707 RUMBuffer::from(data)
708}
709
710pub 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
735pub fn string_to_b64(data: &str) -> String {
744 BASE64_STANDARD.encode(data)
745}
746
747pub 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#[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}