urlquerystring 0.1.1

A high-performance, zero-allocation URL query string parser.
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/// A high-performance, zero-allocation URL query string parser.
///
/// This crate provides a stack-based implementation for parsing URL query strings
/// without any heap allocations. It's designed for performance-critical environments
/// where memory allocation overhead needs to be minimized.
///
/// # Features
///
/// - Zero heap allocations
/// - High performance through direct byte manipulation
/// - UTF-8 safe parameter handling
/// - Built-in percent-decoding support
/// - Const-generic based size configuration
/// - Zero-cost abstractions where possible
///
/// # Examples
///
/// ```rust
/// use urlquerystring::StackQueryParams;
///
/// let url = "https://example.com/path?name=John&age=25&city=New%20York";
/// let params = StackQueryParams::new(url);
///
/// assert_eq!(params.get("name"), Some("John"));
/// assert_eq!(params.get("city"), Some("New York")); // Automatically percent-decoded
/// ```

/// Default maximum number of query parameters that can be stored.
pub const MAX_PARAM_COUNT: usize = 16;

/// Default maximum length for parameter keys in bytes.
pub const MAX_KEY_SIZE: usize = 32;

/// Default maximum length for parameter values in bytes.
pub const MAX_VALUE_SIZE: usize = 128;

/// A stack-based parameter type with fixed-size storage for key and value.
///
/// This struct provides a container for a single query parameter with fixed-size
/// buffers for both the key and value. The sizes are determined by the const
/// generic parameters `KEY_SIZE` and `VALUE_SIZE`.
///
/// # Examples
///
/// ```rust
/// use urlquerystring::StackParam;
///
/// let param = StackParam::<32, 128>::new();
/// ```
#[derive(Debug, Clone, Copy)]
pub struct StackParam<const KEY_SIZE: usize, const VALUE_SIZE: usize> {
    key: StackString<KEY_SIZE>,
    value: StackString<VALUE_SIZE>,
}

impl<const KEY_SIZE: usize, const VALUE_SIZE: usize> StackParam<KEY_SIZE, VALUE_SIZE> {
    /// Creates a new empty parameter with zero-initialized buffers.
    ///
    /// This operation is zero-cost and performs no heap allocations.
    pub fn new() -> Self {
        StackParam {
            key: StackString::new(),
            value: StackString::new(),
        }
    }

    /// Returns the key as a string slice.
    ///
    /// This is a zero-cost operation that returns a view into the internal buffer.
    pub fn key(&self) -> &str {
        self.key.as_str()
    }

    /// Returns the value as a string slice.
    ///
    /// This is a zero-cost operation that returns a view into the internal buffer.
    pub fn value(&self) -> &str {
        self.value.as_str()
    }
}

/// A stack-based query parameters container with fixed-size storage.
///
/// This struct provides a container for URL query parameters with fixed-size
/// storage for both the number of parameters and their individual key/value sizes.
/// All memory is allocated on the stack, making it suitable for performance-critical
/// environments.
///
/// The size limits are determined by the const generic parameters:
/// - `PARAM_COUNT`: Maximum number of parameters that can be stored
/// - `KEY_SIZE`: Maximum length for parameter keys in bytes
/// - `VALUE_SIZE`: Maximum length for parameter values in bytes
///
/// # Examples
///
/// ```rust
/// use urlquerystring::StackQueryParams;
///
/// // Using default size limits
/// let params = StackQueryParams::new("https://example.com/path?name=John");
///
/// // Using custom size limits
/// let params = StackQueryParams::<32, 64, 256>::custom_new("https://example.com/path?param=value");
/// ```
#[derive(Debug)]
pub struct StackQueryParams<
    const PARAM_COUNT: usize,
    const KEY_SIZE: usize,
    const VALUE_SIZE: usize,
> {
    params: [StackParam<KEY_SIZE, VALUE_SIZE>; PARAM_COUNT],
    count: usize,
}


