kawa 0.7.0

Agnostic representation of HTTP/1.1 and HTTP/2.0 for parsing, generating and translating HTTP messages, with zero-copy, made for Sōzu.
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
use nom::{
    bytes::{
        complete::{tag as tag_complete, take_while as take_while_complete},
        streaming::{tag, take, take_while},
    },
    character::{
        complete::char as char_complete,
        streaming::{char, hex_digit1, one_of},
    },
    combinator::opt,
    error::{make_error, ErrorKind as NomErrorKind, ParseError},
    AsChar, Err as NomError, IResult, Parser,
};

use crate::{
    compile_lookup, make_char_table,
    protocol::utils::compare_no_case,
    storage::{Store, Version},
};

fn error_position<I, E: ParseError<I>>(i: I, kind: NomErrorKind) -> NomError<E> {
    NomError::Error(make_error(i, kind))
}

/// A set of rules to decide if a character is valid or not
pub struct CharLookup {
    ranges: CharRanges,
    table: CharTable,
    len: i32,
}

/// Character lookup table, it indicates for each character if it passes or not
#[repr(align(16))]
pub struct CharTable([bool; 256]);

impl std::ops::Deref for CharTable {
    type Target = [bool; 256];
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Character invalid ranges, defines up to 8 ranges of invalid characters
#[repr(align(16))]
pub struct CharRanges([u8; 16]);

impl std::ops::Deref for CharRanges {
    type Target = [u8; 16];
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

//////////////////////////////////////////////////
// STREAMING PARSERS
//////////////////////////////////////////////////

#[cfg(not(feature = "tolerant-parsing"))]
const LAST_INVALID_CHAR: u8 = 0xFF;
#[cfg(feature = "tolerant-parsing")]
const LAST_INVALID_CHAR: u8 = 0x9F;

/*
    Creates a tchar module for parsing header keys and http methods.

    Control characters
   \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    Visible characters
   SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    0, 1, X, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, X,
    0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
    @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
    `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,

    note: _mm_cmpestri can only hold 8 ranges, " and / are invalid tchars but will slip through.
    It should be acceptable as tchars are delimited by spaces or colons and Kawa is not an HTTP
    validator, it parses the strict minimum to extract an higher representation. Nonetheless, the
    parsers are strict enough to ensure all slices are valid UTF-8, so from_utf8_uncheck can be
    used on them.
*/
compile_lookup!(pub tchar => [0x00..0x20, b'('..b')', b'['..b']', b'{', b'}', b',', b':'..b'@', 0x7F..LAST_INVALID_CHAR]);

/*
    Creates a vchar module for preparsing URIs.

    Control characters
   \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    Visible characters
   SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
*/
compile_lookup!(pub vchar => [0x00..0x20, 0x7F..LAST_INVALID_CHAR]);

/*
    Creates a ck_char and cv_char module for parsing cookie keys and values respectively.

    Control characters
   \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    Visible characters
   SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, ?, 1, 1,
    @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,

    note: cookie values can contain equal signs and spaces, not keys.
*/
compile_lookup!(pub ck_char => [0x00..0x1F, b';', b'=', 0x7F..LAST_INVALID_CHAR]);
compile_lookup!(pub cv_char => [0x00..0x1F, b';', 0x7F..LAST_INVALID_CHAR]);

/*
    Creates a achar module for parsing header values and http reasons.

    Control characters
   \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    Visible characters
   SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
*/
compile_lookup!(pub achar => [0x00..0x08, 0x0A..0x1F, 0x7F..LAST_INVALID_CHAR]);

#[inline]
fn space(i: &[u8]) -> IResult<&[u8], char> {
    char(' ').parse(i)
}

#[inline]
pub fn crlf(i: &[u8]) -> IResult<&[u8], &[u8]> {
    tag(&b"\r\n"[..]).parse(i)
}

#[inline]
fn http_version(i: &[u8]) -> IResult<&[u8], Version> {
    let (i, _) = tag(&b"HTTP/1."[..]).parse(i)?;
    let (i, minor) = one_of("01").parse(i)?;

    Ok((
        i,
        if minor == '0' {
            Version::V10
        } else {
            Version::V11
        },
    ))
}

#[inline]
fn http_status(i: &[u8]) -> IResult<&[u8], (&[u8], u16)> {
    let (i, status) = take(3usize).parse(i)?;
    let code = std::str::from_utf8(status)
        .ok()
        .and_then(|status| status.parse::<u16>().ok());
    match code {
        Some(code) => Ok((i, (status, code))),
        None => Err(error_position(i, NomErrorKind::MapRes)),
    }
}

/// parse first line of HTTP request into RawStatusLine, including terminating CRLF
///
/// example: `GET www.clever.cloud.com HTTP/1.1\r\n`
#[inline]
#[allow(clippy::type_complexity)]
pub fn parse_request_line(i: &[u8]) -> IResult<&[u8], (&[u8], &[u8], Version)> {
    let (i, method) = tchar::take_while_fast(i)?;
    let (i, _) = space(i)?;
    let (i, uri) = vchar::take_while_fast(i)?;
    let (i, _) = space(i)?;
    let (i, version) = http_version(i)?;
    let (i, _) = crlf(i)?;
    Ok((i, (method, uri, version)))
}

/// parse first line of HTTP response into RawStatusLine, including terminating CRLF
///
/// example: `HTTP/1.1 200 OK\r\n`
#[inline]
#[allow(clippy::type_complexity)]
pub fn parse_response_line(i: &[u8]) -> IResult<&[u8], (Version, &[u8], u16, &[u8])> {
    let (i, version) = http_version(i)?;
    let (i, _) = space(i)?;
    let (i, (status, code)) = http_status(i)?;
    let (i, _) = space(i)?;
    let (i, reason) = achar::take_while_fast(i)?;
    let (i, _) = crlf(i)?;
    Ok((i, (version, status, code, reason)))
}

/// parse a HTTP header, including terminating CRLF
/// if it is a cookie header, nothing is returned and parse_single_crumb should be called
///
/// example: `Content-Length: 42\r\n`
#[inline]
#[allow(clippy::type_complexity)]
pub fn parse_header_or_cookie(i: &[u8]) -> IResult<&[u8], Option<(&[u8], &[u8])>> {
    let (i, key) = tchar::take_while_fast(i)?;
    let (i, _) = tag(&b":"[..]).parse(i)?;
    let (i, _) = take_while(AsChar::is_space).parse(i)?;
    if compare_no_case(key, b"cookie") {
        return Ok((i, None));
    }
    let (i, val) = achar::take_while_fast(i)?;
    let (i, _) = crlf(i)?;
    Ok((i, Some((key, val))))
}

/// parse a HTTP header, including terminating CRLF
/// note: treat cookie headers as regular headers
///
/// example: `Content-Length: 42\r\n`
#[inline]
pub fn parse_header(i: &[u8]) -> IResult<&[u8], (&[u8], &[u8])> {
    let (i, key) = tchar::take_while_fast(i)?;
    let (i, _) = tag(&b":"[..]).parse(i)?;
    let (i, _) = take_while(AsChar::is_space).parse(i)?;
    let (i, val) = achar::take_while_fast(i)?;
    let (i, _) = crlf(i)?;
    Ok((i, (key, val)))
}

/// parse a single crumb from a Cookie header
///
/// examples:
/// ```txt
/// crumb=0          -> ("crumb", "0")
/// crumb=1; crumb=2 -> ("crumb", "1")
/// ```
#[inline]
#[allow(clippy::type_complexity)]
pub fn parse_single_crumb(i: &[u8], first: bool) -> IResult<&[u8], (&[u8], &[u8])> {
    let i = if !first {
        let (i, _) = (tag(&b";"[..]), take_while(AsChar::is_space)).parse(i)?;
        i
    } else {
        i
    };
    let (i, key) = ck_char::take_while_fast(i)?;
    let (i, val) = opt((tag(&b"="[..]), cv_char::take_while_fast)).parse(i)?;

    match val {
        Some((_, val)) => Ok((i, (key, val))),
        None => Ok((i, (&key[..0], key))),
    }
}

//////////////////////////////////////////////////
// COMPLETE PARSERS
//////////////////////////////////////////////////

#[rustfmt::skip]
const SCHEME_CHAR_MAP: CharTable = make_char_table![
    // Control characters
// \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
//                                  \e
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    // Visible characters
// SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0,
//  0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
//  @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
//  `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,

    // Non ascii characters
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];

#[rustfmt::skip]
const AUTHORITY_CHAR_MAP: CharTable = make_char_table![
    // Control characters
// \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
//                                  \e
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    // Visible characters
// SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
//  0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
//  @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,

    // Non ascii characters
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];

#[rustfmt::skip]
const USERINFO_CHAR_MAP: CharTable = make_char_table![
    // Control characters
// \0                   \a \b \t \n \v \f \r
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
//                                  \e
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

    // Visible characters
// SP  !  "  #  $  %  &  '  (  )  *  +  ,  -  .  /
    0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
//  0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
//  @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  P  Q  R  S  T  U  V  W  X  Y  Z  [  \  ]  ^  _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
//  `  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
//  p  q  r  s  t  u  v  w  x  y  z  {  |  }  ~
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,

    // Non ascii characters
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];

#[inline]
fn is_scheme_char(i: u8) -> bool {
    SCHEME_CHAR_MAP[i as usize]
}
#[inline]
fn is_authority_char(i: u8) -> bool {
    AUTHORITY_CHAR_MAP[i as usize]
}
#[inline]
fn is_userinfo_char(i: u8) -> bool {
    USERINFO_CHAR_MAP[i as usize]
}

#[inline]
pub fn chunk_size(i: &[u8]) -> IResult<&[u8], (&[u8], usize)> {
    let (i, size_hexa) = hex_digit1(i)?;
    let size = std::str::from_utf8(size_hexa)
        .ok()
        .and_then(|chunk_size| usize::from_str_radix(chunk_size, 16).ok());

    match size {
        Some(size) => Ok((i, (size_hexa, size))),
        None => Err(error_position(i, NomErrorKind::MapRes)),
    }
}

#[inline]
pub fn parse_chunk_header(first: bool, i: &[u8]) -> IResult<&[u8], (&[u8], usize)> {
    if first {
        let (i, size) = chunk_size(i)?;
        let (i, _) = crlf(i)?;
        Ok((i, size))
    } else {
        let (i, _) = crlf(i)?;
        let (i, size) = chunk_size(i)?;
        let (i, _) = crlf(i)?;
        Ok((i, size))
    }
}

#[inline]
fn userinfo(i: &[u8]) -> IResult<&[u8], &[u8]> {
    let (i, userinfo) = take_while_complete(is_userinfo_char).parse(i)?;
    let (i, _) = char_complete('@').parse(i)?;
    Ok((i, userinfo))
}

/// ```txt
/// server-wide:         OPTIONS * HTTP/1.1                                      -> (Empty, "*")
/// origin:              OPTIONS /index.html                                     -> (Empty, "/index.html")
/// absolute+empty path: OPTIONS http://www.example.org:8001 HTTP/1.1            -> ("www.example.org:8001", "*")
/// absolute+path:       OPTIONS http://www.example.org:8001/index.html HTTP/1.1 -> ("www.example.org:8001", "/index.html")
/// ```
#[inline]
fn parse_asterisk_form<'a>(buffer: &[u8], i: &'a [u8]) -> IResult<&'a [u8], (Store, Store)> {
    if i == b"*" {
        Ok((i, (Store::Empty, Store::Static(b"*"))))
    } else if i[0] == b'/' {
        parse_origin_form(buffer, i)
    } else {
        parse_absolute_form(buffer, i, b"*")
    }
}
/// ```txt
/// www.example.org:8001 -> ("www.example.org:8001", "/")
/// ```
#[inline]
fn parse_authority_form<'a>(buffer: &[u8], i: &'a [u8]) -> IResult<&'a [u8], (Store, Store)> {
    Ok((&[], (Store::new_slice(buffer, i), Store::Static(b"/"))))
}
/// ```txt
/// /index.html?k=v#h -> (Empty, "/index.html?k=v#h")
/// ```
#[inline]
fn parse_origin_form<'a>(buffer: &[u8], i: &'a [u8]) -> IResult<&'a [u8], (Store, Store)> {
    Ok((&[], (Store::Empty, Store::new_slice(buffer, i))))
}
/// ```txt
/// http://www.example.org:8001                            -> ("www.example.org:8001", "/")
/// http://www.example.org:8001?k=v#h                      -> ("www.example.org:8001", "?k=v#h")
/// http://www.example.org:8001/index.html?k=v#h           -> ("www.example.org:8001", "/index.html?k=v#h")
/// http://user:pass@www.example.org:8001/index.html?k=v#h -> ("www.example.org:8001", "/index.html?k=v#h")
/// ```
#[inline]
fn parse_absolute_form<'a>(
    buffer: &[u8],
    i: &'a [u8],
    empty_path_replacer: &'static [u8],
) -> IResult<&'a [u8], (Store, Store)> {
    let (i, _scheme) = take_while_complete(is_scheme_char).parse(i)?;
    let (i, _) = tag_complete(&b"://"[..]).parse(i)?;
    let (i, _userinfo) = opt(userinfo).parse(i)?;
    let (path, authority) = take_while_complete(is_authority_char).parse(i)?;

    let authority = Store::new_slice(buffer, authority);
    let path = if path.is_empty() {
        Store::Static(empty_path_replacer)
    } else {
        Store::new_slice(buffer, path)
    };
    Ok((&[], (authority, path)))
}

