gload 0.5.1

A command line client for the Gemini protocol.
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! This software is licensed as described in the file LICENSE, which
//! you should have received as part of this distribution.
//!
//! You may opt to use, copy, modify, merge, publish, distribute and/or sell
//! copies of the Software, and permit persons to whom the Software is
//! furnished to do so, under the terms of the LICENSE file.
//!
//! This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
//! KIND, either express or implied.
//!
//! SPDX-License-Identifier: BSD-3-Clause

use crate::request::{CR, LF};
use core::{
	num::NonZeroU8,
	str::{FromStr, Utf8Error},
};

/// A struct that represents a full Gemini response, with utilities to parse
/// important parts from it.
#[derive(Debug, Clone)]
pub struct Response {
	status: StatusCode,
	meta: Option<String>,
	body: Option<Vec<u8>>,
}

const BYTE_ORDER_MARK: &[u8] = "\u{FEFF}".as_bytes();

impl Response {
	/// Parses the given bytes as a Gemini response. If the response is malformed,
	/// we try our best with it. Returns `Err` in the following cases:
	/// - The status code out of range (10-69 inclusive) or containss a non-ASCII-digit
	///   (e.g. `09`, `71`, `2 `, `AA`, etc. are invalid)
	/// - The header isn't valid UTF-8 (e.g. `[0x32 30 c0 62 61 64]`/`20�bad` is invalid)
	/// - The header is too short to parse meaningfully (less than two bytes)
	pub(crate) fn new<B: AsRef<[u8]>>(response_bytes: B) -> Result<Self, ResponseParseError> {
		let mut response_chunks = response_bytes.as_ref().splitn(2, |c| *c == CR || *c == LF);
		let header_bytes = response_chunks.next().expect("always some response bytes");

		// Spec: "Response headers MUST be UTF-8 encoded text and MUST NOT begin with the Byte Order Mark U+FEFF"
		// but we'll be lenient and just ignore it :3
		let start = if header_bytes.starts_with(BYTE_ORDER_MARK) {
			BYTE_ORDER_MARK.len()
		} else {
			0
		};

		let status_bytes: [u8; 2] = match header_bytes.get(start..(start + 2)) {
			None => return Err(ResponseParseError::TooShort),
			Some(b) => b.try_into().expect("slice came from a range of two"),
		};
		let status = match StatusCode::from_bytes(status_bytes) {
			// Spec: "A client MUST reject any status code less than '10' and greater than '69' and warn the user of such."
			Err(err) => return Err(ResponseParseError::InvalidStatus(err)),
			Ok(s) => s,
		};

		let status_end = start + 2;

		let meta_bytes = header_bytes.get(status_end..).expect("status idx is valid");
		let header = str::from_utf8(meta_bytes)?.trim_start(); // trim one or more leading witespae
		let meta = if header.is_empty() {
			None
		} else {
			Some(header.to_owned())
		};

		let body = match response_chunks.next() {
			None => None,
			Some(body_bytes) => {
				let bytes = body_bytes.strip_prefix(&[LF]).unwrap_or(body_bytes);
				if bytes.is_empty() {
					None
				} else {
					Some(bytes.to_owned())
				}
			}
		};

		Ok(Self { status, meta, body })
	}

	/// The response status.
	#[inline]
	pub const fn status(&self) -> StatusCode {
		self.status
	}

	/// The response meta (redirect target, error message, etc.) if any. If [`Some`],
	/// the string is guaranteed to be nonempty.
	#[inline]
	pub const fn meta(&self) -> Option<&str> {
		match &self.meta {
			None => None,
			Some(meta) => Some(meta.as_str()),
		}
	}

	/// The response body, if any. If [`Some`], the slice is guaranteed to be nonempty.
	#[inline]
	pub const fn body(&self) -> Option<&[u8]> {
		match &self.body {
			None => None,
			Some(b) => Some(b.as_slice()),
		}
	}

	/// Returns `true` if the status is between 20 and 29.
	#[inline]
	pub const fn is_success(&self) -> bool {
		self.status().is_success()
	}
}