impl<const PARAM_COUNT: usize, const KEY_SIZE: usize, const VALUE_SIZE: usize>
    StackQueryParams<PARAM_COUNT, KEY_SIZE, VALUE_SIZE>
{
    /// Creates a new query parameters container with custom size limits.
    ///
    /// This constructor allows you to specify custom size limits for the number of
    /// parameters, key length, and value length. It immediately parses the provided
    /// URL string.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL string to parse query parameters from
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let params = StackQueryParams::<32, 64, 256>::custom_new(
    ///     "https://example.com/path?param=value"
    /// );
    /// ```
    pub fn custom_new(url: &str) -> Self {
        let mut stack_query_params = StackQueryParams {
            params: [StackParam::<KEY_SIZE, VALUE_SIZE>::new(); PARAM_COUNT],
            count: 0,
        };
        stack_query_params.parse_from_url(url);
        stack_query_params
    }
}

impl StackQueryParams<MAX_PARAM_COUNT, MAX_KEY_SIZE, MAX_VALUE_SIZE> {
    /// Creates a new query parameters container with default size limits.
    ///
    /// This constructor uses the default size limits defined by the constants:
    /// - `MAX_PARAM_COUNT`: 16 parameters
    /// - `MAX_KEY_SIZE`: 32 bytes
    /// - `MAX_VALUE_SIZE`: 128 bytes
    ///
    /// It immediately parses the provided URL string.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL string to parse query parameters from
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let params = StackQueryParams::new("https://example.com/path?name=John");
    /// ```
    pub fn new(url: &str) -> Self {
        let mut stack_query_params = StackQueryParams {
            params: [StackParam::<MAX_KEY_SIZE, MAX_VALUE_SIZE>::new(); MAX_PARAM_COUNT],
            count: 0,
        };
        stack_query_params.parse_from_url(url);
        stack_query_params
    }
}

impl<const PARAM_COUNT: usize, const KEY_SIZE: usize, const VALUE_SIZE: usize>
    StackQueryParams<PARAM_COUNT, KEY_SIZE, VALUE_SIZE>
{
    /// Parses a URL query string with automatic percent-decoding.
    ///
    /// This method efficiently parses the query string portion of a URL,
    /// automatically handling percent-encoded characters and plus signs.
    /// It performs no heap allocations and uses only stack-based memory.
    ///
    /// The method will:
    /// - Skip any URL portion before the '?' character
    /// - Parse key-value pairs separated by '&'
    /// - Handle empty values (e.g., "key=")
    /// - Automatically percent-decode both keys and values
    /// - Stop parsing if the parameter count limit is reached
    ///
    /// # Arguments
    ///
    /// * `url` - The URL string to parse query parameters from
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let mut params = StackQueryParams::new("https://example.com/path");
    /// params.parse_from_url("https://example.com/path?name=John&age=25");
    /// ```
    fn parse_from_url(&mut self, url: &str) {
        // Find where the query string starts (after '?')
        let query = match url.find('?') {
            Some(pos) => &url[pos + 1..],
            None => return, // No query parameters
        };

        // Track our position in the query string
        let mut start = 0;
        let bytes = query.as_bytes();

        while start < bytes.len() && self.count < PARAM_COUNT {
            // Find the end of this parameter (& or end of string)
            let mut end = start;
            while end < bytes.len() && bytes[end] != b'&' {
                end += 1;
            }

            // Process this parameter
            let pair = &query[start..end];

            // Find the equals sign
            let param = &mut self.params[self.count];
            if let Some(eq_pos) = pair.find('=') {
                let key_str = &pair[0..eq_pos];
                let value_str = &pair[eq_pos + 1..];

                if !key_str.is_empty() {
                    // Decode key and value
                    let key_decoded = percent_decode::<KEY_SIZE>(key_str);
                    let value_decoded = percent_decode::<VALUE_SIZE>(value_str);

                    // Store in our parameter
                    param.key = key_decoded;
                    param.value = value_decoded;
                    self.count += 1;
                }
            } else if !pair.is_empty() {
                // Key with no value
                let key_decoded = percent_decode::<KEY_SIZE>(pair);
                param.key = key_decoded;
                self.count += 1;
            }

            // Move to the next parameter
            start = end + 1;
        }
    }

    /// Returns the value associated with the given key.
    ///
    /// This is a zero-cost operation that returns a view into the internal buffer.
    /// The search is case-sensitive.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up
    ///
    /// # Returns
    ///
    /// * `Option<&str>` - The value if found, None otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let params = StackQueryParams::new("https://example.com/path?name=John");
    ///
    /// assert_eq!(params.get("name"), Some("John"));
    /// assert_eq!(params.get("missing"), None);
    /// ```
    pub fn get(&self, key: &str) -> Option<&str> {
        for i in 0..self.count {
            if self.params[i].key() == key {
                return Some(self.params[i].value());
            }
        }
        None
    }

    /// Returns the number of parameters currently stored.
    ///
    /// This is a zero-cost operation that returns the current count.
    /// The count will never exceed the `PARAM_COUNT` limit.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let params = StackQueryParams::new("https://example.com/path?name=John&age=25");
    /// assert_eq!(params.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.count
    }

    /// Returns true if no parameters are stored.
    ///
    /// This is a zero-cost operation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let params = StackQueryParams::new("https://example.com/path");
    /// assert!(params.is_empty());
    ///
    /// let params = StackQueryParams::new("https://example.com/path?name=John");
    /// assert!(!params.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Returns an iterator over all key-value pairs.
    ///
    /// The iterator yields tuples of `(&str, &str)` representing the key and value
    /// of each parameter. This is a zero-cost operation that returns views into
    /// the internal buffers.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackQueryParams;
    ///
    /// let params = StackQueryParams::new("https://example.com/path?name=John&age=25");
    /// let pairs: Vec<_> = params.iter().collect();
    ///
    /// assert_eq!(pairs.len(), 2);
    /// assert!(pairs.contains(&("name", "John")));
    /// assert!(pairs.contains(&("age", "25")));
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
        (0..self.count).map(move |i| (self.params[i].key(), self.params[i].value()))
    }
}

