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
/*!
# Dowser: Extension
*/

use dactyl::{
	NiceU16,
	NiceU32,
};
use std::{
	hash::{
		Hash,
		Hasher,
	},
	path::Path,
};

#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;



#[cfg(unix)]
/// # Path to Bytes.
///
/// Convert a path to a slice.
macro_rules! path_slice {
	($path:ident) => ($path.as_ref().as_os_str().as_bytes());
}

#[cfg(not(unix))]
/// # Path to Bytes.
///
/// Convert a path to a slice. On Windows this may not be strictly correct,
/// but hopefully good enough to match an extension.
macro_rules! path_slice {
	($path:ident) => ($path.as_ref().to_string_lossy().as_bytes());
}



#[derive(Debug, Clone, Copy)]
/// # Extension.
///
/// This enum can be used to efficiently check a file path's extension case-
/// insensitively against a hard-coded reference extension. It is likely
/// overkill in most situations, but if you're looking to optimize the
/// filtering of large path lists, this can turn those painful nanosecond
/// operations into pleasant picosecond ones!
///
/// The magic is largely down to storing values as `u16` or `u32` integers and
/// comparing those (rather than byte slices or `OsStr`), and not messing
/// around with the path `Components` iterator. (Note, this is done using the
/// safe `u*::from_le_bytes()` methods rather than casting chicanery.)
///
/// At the moment, only extensions sized between 2-4 bytes are supported as
/// those sizes are the most common and also translate perfectly to primitives,
/// but larger values may be added in the future.
///
/// ## Reference Constructors.
///
/// A "reference" extension is one known to you ahead of time, i.e. what you're
/// looking for. These can be constructed using the constant [`Extension::new2`],
/// [`Extension::new3`], and [`Extension::new4`] methods.
///
/// Because these are "known" values, no logical validation is performed. If
/// you do something silly like mix case or type them incorrectly, equality
/// tests will fail. You'd only be hurting yourself!
///
/// ```
/// use dowser::Extension;
///
/// const EXT2: Extension = Extension::new2(*b"gz");
/// const EXT3: Extension = Extension::new3(*b"png");
/// const EXT4: Extension = Extension::new4(*b"html");
/// ```
///
/// The main idea is you'll pre-compute these values and compare unknown
/// runtime values against them later.
///
/// ## Runtime Constructors.
///
/// A "runtime" extension, for lack of a better adjective, is a value you
/// don't know ahead of time, e.g. from a user-supplied path. These can be
/// constructed using the [`Extension::try_from2`], [`Extension::try_from3`],
/// and [`Extension::try_from4`] methods, which accept any `AsRef<Path>`
/// argument.
///
/// The method you choose should match the length you're looking for. For
/// example, if you're hoping for a PNG, use [`Extension::try_from3`].
///
/// ```
/// use dowser::Extension;
///
/// const EXT3: Extension = Extension::new3(*b"png");
/// assert_eq!(Extension::try_from3("/path/to/IMAGE.PNG"), Some(EXT3));
/// assert_eq!(Extension::try_from3("/path/to/doc.html"), None);
/// ```
///
/// ## Examples
///
/// To filter a list of image paths with the standard library — say, matching
/// PNGs — you would do something like:
///
/// ```no_run
/// use std::ffi::OsStr;
/// use std::path::PathBuf;
///
/// // Imagine this is much longer…
/// let paths = vec![PathBuf::from("/path/to/image.png")];
///
/// paths.iter()
///     .filter(|p| p.extension()
///         .map_or(false, |e| e.eq_ignore_ascii_case(OsStr::new("png")))
///     )
///     .for_each(|p| todo!());
/// ```
///
/// Using [`Extension`] instead, the same operation looks like:
///
/// ```no_run
/// use dowser::Extension;
/// use std::path::PathBuf;
///
/// // Imagine this is much longer…
/// let paths = vec![PathBuf::from("/path/to/image.png")];
///
/// // The reference extension.
/// const EXT: Extension = Extension::new3(*b"png");
///
/// paths.iter()
///     .filter(|p| Extension::try_from3(p).map_or(false, |e| e == EXT))
///     .for_each(|p| todo!());
/// ```
pub enum Extension {
	/// # 2-char Extension.
	///
	/// Like `.gz`.
	Ext2(u16),

