suika_utils/
lib.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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use std::{
    collections::HashMap,
    str::Chars,
    task::{RawWaker, RawWakerVTable, Waker},
};

/// Parses a query string into a HashMap.
///
/// # Arguments
///
/// * `query` - A string slice that holds the query string.
///
/// # Returns
///
/// A HashMap containing the key-value pairs from the query string.
///
/// # Examples
///
/// ```
/// use suika_utils::parse_query_string;
/// let query = "name=John&age=30";
/// let params = parse_query_string(query);
/// assert_eq!(params.get("name"), Some(&"John".to_string()));
/// assert_eq!(params.get("age"), Some(&"30".to_string()));
/// ```
pub fn parse_query_string(query: &str) -> HashMap<String, String> {
    query
        .split('&')
        .filter_map(|pair| {
            let mut iter = pair.split('=');
            if let (Some(key), Some(value)) = (iter.next(), iter.next()) {
                Some((key.to_string(), value.to_string()))
            } else {
                None
            }
        })
        .collect()
}

/// Skips whitespace characters in the input.
///
/// # Arguments
///
/// * `chars` - A mutable reference to an iterator over characters.
/// * `current_char` - A mutable reference to an Option containing the current character.
///
/// # Examples
///
/// ```
/// use suika_utils::skip_whitespace;
/// let input = "   abc";
/// let mut chars = input.chars();
/// let mut current_char = chars.next();
/// skip_whitespace(&mut chars, &mut current_char);
/// assert_eq!(current_char, Some('a'));
/// ```
pub fn skip_whitespace(chars: &mut Chars, current_char: &mut Option<char>) {
    while let Some(c) = *current_char {
        if c.is_whitespace() {
            *current_char = chars.next();
        } else {
            break;
        }
    }
}

/// Expects a specific sequence of characters in the input.
///
/// # Arguments
///
/// * `chars` - A mutable reference to an iterator over characters.
/// * `current_char` - A mutable reference to an Option containing the current character.
/// * `expected` - The expected sequence of characters.
///
/// # Returns
///
/// An empty Result if the sequence matches, or an Err with a descriptive message otherwise.
///
/// # Examples
///
/// ```
/// use suika_utils::expect_sequence;
/// let input = "true";
/// let mut chars = input.chars();
/// let mut current_char = chars.next();
/// assert!(expect_sequence(&mut chars, &mut current_char, "true").is_ok());
/// assert_eq!(current_char, None);
///
/// let input = "tru";
/// let mut chars = input.chars();
/// let mut current_char = chars.next();
/// assert!(expect_sequence(&mut chars, &mut current_char, "true").is_err());
/// ```
pub fn expect_sequence(
    chars: &mut Chars,
    current_char: &mut Option<char>,
    expected: &str,
) -> Result<(), String> {
    for expected_char in expected.chars() {
        if Some(expected_char) != *current_char {
            return Err(format!(
                "Expected '{}', found '{:?}'",
                expected_char, current_char
            ));
        }
        *current_char = chars.next();
    }
    Ok(())
}

/// Builds a URL from a base and a set of query parameters.
///
/// # Arguments
///
/// * `base` - A string slice that holds the base URL.
/// * `params` - A reference to a HashMap containing the query parameters.
///
/// # Returns
///
/// A String containing the full URL with query parameters.
///
/// # Examples
///
/// ```
/// use suika_utils::build_url;
/// let base = "https://example.com";
/// let mut params = std::collections::HashMap::new();
/// params.insert("name", "John");
/// params.insert("age", "30");
/// let url = build_url(base, &params);
/// assert_eq!(url, "https://example.com?age=30&name=John");
/// ```
pub fn build_url(base: &str, params: &HashMap<&str, &str>) -> String {
    let mut url = base.to_string();
    if !params.is_empty() {
        url.push('?');
        let mut query_params: Vec<_> = params.iter().collect();
        query_params.sort_by_key(|&(key, _)| key);
        let query_string: String = query_params
            .iter()
            .map(|&(key, value)| format!("{}={}", key, value))
            .collect::<Vec<String>>()
            .join("&");
        url.push_str(&query_string);
    }
    url
}