/// A stack-based string type with fixed-size storage.
///
/// This struct provides a string-like interface using a fixed-size buffer
/// to avoid heap allocations. The size of the buffer is determined by the
/// const generic parameter `SIZE`.
///
/// # Safety
///
/// This type ensures that only valid UTF-8 is stored and provides safe
/// access to the underlying bytes.
///
/// # Examples
///
/// ```rust
/// use urlquerystring::StackString;
///
/// let mut s = StackString::<32>::new();
/// s.push('H');
/// s.push('e');
/// s.push('l');
/// s.push('l');
/// s.push('o');
///
/// assert_eq!(s.as_str(), "Hello");
/// ```
#[derive(Debug, Clone, Copy)]
pub struct StackString<const SIZE: usize> {
    buf: [u8; SIZE],
    len: usize,
}

impl<const SIZE: usize> StackString<SIZE> {
    /// Creates a new empty stack string.
    ///
    /// This operation is zero-cost and performs no heap allocations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackString;
    ///
    /// let s = StackString::<32>::new();
    /// assert!(s.is_empty());
    /// ```
    pub fn new() -> Self {
        StackString {
            buf: [0; SIZE],
            len: 0,
        }
    }

    /// Pushes a character to the string if there's room.
    ///
    /// This method safely handles UTF-8 encoding and ensures the buffer
    /// doesn't overflow. It performs no heap allocations.
    ///
    /// # Arguments
    ///
    /// * `c` - The character to append
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackString;
    ///
    /// let mut s = StackString::<32>::new();
    /// s.push('H');
    /// s.push('e');
    /// s.push('l');
    /// s.push('l');
    /// s.push('o');
    ///
    /// assert_eq!(s.as_str(), "Hello");
    /// ```
    pub fn push(&mut self, c: char) {
        let mut buf = [0u8; 4]; // UTF-8 chars can be up to 4 bytes
        let char_bytes = c.encode_utf8(&mut buf).as_bytes();

        // Check if we have enough space left
        if self.len + char_bytes.len() <= SIZE {
            self.buf[self.len..self.len + char_bytes.len()].copy_from_slice(char_bytes);
            self.len += char_bytes.len();
        }
    }

    /// Returns the current length in bytes.
    ///
    /// This is a zero-cost operation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackString;
    ///
    /// let mut s = StackString::<32>::new();
    /// s.push('H');
    /// s.push('e');
    /// s.push('l');
    /// s.push('l');
    /// s.push('o');
    ///
    /// assert_eq!(s.len(), 5);
    /// ```
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the string is empty.
    ///
    /// This is a zero-cost operation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackString;
    ///
    /// let mut s = StackString::<32>::new();
    /// assert!(s.is_empty());
    ///
    /// s.push('H');
    /// assert!(!s.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the string as a string slice.
    ///
    /// This is a zero-cost operation that returns a view into the internal buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use urlquerystring::StackString;
    ///
    /// let mut s = StackString::<32>::new();
    /// s.push('H');
    /// s.push('e');
    /// s.push('l');
    /// s.push('l');
    /// s.push('o');
    ///
    /// assert_eq!(s.as_str(), "Hello");
    /// ```
    pub fn as_str(&self) -> &str {
        // This is safe because we only insert valid UTF-8 characters
        std::str::from_utf8(&self.buf[0..self.len]).unwrap_or("")
    }
}