/// A server response could not be parsed meaningfully.
#[derive(Debug)]
#[non_exhaustive]
pub enum ResponseParseError {
	/// The server responded with an invalid status code.
	InvalidStatus(InvalidStatusCode),

	/// The server response header could not be parsed as UTF-8.
	HeaderNotUtf8(Utf8Error),

	/// The server response was too short to determine a status code.
	TooShort,
}

#[cfg(not(tarpaulin_include))]
impl core::fmt::Display for ResponseParseError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::InvalidStatus(err) => write!(f, "{err}"),
			Self::HeaderNotUtf8(err) => write!(f, "Could not parse header: {err}"),
			Self::TooShort => write!(f, "Header too short to parse"),
		}
	}
}

#[cfg(not(tarpaulin_include))]
impl core::error::Error for ResponseParseError {}

impl From<Utf8Error> for ResponseParseError {
	fn from(value: Utf8Error) -> Self {
		Self::HeaderNotUtf8(value)
	}
}

/// A Gemini protocol status code.
///
/// The status values range from 10 to 69 inclusive. The spec does not currently
/// define all values, but known values are provided as constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StatusCode(NonZeroU8);

/// The six status category groups, as defined by the Gemini network protocol spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusCategory {
	// Spec: "There are six groups of status codes:"
	/// Statuses from 10 to 19.
	InputExpected,

	/// Statuses from 20-29.
	Success,

	/// Statuses from 30-39
	Redirection,

	/// Statuses from 40-49
	TemporaryFailure,

	/// Statuses from 50-59
	PermanentFailure,

	/// Statuses from 60-69
	ClientCertificates,
}

impl From<StatusCode> for StatusCategory {
	#[inline]
	fn from(value: StatusCode) -> Self {
		value.category()
	}
}

impl StatusCode {
	/// The decimal status code given by the server, guaranteed to be between 10 and 69, inclusive.
	#[inline]
	pub const fn as_u8(self) -> u8 {
		self.0.get()
	}

	/// The category under which this status falls. Determines things like how the reply header is parsed.
	#[inline]
	pub const fn category(self) -> StatusCategory {
		// Spec: "The status values range from 10 to 69 inclusive, although not all values are currently defined."
		// Spec: "They are grouped such that a client MAY use the initial digit to handle the response"
		match self.0.get() {
			..10 => unreachable!(),
			10..=19 => StatusCategory::InputExpected,
			20..=29 => StatusCategory::Success,
			30..=39 => StatusCategory::Redirection,
			40..=49 => StatusCategory::TemporaryFailure,
			50..=59 => StatusCategory::PermanentFailure,
			60..=69 => StatusCategory::ClientCertificates,
			70.. => unreachable!(),
		}
	}

	/// Constructs a [`StatusCode`] value from the given UTF-8 bytes. Returns `Err` if
	/// the status is invalid.
	#[inline]
	pub const fn from_bytes(bytes: [u8; 2]) -> Result<Self, InvalidStatusCode> {
		// TODO: Is there a more efficient math-y way to do this conversion?
		let raw_str = match str::from_utf8(&bytes) {
			Err(_) => return Err(InvalidStatusCode::new(InvalidStatusCodeKind::Utf8)),
			Ok(s) => s,
		};
		let raw = match u8::from_str_radix(raw_str, 10) {
			Err(_) => return Err(InvalidStatusCode::new(InvalidStatusCodeKind::ParseInt)),
			Ok(r) => r,
		};
		Self::from_u8(raw)
	}

	/// Constructs a [`StatusCode`] value from the given integer. Returns `Err` if
	/// the status is invalid.
	#[inline]
	pub const fn from_u8(value: u8) -> Result<Self, InvalidStatusCode> {
		// Spec: "A client SHOULD deal with undefined status codes between '10' and '69' per the default action of the initial digit. So a status of '14' should be acted upon as if the client received a '10'; a status of '22' should be acted upon as if the client received a '20'."
		if value < 10 || value > 69 {
			// Spec: "A client MUST reject any status code less than '10' and greater than '69' and warn the user of such."
			Err(InvalidStatusCode::new(InvalidStatusCodeKind::Range))
		} else {
			Ok(Self(NonZeroU8::new(value).expect("non-zero")))
		}
	}