/// Parses a URL into its components: scheme, host, path, and query parameters.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL.
///
/// # Returns
///
/// An Option containing a tuple with the scheme, host, path, and a HashMap of query parameters.
///
/// # Examples
///
/// ```
/// use suika_utils::parse_url;
/// let url = "https://example.com/path?name=John&age=30";
/// let components = parse_url(url).unwrap();
/// assert_eq!(components.0, "https");
/// assert_eq!(components.1, "example.com");
/// assert_eq!(components.2, "/path");
/// assert_eq!(components.3.get("name"), Some(&"John".to_string()));
/// assert_eq!(components.3.get("age"), Some(&"30".to_string()));
/// ```
pub fn parse_url(url: &str) -> Option<(String, String, String, HashMap<String, String>)> {
    let mut url_parts = url.splitn(2, "://");
    let scheme = url_parts.next()?.to_string();
    let rest = url_parts.next()?;

    let mut rest_parts = rest.splitn(2, '/');
    let host_and_query = rest_parts.next()?.to_string();
    let path_and_query = rest_parts.next().unwrap_or("").to_string();

    let (host, path, query) = match host_and_query.find('?') {
        Some(query_start) => {
            let host = &host_and_query[..query_start];
            let query_string = &host_and_query[query_start + 1..];
            (
                host.to_string(),
                "/".to_string(),
                parse_query_string(query_string),
            )
        }
        None => match path_and_query.find('?') {
            Some(query_start) => {
                let path = &path_and_query[..query_start];
                let query_string = &path_and_query[query_start + 1..];
                (
                    host_and_query,
                    format!("/{}", path),
                    parse_query_string(query_string),
                )
            }
            None => (
                host_and_query,
                if path_and_query.is_empty() {
                    "/".to_string()
                } else {
                    format!("/{}", path_and_query)
                },
                HashMap::new(),
            ),
        },
    };

    Some((scheme, host, path, query))
}

/// Creates a no-op Waker for use in tests.
///
/// # Returns
///
/// A Waker that does nothing when notified.
///
/// # Examples
///
/// ```
/// use suika_utils::noop_waker;
/// use std::task::{Context, Poll};
/// use std::future::Future;
/// use std::pin::Pin;
/// use std::sync::{
///     atomic::{AtomicBool, Ordering},
///     Arc,
/// };
///
/// let waker = noop_waker();
/// let mut cx = Context::from_waker(&waker);
///
/// let ready = Arc::new(AtomicBool::new(false));
/// let ready_clone = Arc::clone(&ready);
///
/// let mut future = Box::pin(async move {
///     ready_clone.store(true, Ordering::SeqCst);
/// });
///
/// assert!(!ready.load(Ordering::SeqCst));
/// let _ = future.as_mut().poll(&mut cx);
/// assert!(ready.load(Ordering::SeqCst));
/// ```
pub fn noop_waker() -> Waker {
    fn noop(_: *const ()) {}
    fn clone(_: *const ()) -> RawWaker {
        RawWaker::new(std::ptr::null(), &VTABLE)
    }
    static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
    unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::future::Future;
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };
    use std::task::Context;

    #[test]
    fn test_parse_query_string() {
        let query = "name=John&age=30";
        let params = parse_query_string(query);
        assert_eq!(params.get("name"), Some(&"John".to_string()));
        assert_eq!(params.get("age"), Some(&"30".to_string()));
    }

    #[test]
    fn test_skip_whitespace() {
        let input = "   abc";
        let mut chars = input.chars();
        let mut current_char = chars.next();
        skip_whitespace(&mut chars, &mut current_char);
        assert_eq!(current_char, Some('a'));
    }

    #[test]
    fn test_expect_sequence() {
        let input = "true";
        let mut chars = input.chars();
        let mut current_char = chars.next();
        assert!(expect_sequence(&mut chars, &mut current_char, "true").is_ok());
        assert_eq!(current_char, None);

        let input = "false";
        let mut chars = input.chars();
        let mut current_char = chars.next();
        assert!(expect_sequence(&mut chars, &mut current_char, "false").is_ok());
        assert_eq!(current_char, None);

        let input = "tru";
        let mut chars = input.chars();
        let mut current_char = chars.next();
        assert!(expect_sequence(&mut chars, &mut current_char, "true").is_err());
    }

    #[test]
    fn test_build_url() {
        let base = "https://example.com";
        let mut params = HashMap::new();
        params.insert("name", "John");
        params.insert("age", "30");
        let url = build_url(base, &params);
        assert_eq!(url, "https://example.com?age=30&name=John");
    }

    #[test]
    fn test_parse_url() {
        let url = "https://example.com/path?name=John&age=30";
        let components = parse_url(url).unwrap();
        assert_eq!(components.0, "https");
        assert_eq!(components.1, "example.com");
        assert_eq!(components.2, "/path");
        assert_eq!(components.3.get("name"), Some(&"John".to_string()));
        assert_eq!(components.3.get("age"), Some(&"30".to_string()));
    }

    #[test]
    fn test_parse_url_no_path() {
        let url = "https://example.com?name=John&age=30";
        let components = parse_url(url).unwrap();
        assert_eq!(components.0, "https");
        assert_eq!(components.1, "example.com");
        assert_eq!(components.2, "/");
        assert_eq!(components.3.get("name"), Some(&"John".to_string()));
        assert_eq!(components.3.get("age"), Some(&"30".to_string()));
    }

    #[test]
    fn test_noop_waker() {
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);

        let ready = Arc::new(AtomicBool::new(false));
        let ready_clone = Arc::clone(&ready);

        let mut future = Box::pin(async move {
            ready_clone.store(true, Ordering::SeqCst);
        });

        assert!(!ready.load(Ordering::SeqCst));
        let _ = future.as_mut().poll(&mut cx);
        assert!(ready.load(Ordering::SeqCst));
    }
}