	/// # 3-char Extension.
	///
	/// Like `.png`.
	Ext3(u32),

	/// # 4-char Extension.
	///
	/// Like `.html`.
	Ext4(u32),
}

impl Eq for Extension {}

impl Hash for Extension {
	#[inline]
	fn hash<H: Hasher>(&self, state: &mut H) {
		match *self {
			Self::Ext2(n) => { state.write_u16(n); },
			Self::Ext3(n) | Self::Ext4(n) => { state.write_u32(n); },
		}
	}
}

impl PartialEq for Extension {
	#[inline]
	fn eq(&self, other: &Self) -> bool {
		match (*self, *other) {
			(Self::Ext2(e1), Self::Ext2(e2)) => e1 == e2,
			(Self::Ext3(e1), Self::Ext3(e2)) |
			(Self::Ext4(e1), Self::Ext4(e2)) => e1 == e2,
			_ => false,
		}
	}
}

impl<P> PartialEq<P> for Extension
where P: AsRef<Path> {
	#[inline]
	/// # Path Equality.
	///
	/// When there's just one extension and one path to check, you can compare
	/// them directly (extension first).
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new4(*b"html");
	///
	/// assert_eq!(MY_EXT, "/path/to/index.html");
	/// assert_ne!(MY_EXT, "/path/to/image.jpeg");
	/// ```
	fn eq(&self, other: &P) -> bool {
		match self {
			Self::Ext2(_) => Self::try_from2(other),
			Self::Ext3(_) => Self::try_from3(other),
			Self::Ext4(_) => Self::try_from4(other),
		}
			.map_or(false, |e| e.eq(self))
	}
}

/// # Unchecked Instantiation.
impl Extension {
	#[must_use]
	#[inline]
	/// # New Unchecked (2).
	///
	/// Create a new [`Extension`], unchecked, from two bytes, e.g. `*b"gz"`.
	/// This should be lowercase and not include a period.
	///
	/// This method is intended for known values that you want to check
	/// unknown values against. Sanity-checking is traded for performance, but
	/// you're only hurting yourself if you misuse it.
	///
	/// For compile-time generation, see [`Extension::codegen`].
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	/// const MY_EXT: Extension = Extension::new2(*b"gz");
	/// ```
	pub const fn new2(src: [u8; 2]) -> Self {
		Self::Ext2(u16::from_le_bytes(src))
	}

	#[must_use]
	#[inline]
	/// # New Unchecked (3).
	///
	/// Create a new [`Extension`], unchecked, from three bytes, e.g. `*b"gif"`.
	/// This should be lowercase and not include a period.
	///
	/// This method is intended for known values that you want to check
	/// unknown values against. Sanity-checking is traded for performance, but
	/// you're only hurting yourself if you misuse it.
	///
	/// For compile-time generation, see [`Extension::codegen`].
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	/// const MY_EXT: Extension = Extension::new3(*b"gif");
	/// ```
	pub const fn new3(src: [u8; 3]) -> Self {
		Self::Ext3(u32::from_le_bytes([b'.', src[0], src[1], src[2]]))
	}

	#[must_use]
	#[inline]
	/// # New Unchecked (4).
	///
	/// Create a new [`Extension`], unchecked, from four bytes, e.g. `*b"html"`.
	/// This should be lowercase and not include a period.
	///
	/// This method is intended for known values that you want to check
	/// unknown values against. Sanity-checking is traded for performance, but
	/// you're only hurting yourself if you misuse it.
	///
	/// For compile-time generation, see [`Extension::codegen`].
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	/// const MY_EXT: Extension = Extension::new4(*b"html");
	/// ```
	pub const fn new4(src: [u8; 4]) -> Self {
		Self::Ext4(u32::from_le_bytes(src))
	}
}

