about summary refs log tree commit diff
path: root/splorm/src/query.rs
blob: ddc66dde8e32616235149fee106a493ef90bfa98 (plain)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! A custom query parser.
//!
//! Parses query strings, such as `key=value&booleanKey`

#![allow(dead_code)]
use std::{str::FromStr, vec::IntoIter};

/// querys string parser
#[derive(Debug)]
pub struct Query {
	parameters: Vec<Parameter>,
}

impl Query {
	/// Returns true if the query has a parameter with the given key, whether it's a bool or key-value pair.
	///
	/// # Examples
	///
	///```rust
	///use mavourings::query::Query;
	///let query: Query = "key=value&boolean".parse().unwrap();
	///
	///assert!(query.has("key"));
	///assert!(query.has("boolean"));
	///assert!(!query.has("notakey"));
	///```
	pub fn has<S: AsRef<str>>(&self, key: S) -> bool {
		for param in &self.parameters {
			match param {
				Parameter::Value(param_key, _) if param_key == key.as_ref() => return true,
				Parameter::Bool(param_key) if param_key == key.as_ref() => return true,
				_ => continue,
			}
		}

		false
	}

	/// Returns true if the query has a key-value pair with the given key.
	///
	/// # Examples
	///
	///```rust
	/// use mavourings::query::Query;
	///
	/// let query: Query = "key=value&boolean".parse().unwrap();
	///
	/// assert!(query.has_value("key"));
	/// assert!(!query.has_value("boolean"));
	///```
	pub fn has_value<S: AsRef<str>>(&self, key: S) -> bool {
		for param in &self.parameters {
			match param {
				Parameter::Value(param_key, _) if param_key == key.as_ref() => return true,

				_ => continue,
			}
		}

		false
	}

	/// Returns true if the query has a bool with the given name.
	///
	/// # Examples
	///
	///```rust
	/// use mavourings::query::Query;
	///
	/// let query: Query = "key=value&boolean".parse().unwrap();
	///
	/// assert!(query.has_bool("boolean"));
	/// assert!(!query.has_bool("key"));
	///```
	pub fn has_bool<S: AsRef<str>>(&self, name: S) -> bool {
		for param in &self.parameters {
			match param {
				Parameter::Bool(param_key) if param_key == name.as_ref() => return true,
				_ => continue,
			}
		}

		false
	}

	/// Returns the first value from a key-value pair if one is found. If none
	/// is found, None is returned.
	///
	/// # Examples
	///
	///```rust
	/// use mavourings::query::Query;
	///
	/// let query: Query = "key=value&boolean".parse().unwrap();
	///
	/// assert_eq!(query.get_first_value("key"), Some("value"));
	/// assert_eq!(query.get_first_value("boolean"), None);
	///```
	pub fn get_first_value<S: AsRef<str>>(&self, search: S) -> Option<&str> {
		for param in &self.parameters {
			match param {
				Parameter::Value(key, value) if key == search.as_ref() => return Some(value),
				_ => continue,
			}
		}

		None
	}

	/// Parses the first value from a key-value pair, if one is found, and returns
	/// the result, or None if it can't be found.
	///
	/// # Example
	///
	/// ```rust
	/// use mavourings::query::Query;
	///
	/// let query: Query = "id=256".parse().unwrap();
	///
	/// assert_eq!(query.parse_first_value("id"), Some(Ok(256)))
	/// ```
	pub fn parse_first_value<S: AsRef<str>, T: FromStr>(
		&self,
		search: S,
	) -> Option<Result<T, <T as FromStr>::Err>> {
		self.get_first_value(search).map(|v| v.parse())
	}