impl<const SIZE: usize> AsRef<str> for StackString<SIZE> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

/// Decodes percent-encoded URL components.
///
/// This function efficiently decodes percent-encoded characters in URLs
fn percent_decode<const OUTPUT_SIZE: usize>(input: &str) -> StackString<OUTPUT_SIZE> {
    let mut result = StackString::<OUTPUT_SIZE>::new();
    let mut i = 0;
    let bytes = input.as_bytes();

    while i < bytes.len() && result.len() < OUTPUT_SIZE {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            // Try to decode the hex value
            if let (Some(hi), Some(lo)) = (hex_value(bytes[i + 1]), hex_value(bytes[i + 2])) {
                result.push((hi << 4 | lo) as char);
                i += 3;
            } else {
                result.push('%');
                i += 1;
            }
        } else if bytes[i] == b'+' {
            result.push(' ');
            i += 1;
        } else {
            result.push(bytes[i] as char);
            i += 1;
        }
    }

    result
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_parsing() {
        let url = "https://example.com/path?name=John&age=25&city=New%20York";

        let params = StackQueryParams::new(url);

        assert_eq!(params.len(), 3);
        assert_eq!(params.get("name"), Some("John"));
        assert_eq!(params.get("age"), Some("25"));
        assert_eq!(params.get("city"), Some("New York")); // Now decoded
    }

    #[test]
    fn test_no_query_params() {
        let url = "https://example.com/path";

        let params = StackQueryParams::new(url);

        assert_eq!(params.len(), 0);
        assert!(params.is_empty());
    }

    #[test]
    fn test_empty_value() {
        let url = "https://example.com/path?param=";

        let params = StackQueryParams::new(url);

        assert_eq!(params.len(), 1);
        assert_eq!(params.get("param"), Some(""));
    }

    #[test]
    fn test_percent_decode() {
        assert_eq!(percent_decode::<32>("hello+world").as_str(), "hello world");
        assert_eq!(
            percent_decode::<32>("hello%20world").as_str(),
            "hello world"
        );
        assert_eq!(percent_decode::<32>("50%25").as_str(), "50%");
        assert_eq!(percent_decode::<32>("a%2Fb%2Fc").as_str(), "a/b/c");
        assert_eq!(percent_decode::<32>("a+b+c").as_str(), "a b c");
    }

    #[test]
    fn test_max_params_limit() {
        // Create a URL with more than MAX_QUERY_PARAMS parameters
        let mut url = String::from("https://example.com/path?");
        for i in 0..MAX_PARAM_COUNT + 5 {
            if i > 0 {
                url.push('&');
            }
            url.push_str(&format!("param{}=value{}", i, i));
        }

        let params = StackQueryParams::new(&url);

        // Should only have parsed MAX_QUERY_PARAMS
        assert_eq!(params.len(), MAX_PARAM_COUNT);
    }

    #[test]
    fn test_key_value_length_limits() {
        // Create a key and value that exceed the length limits
        let long_key = "a".repeat(MAX_KEY_SIZE + 10);
        let long_value = "b".repeat(MAX_VALUE_SIZE + 10);
        let url = format!("https://example.com/path?{}={}", long_key, long_value);

        let params = StackQueryParams::new(&url);

        assert_eq!(params.len(), 1);

        // The parsed key should be truncated
        let expected_key = "a".repeat(MAX_KEY_SIZE);
        let expected_value = "b".repeat(MAX_VALUE_SIZE);

        // Get the first key directly since we can't lookup by the full long key
        let (actual_key, actual_value) = params.iter().next().unwrap();

        assert_eq!(actual_key, expected_key);
        assert_eq!(actual_value, expected_value);
    }

    #[test]
    fn test_custom_new() {
        let url = "https://example.com/path?name=John&age=25&city=New%20York";

        let params = StackQueryParams::<8, 16, 64>::custom_new(url);

        assert_eq!(params.len(), 3);
        assert_eq!(params.get("name"), Some("John"));
        assert_eq!(params.get("age"), Some("25"));
        assert_eq!(params.get("city"), Some("New York"));
    }
}