/// # From Paths.
impl Extension {
	#[must_use]
	#[inline]
	/// # Try From Path (2).
	///
	/// This method is used to (try to) pull a 2-byte extension from a file
	/// path. This requires that the path be at least 4 bytes, with anything
	/// but a forward/backward slash at `[len - 4]` and a dot at `[len - 3]`.
	///
	/// If successful, it will return an [`Extension::Ext2`] that can be
	/// compared against your reference [`Extension`]. Casing will be fixed
	/// automatically.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new2(*b"gz");
	/// assert_eq!(Extension::try_from2("/path/to/file.gz"), Some(MY_EXT));
	/// assert_eq!(Extension::try_from2("/path/to/file.GZ"), Some(MY_EXT));
	///
	/// assert_eq!(Extension::try_from2("/path/to/file.png"), None);
	/// assert_ne!(Extension::try_from2("/path/to/file.br"), Some(MY_EXT));
	/// ```
	pub fn try_from2<P>(path: P) -> Option<Self>
	where P: AsRef<Path> {
		Self::slice_ext2(path_slice!(path))
	}

	#[must_use]
	#[inline]
	/// # Try From Path (3).
	///
	/// This method is used to (try to) pull a 3-byte extension from a file
	/// path. This requires that the path be at least 5 bytes, with anything
	/// but a forward/backward slash at `[len - 5]` and a dot at `[len - 4]`.
	///
	/// If successful, it will return an [`Extension::Ext3`] that can be
	/// compared against your reference [`Extension`]. Casing will be fixed
	/// automatically.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new3(*b"png");
	/// assert_eq!(Extension::try_from3("/path/to/file.png"), Some(MY_EXT));
	/// assert_eq!(Extension::try_from3("/path/to/FILE.PNG"), Some(MY_EXT));
	///
	/// assert_eq!(Extension::try_from3("/path/to/file.html"), None);
	/// assert_ne!(Extension::try_from3("/path/to/file.jpg"), Some(MY_EXT));
	/// ```
	pub fn try_from3<P>(path: P) -> Option<Self>
	where P: AsRef<Path> {
		Self::slice_ext3(path_slice!(path))
	}

	#[must_use]
	#[inline]
	/// # Try From Path (4).
	///
	/// This method is used to (try to) pull a 4-byte extension from a file
	/// path. This requires that the path be at least 6 bytes, with anything
	/// but a forward/backward slash at `[len - 6]` and a dot at `[len - 5]`.
	///
	/// If successful, it will return an [`Extension::Ext4`] that can be
	/// compared against your reference [`Extension`]. Casing will be fixed
	/// automatically.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new4(*b"html");
	/// assert_eq!(Extension::try_from4("/path/to/file.html"), Some(MY_EXT));
	/// assert_eq!(Extension::try_from4("/path/to/FILE.HTML"), Some(MY_EXT));
	///
	/// assert_eq!(Extension::try_from4("/path/to/file.png"), None);
	/// assert_ne!(Extension::try_from4("/path/to/file.xhtm"), Some(MY_EXT));
	/// ```
	pub fn try_from4<P>(path: P) -> Option<Self>
	where P: AsRef<Path> {
		Self::slice_ext4(path_slice!(path))
	}
}