	/// Processes a string, converting any percent encoded characteres into
	/// their proper representations.
	///
	/// If the second parameter is true, this function will also turn any '+'
	/// into spaces as most browsers replace spaces with plus. This will not be
	/// done if the plus is percent encoded (%2B)
	///
	/// # Returns
	///
	/// The decoded String on success or a QueryParseError if the decode resulted
	/// in invalid UTF8
	///
	/// # Examples
	///
	///```rust
	///use mavourings::query::{Query, QueryParseError};
	///
	///assert_eq!(Query::url_decode("a+space+two%20ways%21", true), Ok(String::from("a space two ways!")));
	///assert_eq!(Query::url_decode("invalid%1Z", true), Ok(String::from("invalid%1Z")));
	///assert_eq!(Query::url_decode("a%20plus+sign", false), Ok(String::from("a plus+sign")));
	///```
	pub fn url_decode<S: AsRef<str>>(
		urlencoded: S,
		plus_as_space: bool,
	) -> Result<String, QueryParseError> {
		let mut uncoded: Vec<u8> = vec![];

		let mut chars = urlencoded.as_ref().chars().peekable();
		loop {
			match chars.next() {
				Some('+') => match plus_as_space {
					true => uncoded.push(b' '),
					false => uncoded.push(b'+'),
				},
				Some('%') => match chars.peek() {
					Some(c) if c.is_ascii_hexdigit() => {
						let upper = chars.next().unwrap();

						if let Some(lower) = chars.peek() {
							if lower.is_ascii_hexdigit() {
								let upper = upper.to_digit(16).unwrap();
								let lower = chars.next().unwrap().to_digit(16).unwrap();

								uncoded.push(upper as u8 * 16 + lower as u8);
								continue;
							}
						}

						uncoded.push(b'%');
						uncoded.extend_from_slice(&Self::char_bytes(upper));
					}
					_ => {
						uncoded.push(b'%');
					}
				},
				Some(c) => {
					uncoded.extend_from_slice(&Self::char_bytes(c));
				}
				None => {
					return Ok(
						String::from_utf8(uncoded).map_err(|_| QueryParseError::InvalidUtf8)?
					);
				}
			}
		}
	}

	/// Process a string, encoding the reserved URL characters below into their
	/// percent equivalent. Any character outside of the ASCII printables are
	/// also percent encoded.
	///
	/// The following characters are reserved and will be encoded as %xx where
	/// x is a lowercase hex digit:
	/// `! # $ % ' ( ) * + , / : ; = ? @ [ ]`
	///
	/// # Returns
	///
	/// The decoded String on success or a QueryParseError if the decode resulted
	/// in invalid UTF8
	///
	/// # Examples
	///
	///```rust
	///use mavourings::query::{Query, QueryParseError};
	///
	///assert_eq!(Query::url_encode("encode me spaces!"), String::from("encode%20me%20spaces%21"));
	///assert_eq!(Query::url_encode("🥺"), String::from("%f0%9f%a5%ba"));
	///assert_eq!(Query::url_encode("one+two"), String::from("one%2btwo"));
	///```
	pub fn url_encode<S: AsRef<str>>(raw: S) -> String {
		let mut encoded = String::new();
		let mut chars = raw.as_ref().chars().peekable();
		let should_encode = |c: char| !c.is_ascii_graphic() || "!#$%'()*+,/:;=?@[]".contains(c);

		loop {
			match chars.next() {
				Some(c) if should_encode(c) => {
					let bytes = Self::char_bytes(c);
					for byte in bytes {
						encoded.push_str(&format!("%{:02x}", byte));
					}
				}
				Some(c) => {
					encoded.push(c);
				}
				None => return encoded,
			}
		}
	}

	fn char_bytes(c: char) -> Vec<u8> {
		let mut utf8 = vec![0; c.len_utf8()];
		c.encode_utf8(&mut utf8);
		utf8
	}
}

impl std::str::FromStr for Query {
	type Err = QueryParseError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let mut parameters: Vec<Parameter> = vec![];
		let splits = s.split('&');

		for split in splits {
			let splits: Vec<&str> = split.splitn(2, '=').collect();

			match splits.len() {
				1 => parameters.push(Parameter::Bool(splits[0].into())),
				2 => parameters.push(Parameter::Value(
					splits[0].into(),
					Self::url_decode(splits[1], true)?,
				)),
				_ => unreachable!(),
			}
		}

		Ok(Self { parameters })
	}
}

impl IntoIterator for Query {
	type Item = Parameter;

	type IntoIter = IntoIter<Parameter>;

	fn into_iter(self) -> Self::IntoIter {
		self.parameters.into_iter()
	}
}

#[derive(Debug)]
pub enum Parameter {
	Bool(String),
	Value(String, String),
}

#[derive(Debug, PartialEq)]
pub enum QueryParseError {
	InvalidUtf8,
}

impl std::fmt::Display for QueryParseError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::InvalidUtf8 => {
				write!(f, "Query did not parse as valid utf8")
			}
		}
	}
}