	/// Returns `true` if the status is between 10 and 19, inclusive.
	#[inline]
	pub const fn is_input(self) -> bool {
		matches!(self.category(), StatusCategory::InputExpected)
	}

	/// Returns `true` if the status is between 20 and 29, inclusive.
	#[inline]
	pub const fn is_success(self) -> bool {
		matches!(self.category(), StatusCategory::Success)
	}

	/// Returns `true` if the status is between 30 and 39, inclusive.
	#[inline]
	pub const fn is_redirection(self) -> bool {
		matches!(self.category(), StatusCategory::Redirection)
	}

	/// Returns `true` if the status is between 40 and 49, inclusive.
	#[inline]
	pub const fn is_temporary_failure(self) -> bool {
		matches!(self.category(), StatusCategory::TemporaryFailure)
	}

	/// Returns `true` if the status is between 50 and 59, inclusive.
	#[inline]
	pub const fn is_permanent_failure(self) -> bool {
		matches!(self.category(), StatusCategory::PermanentFailure)
	}

	/// Returns `true` if the status is between 60 and 69, inclusive.
	#[inline]
	pub const fn is_client_certificate_failure(self) -> bool {
		matches!(self.category(), StatusCategory::ClientCertificates)
	}

	/// Returns `true` if the status is greater than or equal to 40.
	#[inline]
	pub const fn is_failure(self) -> bool {
		match self.category() {
			StatusCategory::InputExpected
			| StatusCategory::Success
			| StatusCategory::Redirection => false,
			StatusCategory::TemporaryFailure
			| StatusCategory::PermanentFailure
			| StatusCategory::ClientCertificates => true,
		}
	}
}

macro_rules! status_code {
	(
		$(
			$(#[$docs:meta])*
			($code:literal, $name:ident),
		)+
	) => {
		impl StatusCode {
		$(
			$(#[$docs])*
			pub const $name: Self = Self(NonZeroU8::new($code).expect("non-zero"));
		)+
		}
	};
}

status_code! {
	/// Status 10---input expected
	(10, INPUT_EXPECTED),
	/// Status 11---sensitive input expected
	(11, SENSITIVE_INPUT_EXPECTED),

	/// Status 20---success
	(20, SUCCESS),

	/// Status 30---temporary redirection
	(30, TEMPORARY_REDIRECTION),
	/// Status 31---permanent redirection
	(31, PERMANENT_REDIRECTION),

	/// Status 40---temporary failure
	(40, TEMPORARY_FAILURE),
	/// Status 41---server unavailable
	(41, SERVER_UNAVAILABLE),
	/// Status 42---CGI error
	(42, CGI_ERROR),
	/// Status 43---proxy error
	(43, PROXY_ERROR),
	/// Status 44---slow down
	(44, SLOW_DOWN),

	/// Status 50---permanent failure
	(50, PERMANENT_FAILURE),
	/// Status 51---not found
	(51, NOT_FOUND),
	/// Status 52---gone
	(52, GONE),
	/// Status 53---proxy request refused
	(53, PROXY_REQUEST_REFUSED),
	/// Status 59---bad request
	(59, BAD_REQUEST),

	/// Status 60---certificate required
	(60, CERTIFICATE_REQUIRED),
	/// Status 61---certificate not authorized
	(61, CERTIFICATE_NOT_AUTHORIZED),
	/// Status 62---certificate not valid
	(62, CERTIFICATE_NOT_VALID),
}

impl Default for StatusCode {
	#[inline]
	fn default() -> Self {
		Self::SUCCESS
	}
}

impl PartialEq<u8> for StatusCode {
	#[inline]
	fn eq(&self, other: &u8) -> bool {
		self.as_u8() == *other
	}
}

impl From<StatusCode> for u8 {
	#[inline]
	fn from(value: StatusCode) -> Self {
		value.as_u8()
	}
}

impl TryFrom<&[u8]> for StatusCode {
	type Error = InvalidStatusCode;

	#[inline]
	fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
		let bytes: [u8; 2] = match value.try_into() {
			Ok(b) => b,
			Err(_) => return Err(InvalidStatusCode::new(InvalidStatusCodeKind::Length)),
		};
		Self::try_from(bytes)
	}
}

impl TryFrom<[u8; 2]> for StatusCode {
	type Error = InvalidStatusCode;

	#[inline]
	fn try_from(value: [u8; 2]) -> Result<Self, Self::Error> {
		Self::from_bytes(value)
	}
}

impl TryFrom<&[u8; 2]> for StatusCode {
	type Error = InvalidStatusCode;

	#[inline]
	fn try_from(value: &[u8; 2]) -> Result<Self, Self::Error> {
		Self::from_bytes(*value)
	}
}

impl TryFrom<u8> for StatusCode {
	type Error = InvalidStatusCode;

	#[inline]
	fn try_from(value: u8) -> Result<Self, Self::Error> {
		Self::from_u8(value)
	}
}

impl FromStr for StatusCode {
	type Err = InvalidStatusCode;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		if s.len() != 2 || s.chars().count() != 2 {
			return Err(InvalidStatusCode::new(InvalidStatusCodeKind::Length));
		}
		let raw = match s.parse::<u8>() {
			Err(_) => return Err(InvalidStatusCode::new(InvalidStatusCodeKind::ParseInt)),
			Ok(r) => r,
		};

		Self::from_u8(raw)
	}
}