/// # From Slices.
impl Extension {
	#[inline]
	#[must_use]
	/// # Extension Slice (2).
	///
	/// This method is used to (try to) pull a 2-byte extension from a file
	/// path in slice form. This requires that the path be at least 4 bytes,
	/// with anything but a forward/backward slash at `[len - 4]` and a dot at
	/// `[len - 3]`.
	///
	/// If successful, it will return an [`Extension::Ext2`] that can be
	/// compared against your reference [`Extension`]. Casing will be fixed
	/// automatically.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new2(*b"gz");
	/// assert_eq!(Extension::slice_ext2(b"/path/to/file.gz"), Some(MY_EXT));
	/// assert_eq!(Extension::slice_ext2(b"/path/to/file.GZ"), Some(MY_EXT));
	///
	/// // Non-matches.
	/// assert_eq!(Extension::slice_ext2(b"/path/to/.gz"), None);
	/// assert_eq!(Extension::slice_ext2(b"/path/to\\.gz"), None);
	/// assert_eq!(Extension::slice_ext2(b"/path/to/file.png"), None);
	/// assert_ne!(Extension::slice_ext2(b"/path/to/file.br"), Some(MY_EXT));
	/// ```
	pub const fn slice_ext2(path: &[u8]) -> Option<Self> {
		if let [.., 0..=46 | 48..=91 | 93..=255, b'.', a, b] = path {
			Some(Self::Ext2(u16::from_le_bytes([
				a.to_ascii_lowercase(),
				b.to_ascii_lowercase(),
			])))
		}
		else { None }
	}

	#[inline]
	#[must_use]
	/// # Extension Slice (3).
	///
	/// This method is used to (try to) pull a 3-byte extension from a file
	/// path in slice form. This requires that the path be at least 5 bytes,
	/// with anything but a forward/backward slash at `[len - 5]` and a dot at
	/// `[len - 4]`.
	///
	/// If successful, it will return an [`Extension::Ext3`] that can be
	/// compared against your reference [`Extension`]. Casing will be fixed
	/// automatically.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new3(*b"png");
	/// assert_eq!(Extension::slice_ext3(b"/path/to/file.png"), Some(MY_EXT));
	/// assert_eq!(Extension::slice_ext3(b"/path/to/FILE.PNG"), Some(MY_EXT));
	///
	/// // Non-matches.
	/// assert_eq!(Extension::slice_ext3(b"/path/to/.png"), None);
	/// assert_eq!(Extension::slice_ext3(b"/path/to\\.png"), None);
	/// assert_eq!(Extension::slice_ext3(b"/path/to/file.html"), None);
	/// assert_ne!(Extension::slice_ext3(b"/path/to/file.jpg"), Some(MY_EXT));
	/// ```
	pub const fn slice_ext3(path: &[u8]) -> Option<Self> {
		if let [.., 0..=46 | 48..=91 | 93..=255, b'.', a, b, c] = path {
			Some(Self::Ext3(u32::from_le_bytes([
				b'.',
				a.to_ascii_lowercase(),
				b.to_ascii_lowercase(),
				c.to_ascii_lowercase(),
			])))
		}
		else { None }
	}

	#[inline]
	#[must_use]
	/// # Extension Slice (4).
	///
	/// This method is used to (try to) pull a 4-byte extension from a file
	/// path in slice form. This requires that the path be at least 6 bytes,
	/// with anything but a forward/backward slash at `[len - 6]` and a dot at
	/// `[len - 5]`.
	///
	/// If successful, it will return an [`Extension::Ext4`] that can be
	/// compared against your reference [`Extension`]. Casing will be fixed
	/// automatically.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// const MY_EXT: Extension = Extension::new4(*b"html");
	/// assert_eq!(Extension::slice_ext4(b"/path/to/file.html"), Some(MY_EXT));
	/// assert_eq!(Extension::slice_ext4(b"/path/to/FILE.HTML"), Some(MY_EXT));
	///
	/// // Non-matches.
	/// assert_eq!(Extension::slice_ext2(b"/path/to/.html"), None);
	/// assert_eq!(Extension::slice_ext2(b"/path/to\\.html"), None);
	/// assert_eq!(Extension::slice_ext4(b"/path/to/file.png"), None);
	/// assert_ne!(Extension::slice_ext4(b"/path/to/file.xhtm"), Some(MY_EXT));
	/// ```
	pub const fn slice_ext4(path: &[u8]) -> Option<Self> {
		if let [.., 0..=46 | 48..=91 | 93..=255, b'.', a, b, c, d] = path {
			Some(Self::Ext4(u32::from_le_bytes([
				a.to_ascii_lowercase(),
				b.to_ascii_lowercase(),
				c.to_ascii_lowercase(),
				d.to_ascii_lowercase(),
			])))
		}
		else { None }
	}