#[inline]
pub fn parse_url(buffer: &[u8], method: &[u8], i: &[u8]) -> Option<(Store, Store)> {
    if i.is_empty() {
        return Some((Store::Empty, Store::Static(b"/")));
    }
    let url = if compare_no_case(method, b"OPTIONS") {
        parse_asterisk_form(buffer, i)
    } else if compare_no_case(method, b"CONNECT") {
        parse_authority_form(buffer, i)
    } else if i[0] == b'/' {
        parse_origin_form(buffer, i)
    } else {
        parse_absolute_form(buffer, i, b"/")
    };
    match url {
        Ok((_, url)) => Some(url),
        _ => None,
    }
}

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

    fn test_url(method: &str, url: &str, expect: (&str, &str)) {
        println!("{method} {url} HTTP/1.1");
        let result = parse_url(url.as_bytes(), method.as_bytes(), url.as_bytes());
        assert!(result.is_some());
        let (authority, path) = result.unwrap();
        assert_eq!(
            (
                authority
                    .data_opt(url.as_bytes())
                    .map_or("", |data| unsafe { from_utf8_unchecked(data) }),
                path.data_opt(url.as_bytes())
                    .map_or("", |data| unsafe { from_utf8_unchecked(data) })
            ),
            expect
        );
    }

    #[test]
    fn test_asterisk_form() {
        // server-wide:
        test_url("OPTIONS", "*", ("", "*"));
        // origin
        test_url("OPTIONS", "/index.html?k=v#h", ("", "/index.html?k=v#h"));
        // absolute + empty path
        test_url(
            "OPTIONS",
            "http://www.example.org:8001",
            ("www.example.org:8001", "*"),
        );
        // absolute + path
        test_url(
            "OPTIONS",
            "http://www.example.org:8001/index.html?k=v#h",
            ("www.example.org:8001", "/index.html?k=v#h"),
        );
    }

    #[test]
    fn test_authority_form() {
        // connect
        test_url(
            "CONNECT",
            "www.example.org:8001",
            ("www.example.org:8001", "/"),
        );
    }

    #[test]
    fn test_origin_form() {
        test_url("GET", "/index.html?k=v#h", ("", "/index.html?k=v#h"));
        test_url("OPTIONS", "/index.html?k=v#h", ("", "/index.html?k=v#h"));
    }

    #[test]
    fn test_absolute_form() {
        // empty path
        test_url(
            "GET",
            "http://www.example.org:8001",
            ("www.example.org:8001", "/"),
        );
        // empty path + query params
        test_url(
            "GET",
            "http://www.example.org:8001?k=v#h",
            ("www.example.org:8001", "?k=v#h"),
        );
        // empty path + path
        test_url(
            "GET",
            "http://www.example.org:8001/index.html?k=v#h",
            ("www.example.org:8001", "/index.html?k=v#h"),
        );
        // deprecated user-info + empty path + path
        test_url(
            "GET",
            "http://user:pass@www.example.org:8001/index.html?k=v#h",
            ("www.example.org:8001", "/index.html?k=v#h"),
        );
    }
}