impl TryFrom<&str> for StatusCode {
	type Error = InvalidStatusCode;

	#[inline]
	fn try_from(value: &str) -> Result<Self, Self::Error> {
		Self::from_str(value)
	}
}

impl TryFrom<String> for StatusCode {
	type Error = InvalidStatusCode;

	#[inline]
	fn try_from(value: String) -> Result<Self, Self::Error> {
		Self::from_str(&value)
	}
}

/// An invalid status code was found.
#[derive(Debug)]
pub struct InvalidStatusCode {
	kind: InvalidStatusCodeKind,
	__priv: (),
}

impl InvalidStatusCode {
	/// The way in which the code was invalid.
	#[inline]
	pub const fn kind(&self) -> InvalidStatusCodeKind {
		self.kind
	}

	#[inline]
	const fn new(kind: InvalidStatusCodeKind) -> Self {
		Self { kind, __priv: () }
	}
}

impl std::fmt::Display for InvalidStatusCode {
	#[inline]
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "invalid status code: {}", self.kind)
	}
}

impl std::error::Error for InvalidStatusCode {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidStatusCodeKind {
	/// The value couldn't be parsed as a u8.
	ParseInt,

	/// The value is either greater than 69 or less than 10.
	Range,

	/// The value is not 2 bytes long.
	Length,

	/// The value is not valid UTF-8.
	Utf8,
}

impl core::fmt::Display for InvalidStatusCodeKind {
	#[inline]
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::ParseInt => write!(f, "could not parse as u8"),
			Self::Range => write!(f, "value is less than 10 or greater than 69"),
			Self::Length => write!(f, "value is not exactly 2 characters"),
			Self::Utf8 => write!(f, "value is not valid UTF-8"),
		}
	}
}