	#[must_use]
	/// # Slice Extension.
	///
	/// This returns the file extension portion of a path as a byte slice,
	/// similar to [`std::path::Path::extension`], but faster since it is dealing with
	/// straight bytes.
	///
	/// The extension is found by jumping to the last period, ensuring the byte
	/// _before_ that period is not a path separator, and that there are one or
	/// more bytes _after_ that period (none of which are path separators).
	///
	/// If the above are all good, a slice containing everything after that
	/// last period is returned.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// // Uppercase in, uppercase out.
	/// assert_eq!(
	///     Extension::slice_ext(b"/path/to/IMAGE.JPEG"),
	///     Some(&b"JPEG"[..])
	/// );
	///
	/// // Lowercase in, lowercase out.
	/// assert_eq!(
	///     Extension::slice_ext(b"/path/to/file.docx"),
	///     Some(&b"docx"[..])
	/// );
	///
	/// // These are all bad, though:
	/// assert_eq!(
	///     Extension::slice_ext(b"/path/to/.hide"),
	///     None
	/// );
	/// assert_eq!(
	///     Extension::slice_ext(b"/path/to/"),
	///     None
	/// );
	/// assert_eq!(
	///     Extension::slice_ext(b"/path/to/file."),
	///     None
	/// );
	/// ```
	pub fn slice_ext(src: &[u8]) -> Option<&[u8]> {
		let dot = src.iter().rposition(|&b| matches!(b, b'.' | b'/' | b'\\'))?;

		if
			0 < dot &&
			dot + 1 < src.len() &&
			src[dot] == b'.' &&
			// Safety: we tested 0 < dot, so the subtraction won't overflow.
			! matches!(src[dot - 1], b'/' | b'\\')
		{
			Some(&src[dot + 1..])
		}
		else { None }
	}
}

