This repository has been archived by the owner on Jan 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathstring_helpers.rs
96 lines (91 loc) · 2.78 KB
/
string_helpers.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Default)]
pub struct StringCategory {
pub is_byte: bool,
pub is_raw: bool,
pub is_format: bool,
pub is_unicode: bool,
}
#[derive(Debug)]
#[derive(PartialEq)]
pub struct InvalidStringCategoryError {
pub invalid_prefix: String,
}
/// Return a string containing all characters prior to the first ' or "
pub fn string_prefix(string_contents: &str) -> String {
let mut prefix: String = String::from("");
for ch in string_contents.chars() {
if ch == '\'' || ch == '"' {
break;
}
prefix.push(ch);
}
prefix
}
/// categorize_string will return a StringCategory
/// containing the type of string which has been passed to the function
/// i.e. a byte, format, unicode or raw string as signified by the prefix
/// of the string, e.g. `b"a byte string"` is a byte string etc.
/// If an invalid combination of prefix is provided then this is returned
/// as a InvalidStringCategoryError for processing by the caller
pub fn categorize_string(
to_categorize: &str,
) -> Result<StringCategory, InvalidStringCategoryError> {
// Only valid prefixes are:
// "r" | "u" | "f" | "b"
// "fr" | "rf"
// "br"| "rb"
let mut prefix = string_prefix(to_categorize);
prefix = prefix.to_lowercase();
match prefix.len() {
1 => match prefix.as_str() {
"r" => Ok(StringCategory {
is_raw: true,
..Default::default()
}),
"u" => Ok(StringCategory {
is_unicode: true,
..Default::default()
}),
"f" => Ok(StringCategory {
is_format: true,
..Default::default()
}),
"b" => Ok(StringCategory {
is_byte: true,
..Default::default()
}),
_ => Err(InvalidStringCategoryError {
invalid_prefix: prefix,
}),
},
2 => match prefix.as_str() {
"fr" | "rf" => Ok(StringCategory {
is_format: true,
is_raw: true,
..Default::default()
}),
"br" | "rb" => Ok(StringCategory {
is_byte: true,
is_raw: true,
..Default::default()
}),
_ => Err(InvalidStringCategoryError {
invalid_prefix: prefix,
}),
},
0 => Ok(StringCategory {
..Default::default()
}),
_ => Err(InvalidStringCategoryError {
invalid_prefix: prefix,
}),
}
}