// MARK: - Tests

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

	#[test]
	fn test_response_from_reasonable_bytes() {
		let res_data = b"20 text/gemini\r\nHello, world!\r\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert_eq!(res.body().unwrap(), b"Hello, world!\r\n".as_ref());
	}

	#[test]
	fn test_response_from_reasonable_bytes_with_non_unicode_body() {
		// 20 text/plain\r\nHello, w�rld!\r\n
		let res_data = [b"20 text/plain\r\nHello, w".as_ref(), &[0xc0], b"rld!\r\n"].concat();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/plain");
		assert_eq!(
			res.body().unwrap(),
			[b"Hello, w".as_ref(), &[0xc0], b"rld!\r\n"].concat()
		);
	}

	#[test]
	fn test_response_from_weird_status() {
		let res_data = b"21 text/gemini\r\nHello, world!\r\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), 21);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert_eq!(res.body().unwrap(), b"Hello, world!\r\n".as_ref());
	}

	#[test]
	fn test_response_from_bytes_without_trailing_newline() {
		let res_data = b"20 text/gemini\r\nHello, world!".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert_eq!(res.body().unwrap(), b"Hello, world!".as_ref());
	}

	#[test]
	fn test_response_from_bytes_with_extra_leading_body_space() {
		let res_data = b"20 text/gemini\r\n     Hello, world!\r\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert_eq!(res.body().unwrap(), b"     Hello, world!\r\n".as_ref());
	}

	#[test]
	fn test_response_from_bytes_with_extra_trailing_body_space() {
		let res_data = b"20 text/gemini\r\nHello, world!\r\n      ".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert_eq!(res.body().unwrap(), b"Hello, world!\r\n      ".as_ref());
	}

	#[test]
	fn test_response_from_bytes_with_no_body() {
		let res_data = b"20 text/gemini\r\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_extra_meta_space() {
		let res_data = b"20   text/gemini\r\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_nbsp() {
		let res_data = "20 text/gemini\r\n".as_bytes();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.status(), 20);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_byte_order_at_start() {
		let res_data = "\u{FEFF}20 text/gemini\r\n".as_bytes();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_delimiter() {
		let res_data = b"20 text/gemini".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_separation_after_status() {
		let res_data = "20text/gemini".as_bytes();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert_eq!(res.meta().unwrap(), "text/gemini");
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_mime() {
		let res_data = b"20\r\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert!(res.meta().is_none());
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_mime_reversed_delimiter() {
		let res_data = b"20\n\r".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert!(res.meta().is_none());
		assert_eq!(res.body().unwrap(), b"\r".as_ref());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_mime_no_line_feed() {
		let res_data = b"20\n".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert!(res.meta().is_none());
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_mime_no_delimiter() {
		let res_data = b"20".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), StatusCode::SUCCESS);
		assert!(res.meta().is_none());
		assert!(res.body().is_none());
	}

	#[test]
	fn test_response_from_malformed_bytes_with_no_mime_no_delimiter_and_weird_status() {
		let res_data = b"22".to_vec();
		let res = Response::new(res_data).unwrap();
		assert_eq!(res.status(), 22);
		assert!(res.meta().is_none());
		assert!(res.body().is_none());
	}

	#[test]
	fn test_fails_to_parse_single_byte() {
		let res_data = b"2".to_vec();
		let res = Response::new(res_data);
		assert!(matches!(res, Err(ResponseParseError::TooShort)));
	}

	#[test]
	fn test_fails_to_parse_empty_buffer() {
		let res_data = Vec::new();
		let res = Response::new(res_data);
		assert!(matches!(res, Err(ResponseParseError::TooShort)));
	}

	#[test]
	fn test_fails_to_parse_non_utf8_status() {
		let res_data = [0x32, 0xc0, 0x20, 0x62, 0x61, 0x64]; // "2� bad"
		let res = Response::new(res_data).err().unwrap();
		assert!(
			matches!(res, ResponseParseError::InvalidStatus(err) if err.kind() == InvalidStatusCodeKind::Utf8)
		);
	}

	#[test]
	fn test_fails_to_parse_non_utf8_separator() {
		let res_data = [0x32, 0x30, 0xc0, 0x62, 0x61, 0x64]; // "20�bad"
		let res = Response::new(res_data).err().unwrap();
		assert!(
			matches!(res, ResponseParseError::HeaderNotUtf8(err) if format!("{err}") == "invalid utf-8 sequence of 1 bytes from index 0"),
			"{res}"
		);
	}

	#[test]
	fn test_fails_to_parse_non_utf8_header() {
		let res_data = [0x32, 0x30, 0x20, 0x62, 0xc0, 0x61, 0x64]; // "20 b�ad"
		let res = Response::new(res_data).err().unwrap();
		assert!(
			matches!(res, ResponseParseError::HeaderNotUtf8(err) if format!("{err}") == "invalid utf-8 sequence of 1 bytes from index 2"),
			"{res}"
		);
	}

	// MARK: Status

	#[test]
	fn test_invalid_statuses() {
		// Less than 10, greater than 69, and non-ASCII-digit bytes aren't allowed
		#[rustfmt::skip]
		let bad_statuses = [
			b"--", b"--", b"--", b"--", b"--", b"--", b"--", b"--", b"--", b"--",
			b"0-", b"1-", b"2-", b"3-", b"4-", b"5-", b"6-", b"7-", b"8-", b"9-",
			b"-0", b"-1", b"-2", b"-3", b"-4", b"-5", b"-6", b"-7", b"-8", b"-9",
			b"00", b"01", b"02", b"03", b"04", b"05", b"06", b"07", b"08", b"09",
			b"70", b"71", b"72", b"73", b"74", b"75", b"76", b"77", b"78", b"79",
			b"80", b"81", b"82", b"83", b"84", b"85", b"86", b"87", b"88", b"89",
			b"90", b"91", b"92", b"93", b"94", b"95", b"96", b"97", b"98", b"99",
			b"0A", b"0A", b"0A", b"0A", b"0A", b"0A", b"0A", b"0A", b"0A", b"0A",
			b"A0", b"A0", b"A0", b"A0", b"A0", b"A0", b"A0", b"A0", b"A0", b"A0",
			b"AA", b"AA", b"AA", b"AA", b"AA", b"AA", b"AA", b"AA", b"AA", b"AA",
			b"1A", b"1A", b"1A", b"1A", b"1A", b"1A", b"1A", b"1A", b"1A", b"1A",
			&[0xef, 0xbb], // start of Byte Order Mark
		];
		for case in bad_statuses {
			// bad status should return an error
			let res = StatusCode::from_bytes(*case);
			assert!(res.is_err());

			// same when parsing requests
			let err = Response::new(case).err().unwrap(); // status alone is otherwise valid
			assert!(matches!(err, ResponseParseError::InvalidStatus(_)));
		}
	}

	#[test]
	#[rustfmt::skip]
	fn test_valid_statuses() {
		// Known values
		assert_eq!(StatusCode::try_from(b"10").unwrap(), StatusCode::INPUT_EXPECTED);
		assert_eq!(StatusCode::try_from(b"11").unwrap(), StatusCode::SENSITIVE_INPUT_EXPECTED);

		assert_eq!(StatusCode::try_from(b"20").unwrap(), StatusCode::SUCCESS);

		assert_eq!(StatusCode::try_from(b"30").unwrap(), StatusCode::TEMPORARY_REDIRECTION);
		assert_eq!(StatusCode::try_from(b"31").unwrap(), StatusCode::PERMANENT_REDIRECTION);

		assert_eq!(StatusCode::try_from(b"40").unwrap(), StatusCode::TEMPORARY_FAILURE);
		assert_eq!(StatusCode::try_from(b"41").unwrap(), StatusCode::SERVER_UNAVAILABLE);
		assert_eq!(StatusCode::try_from(b"42").unwrap(), StatusCode::CGI_ERROR);
		assert_eq!(StatusCode::try_from(b"43").unwrap(), StatusCode::PROXY_ERROR);
		assert_eq!(StatusCode::try_from(b"44").unwrap(), StatusCode::SLOW_DOWN);

		assert_eq!(StatusCode::try_from(b"50").unwrap(), StatusCode::PERMANENT_FAILURE);
		assert_eq!(StatusCode::try_from(b"51").unwrap(), StatusCode::NOT_FOUND);
		assert_eq!(StatusCode::try_from(b"52").unwrap(), StatusCode::GONE);
		assert_eq!(StatusCode::try_from(b"53").unwrap(), StatusCode::PROXY_REQUEST_REFUSED);
		assert_eq!(StatusCode::try_from(b"59").unwrap(), StatusCode::BAD_REQUEST);

		assert_eq!(StatusCode::try_from(b"60").unwrap(), StatusCode::CERTIFICATE_REQUIRED);
		assert_eq!(StatusCode::try_from(b"61").unwrap(), StatusCode::CERTIFICATE_NOT_AUTHORIZED);
		assert_eq!(StatusCode::try_from(b"62").unwrap(), StatusCode::CERTIFICATE_NOT_VALID);

		// Unknown values
		let cases = [
			(*b"13", 13, StatusCategory::InputExpected),
			(*b"14", 14, StatusCategory::InputExpected),
			(*b"15", 15, StatusCategory::InputExpected),
			(*b"16", 16, StatusCategory::InputExpected),
			(*b"17", 17, StatusCategory::InputExpected),
			(*b"18", 18, StatusCategory::InputExpected),
			(*b"19", 19, StatusCategory::InputExpected),
			(*b"21", 21, StatusCategory::Success),
			(*b"22", 22, StatusCategory::Success),
			(*b"23", 23, StatusCategory::Success),
			(*b"24", 24, StatusCategory::Success),
			(*b"25", 25, StatusCategory::Success),
			(*b"26", 26, StatusCategory::Success),
			(*b"27", 27, StatusCategory::Success),
			(*b"28", 28, StatusCategory::Success),
			(*b"29", 29, StatusCategory::Success),
			(*b"32", 32, StatusCategory::Redirection),
			(*b"33", 33, StatusCategory::Redirection),
			(*b"34", 34, StatusCategory::Redirection),
			(*b"35", 35, StatusCategory::Redirection),
			(*b"36", 36, StatusCategory::Redirection),
			(*b"37", 37, StatusCategory::Redirection),
			(*b"38", 38, StatusCategory::Redirection),
			(*b"39", 39, StatusCategory::Redirection),
			(*b"45", 45, StatusCategory::TemporaryFailure),
			(*b"46", 46, StatusCategory::TemporaryFailure),
			(*b"47", 47, StatusCategory::TemporaryFailure),
			(*b"48", 48, StatusCategory::TemporaryFailure),
			(*b"49", 49, StatusCategory::TemporaryFailure),
			(*b"54", 54, StatusCategory::PermanentFailure),
			(*b"55", 55, StatusCategory::PermanentFailure),
			(*b"56", 56, StatusCategory::PermanentFailure),
			(*b"57", 57, StatusCategory::PermanentFailure),
			(*b"58", 58, StatusCategory::PermanentFailure),
			(*b"63", 63, StatusCategory::ClientCertificates),
			(*b"64", 64, StatusCategory::ClientCertificates),
			(*b"65", 65, StatusCategory::ClientCertificates),
			(*b"66", 66, StatusCategory::ClientCertificates),
			(*b"67", 67, StatusCategory::ClientCertificates),
			(*b"68", 68, StatusCategory::ClientCertificates),
			(*b"69", 69, StatusCategory::ClientCertificates),
		];
		for (bytes, value, category) in cases {
			let status = StatusCode::try_from(bytes).unwrap();
			assert_eq!(status, value);
			assert_eq!(status, StatusCode::from_u8(value).unwrap());
			assert_eq!(status.category(), category);
		}
	}

	#[test]
	fn test_raw_resolution() {
		let statuses = [
			(StatusCode::INPUT_EXPECTED, 10),
			(StatusCode::SENSITIVE_INPUT_EXPECTED, 11),
			(StatusCode::try_from(12).unwrap(), 12), // weird status value
			(StatusCode::SUCCESS, 20),
			(StatusCode::TEMPORARY_REDIRECTION, 30),
			(StatusCode::PERMANENT_REDIRECTION, 31),
			(StatusCode::TEMPORARY_FAILURE, 40),
			(StatusCode::SERVER_UNAVAILABLE, 41),
			(StatusCode::CGI_ERROR, 42),
			(StatusCode::PROXY_ERROR, 43),
			(StatusCode::SLOW_DOWN, 44),
			(StatusCode::PERMANENT_FAILURE, 50),
			(StatusCode::NOT_FOUND, 51),
			(StatusCode::GONE, 52),
			(StatusCode::PROXY_REQUEST_REFUSED, 53),
			(StatusCode::BAD_REQUEST, 59),
			(StatusCode::CERTIFICATE_REQUIRED, 60),
			(StatusCode::CERTIFICATE_NOT_AUTHORIZED, 61),
			(StatusCode::CERTIFICATE_NOT_VALID, 62),
		];

		for (status, raw) in statuses {
			assert_eq!(status, raw);

			let code: u8 = status.into();
			assert_eq!(code, raw);
		}
	}
}