/// # Codegen Helpers.
impl Extension {
	#[allow(clippy::needless_doctest_main)] // For demonstration!
	#[must_use]
	/// # Codegen Helper.
	///
	/// This _compile-time_ method can be used in a `build.rs` script to
	/// generate a pre-computed [`Extension`] value of any supported length
	/// (2-4 bytes).
	///
	/// Unlike the runtime methods, this will automatically fix case and period
	/// inconsistencies, but ideally you should still pass it just the letters,
	/// in lowercase, because you have the power to do so. Haha.
	///
	/// ## Examples
	///
	/// ```
	/// use dowser::Extension;
	///
	/// // This is what it looks like.
	/// assert_eq!(
	///     Extension::codegen(b"js"),
	///     "Extension::Ext2(29_546_u16)"
	/// );
	/// assert_eq!(
	///     Extension::codegen(b"jpg"),
	///     "Extension::Ext3(1_735_420_462_u32)"
	/// );
	/// assert_eq!(
	///     Extension::codegen(b"html"),
	///     "Extension::Ext4(1_819_112_552_u32)"
	/// );
	/// ```
	///
	/// In a typical `build.rs` workflow, you'd be building up a string of
	/// other code around it, and saving it all to a file, like:
	///
	/// ```no_run
	/// use dowser::Extension;
	/// use std::fs::File;
	/// use std::io::Write;
	/// use std::path::PathBuf;
	///
	/// fn main() {
	///     let out = format!(
	///         "const MY_EXT: Extension = {};",
	///         Extension::codegen(b"jpg")
	///     );
	///
	///     let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap())
	///         .join("compile-time-vars.rs");
	///     let mut f = File::create(out_path).unwrap();
	///     f.write_all(out.as_bytes()).unwrap();
	///     f.flush().unwrap();
	/// }
	///
	/// ```
	///
	/// Then in your main program, say `lib.rs`, you'd toss an `include!()` to
	/// that file to import the code _as code_, like:
	///
	/// ```no_run,ignore
	/// use dowser::Extension;
	///
	/// include!(concat!(env!("OUT_DIR"), "/compile-time-vars.rs"));
	/// ```
	///
	/// Et voilà, you've saved yourself a nanosecond of runtime effort! Haha.
	///
	/// ## Panics
	///
	/// This will panic if the extension (minus punctuation) is not 2-4 bytes
	/// or contains whitespace or path separators.
	pub fn codegen(mut src: &[u8]) -> String {
		// Jump past the last period, if any.
		if let Some(pos) = src.iter().rposition(|b| b'.'.eq(b)) {
			assert!(pos + 2 < src.len(), "Extensions must be 2-4 bytes (not including punctuation).");
			src = &src[pos + 1..];
		}

		// Make sure there is no whitespace.
		assert!(
			src.iter().all(|b| ! b.is_ascii_whitespace() && b'/'.ne(b) && b'\\'.ne(b)),
			"Extensions cannot contain whitespace or path separators."
		);

		match src.len() {
			2 => [
				"Extension::Ext2(",
				NiceU16::with_separator(
					u16::from_le_bytes([
						src[0].to_ascii_lowercase(),
						src[1].to_ascii_lowercase(),
					]),
					b'_',
				).as_str(),
				"_u16)",
			].concat(),
			3 => [
				"Extension::Ext3(",
				NiceU32::with_separator(
					u32::from_le_bytes([
						b'.',
						src[0].to_ascii_lowercase(),
						src[1].to_ascii_lowercase(),
						src[2].to_ascii_lowercase(),
					]),
					b'_',
				).as_str(),
				"_u32)",
			].concat(),
			4 => [
				"Extension::Ext4(",
				NiceU32::with_separator(
					u32::from_le_bytes([
						src[0].to_ascii_lowercase(),
						src[1].to_ascii_lowercase(),
						src[2].to_ascii_lowercase(),
						src[3].to_ascii_lowercase(),
					]),
					b'_',
				).as_str(),
				"_u32)",
			].concat(),
			_ => panic!("Extensions must be 2-4 bytes (not including punctuation)."),
		}
	}
}




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

	#[test]
	fn t_codegen() {
		assert_eq!(Extension::codegen(b"js"), "Extension::Ext2(29_546_u16)");
		assert_eq!(Extension::codegen(b"JS"), "Extension::Ext2(29_546_u16)");
		assert_eq!(Extension::codegen(b"/path/to/file.JS"), "Extension::Ext2(29_546_u16)");

		assert_eq!(Extension::codegen(b"jpg"), "Extension::Ext3(1_735_420_462_u32)");
		assert_eq!(Extension::codegen(b"JPG"), "Extension::Ext3(1_735_420_462_u32)");
		assert_eq!(Extension::codegen(b".jpg"), "Extension::Ext3(1_735_420_462_u32)");

		assert_eq!(Extension::codegen(b"html"), "Extension::Ext4(1_819_112_552_u32)");
		assert_eq!(Extension::codegen(b"htML"), "Extension::Ext4(1_819_112_552_u32)");
		assert_eq!(Extension::codegen(b"index.html"), "Extension::Ext4(1_819_112_552_u32)");
	}

	#[test]
	#[should_panic]
	fn t_codegen_bad1() { let _res = Extension::codegen(b""); }

	#[test]
	#[should_panic]
	fn t_codegen_bad2() { let _res = Extension::codegen(b"xhtml"); }

	#[test]
	#[should_panic]
	fn t_codegen_bad3() { let _res = Extension::codegen(b"x./html"); }
}