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
//! Internal utility implementations replacing small third-party crates.
//!
//! This module provides pure-std implementations of `hex`, `base64`,
//! `percent-encoding` and `temp-dir` so that the crate no longer needs to
//! depend on those external crates. The functions here are also re-exported
//! publicly so downstream users may use them directly via `doe::utils::`.
///
/// # Examples
///
/// ```ignore
/// use doe::utils;
///
/// // hex
/// assert_eq!(utils::hex::encode(b"hello"), "68656c6c6f");
///
/// // base64
/// assert_eq!(utils::base64::encode_standard(b"hello"), "aGVsbG8=");
///
/// // percent
/// assert_eq!(
/// utils::percent::encode("a b", utils::percent::EncodeSet::NonAlphanumeric),
/// "a%20b"
/// );
/// ```
#[allow(warnings)]
/// Hexadecimal encoding/decoding (replaces the `hex` crate).
pub mod hex {
/// Error returned by [`decode`] when the input is not valid hex.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidHex {
/// 1-based position in the input where the problem occurred.
pub index: usize,
/// Human-readable description of the problem.
pub reason: &'static str,
}
impl std::fmt::Display for InvalidHex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid hex at index {}: {}", self.index, self.reason)
}
}
impl std::error::Error for InvalidHex {}
const HEX_LOWER: [u8; 16] = *b"0123456789abcdef";
const HEX_UPPER: [u8; 16] = *b"0123456789ABCDEF";
/// Encodes `data` to a lowercase hexadecimal string.
pub fn encode<T: AsRef<[u8]>>(data: T) -> String {
encode_with(data, &HEX_LOWER)
}
/// Encodes `data` to an uppercase hexadecimal string.
pub fn encode_upper<T: AsRef<[u8]>>(data: T) -> String {
encode_with(data, &HEX_UPPER)
}
fn encode_with<T: AsRef<[u8]>>(data: T, table: &[u8; 16]) -> String {
let bytes = data.as_ref();
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
out.push(table[(b >> 4) as usize] as char);
out.push(table[(b & 0x0f) as usize] as char);
}
out
}
/// Decodes a hexadecimal string (upper or lower case) into bytes.
///
/// Whitespace (`' '`, `'\t'`, `'\n'`, `'\r'`, `'\x0c'`) is ignored,
/// matching the tolerant behaviour of the original `hex` crate for the
/// common "0x" prefix use-case is intentionally NOT supported to keep
/// semantics explicit.
pub fn decode<T: AsRef<[u8]>>(data: T) -> Result<Vec<u8>, InvalidHex> {
let bytes = data.as_ref();
// Build a lookup table: 255 = invalid digit.
const fn build_table() -> [u8; 256] {
let mut t = [255u8; 256];
let mut i = 0;
while i < 10 {
t[b'0' as usize + i] = i as u8;
i += 1;
}
let mut i = 0;
while i < 6 {
t[b'a' as usize + i] = (10 + i) as u8;
t[b'A' as usize + i] = (10 + i) as u8;
i += 1;
}
t
}
const DIGIT: [u8; 256] = build_table();
let mut out = Vec::with_capacity(bytes.len() / 2);
let mut nibbles: Vec<u8> = Vec::with_capacity(bytes.len());
for (i, &b) in bytes.iter().enumerate() {
match b {
b' ' | b'\t' | b'\n' | b'\r' | 0x0c => continue,
_ => {}
}
let v = DIGIT[b as usize];
if v == 255 {
return Err(InvalidHex {
index: i,
reason: "invalid hexadecimal character",
});
}
nibbles.push(v);
}
if nibbles.len() % 2 != 0 {
return Err(InvalidHex {
index: bytes.len(),
reason: "odd number of hex digits",
});
}
for pair in nibbles.chunks(2) {
out.push((pair[0] << 4) | pair[1]);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encode_lowercase() {
assert_eq!(encode(b"hello"), "68656c6c6f");
assert_eq!(encode(b""), "");
assert_eq!(encode(b"\x00\xff"), "00ff");
}
#[test]
fn encode_uppercase() {
assert_eq!(encode_upper(b"hello"), "68656C6C6F");
assert_eq!(encode_upper(b"\x00\xff"), "00FF");
}
#[test]
fn decode_basic() {
assert_eq!(decode("68656c6c6f").unwrap(), b"hello");
assert_eq!(decode("68656C6C6F").unwrap(), b"hello");
assert_eq!(decode("").unwrap(), Vec::<u8>::new());
}
#[test]
fn decode_ignores_whitespace() {
assert_eq!(decode("68 65\n6c").unwrap(), b"hel");
}
#[test]
fn decode_odd_length_errors() {
assert!(decode("abc").is_err());
}
#[test]
fn decode_invalid_char_errors() {
assert!(decode("68g5").is_err());
}
#[test]
fn roundtrip() {
let data: Vec<u8> = (0..=255).collect();
assert_eq!(decode(encode(&data)).unwrap(), data);
assert_eq!(decode(encode_upper(&data)).unwrap(), data);
}
}
}
/// Base64 encoding/decoding (replaces the `base64` crate).
///
/// Implements RFC 4648 for the Standard and URL-safe alphabets, with
/// optional padding.
pub mod base64 {
/// Error returned by [`decode`] on malformed input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidBase64 {
/// 1-based position in the input where the problem occurred.
pub index: usize,
/// Human-readable description of the problem.
pub reason: &'static str,
}
impl std::fmt::Display for InvalidBase64 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid base64 at index {}: {}", self.index, self.reason)
}
}
impl std::error::Error for InvalidBase64 {}
/// The alphabet to use for encoding/decoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alphabet {
/// Standard alphabet: `A-Za-z0-9+/`
Standard,
/// URL-safe alphabet: `A-Za-z0-9-_`
UrlSafe,
}
const STANDARD: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const URL_SAFE: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
fn table_for(alphabet: Alphabet) -> &'static [u8; 64] {
match alphabet {
Alphabet::Standard => STANDARD,
Alphabet::UrlSafe => URL_SAFE,
}
}
/// Encodes `data` with the given alphabet, optionally appending `=`
/// padding.
pub fn encode<T: AsRef<[u8]>>(data: T, alphabet: Alphabet, padded: bool) -> String {
let data = data.as_ref();
let table = table_for(alphabet);
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b0 = chunk[0];
let b1 = if chunk.len() > 1 { chunk[1] } else { 0 };
let b2 = if chunk.len() > 2 { chunk[2] } else { 0 };
let n = ((b0 as u32) << 16) | ((b1 as u32) << 8) | (b2 as u32);
out.push(table[((n >> 18) & 0x3f) as usize] as char);
out.push(table[((n >> 12) & 0x3f) as usize] as char);
if chunk.len() > 1 {
out.push(table[((n >> 6) & 0x3f) as usize] as char);
} else if padded {
out.push('=');
}
if chunk.len() > 2 {
out.push(table[(n & 0x3f) as usize] as char);
} else if padded {
out.push('=');
}
}
out
}
/// Builds a combined inverse lookup table for `alphabet`.
/// Values `>= 64` mean "not a valid symbol". Position 256 (`=`) maps to
/// a sentinel handled separately.
fn build_inverse(alphabet: Alphabet) -> [u8; 256] {
let mut inv = [255u8; 256];
let table = table_for(alphabet);
for (i, &c) in table.iter().enumerate() {
inv[c as usize] = i as u8;
}
// Padding is always valid regardless of alphabet.
inv[b'=' as usize] = 64;
inv
}
/// Decodes base64 input. Whitespace (`\n`, `\r`, ` `, `\t`) is ignored.
/// Padding is optional.
pub fn decode<T: AsRef<[u8]>>(input: T, alphabet: Alphabet) -> Result<Vec<u8>, InvalidBase64> {
let input = input.as_ref();
let inv = build_inverse(alphabet);
let mut nibbles: Vec<u8> = Vec::with_capacity(input.len());
let mut padding = 0usize;
for (i, &b) in input.iter().enumerate() {
match b {
b' ' | b'\t' | b'\n' | b'\r' => continue,
b'=' => {
padding += 1;
nibbles.push(64);
continue;
}
_ => {}
}
if padding > 0 {
return Err(InvalidBase64 {
index: i,
reason: "non-padding character after padding",
});
}
let v = inv[b as usize];
if v == 255 {
return Err(InvalidBase64 {
index: i,
reason: "invalid base64 character",
});
}
nibbles.push(v);
}
if nibbles.is_empty() {
return Ok(Vec::new());
}
// For unpadded input, pad conceptually to a multiple of 4 with zeros,
// but track how many trailing sextets are real data.
if !nibbles.len().is_multiple_of(4) {
// Only valid if there was no explicit padding and the input was
// unpadded: lengths 2 or 3 mod 4 are acceptable, 1 mod 4 is not.
if nibbles.len() % 4 == 1 {
return Err(InvalidBase64 {
index: input.len(),
reason: "invalid base64 length",
});
}
}
let mut out = Vec::with_capacity(nibbles.len() / 4 * 3);
for chunk in nibbles.chunks(4) {
let mut n = 0u32;
let mut group_len = chunk.len();
for &v in chunk {
if v == 64 {
// padding / placeholder
group_len = group_len.saturating_sub(1);
n <<= 6;
} else {
n = (n << 6) | v as u32;
}
}
// number of real sextets in this group
let real = chunk.iter().filter(|&&v| v != 64).count();
// pad shifts to align to 24 bits
n <<= (4 - chunk.len()) as u32 * 6;
if real >= 2 {
out.push(((n >> 16) & 0xff) as u8);
}
if real >= 3 {
out.push(((n >> 8) & 0xff) as u8);
}
if real >= 4 {
out.push((n & 0xff) as u8);
}
let _ = group_len;
}
Ok(out)
}
/// Encodes with the standard alphabet and `=` padding.
pub fn encode_standard<T: AsRef<[u8]>>(data: T) -> String {
encode(data, Alphabet::Standard, true)
}
/// Encodes with the standard alphabet and no padding.
pub fn encode_standard_no_pad<T: AsRef<[u8]>>(data: T) -> String {
encode(data, Alphabet::Standard, false)
}
/// Encodes with the URL-safe alphabet and `=` padding.
pub fn encode_url_safe<T: AsRef<[u8]>>(data: T) -> String {
encode(data, Alphabet::UrlSafe, true)
}
/// Decodes standard-alphabet base64.
pub fn decode_standard<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, InvalidBase64> {
decode(input, Alphabet::Standard)
}
/// Decodes URL-safe-alphabet base64.
pub fn decode_url_safe<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, InvalidBase64> {
decode(input, Alphabet::UrlSafe)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_vectors_standard() {
assert_eq!(encode_standard(b""), "");
assert_eq!(encode_standard(b"f"), "Zg==");
assert_eq!(encode_standard(b"fo"), "Zm8=");
assert_eq!(encode_standard(b"foo"), "Zm9v");
assert_eq!(encode_standard(b"foob"), "Zm9vYg==");
assert_eq!(encode_standard(b"fooba"), "Zm9vYmE=");
assert_eq!(encode_standard(b"foobar"), "Zm9vYmFy");
assert_eq!(encode_standard(b"hello"), "aGVsbG8=");
assert_eq!(
encode_standard(b"Hello, World!"),
"SGVsbG8sIFdvcmxkIQ=="
);
}
#[test]
fn decode_known_vectors() {
assert_eq!(decode_standard("").unwrap(), b"");
assert_eq!(decode_standard("Zg==").unwrap(), b"f");
assert_eq!(decode_standard("Zm8=").unwrap(), b"fo");
assert_eq!(decode_standard("Zm9v").unwrap(), b"foo");
assert_eq!(decode_standard("Zm9vYg==").unwrap(), b"foob");
assert_eq!(decode_standard("Zm9vYmE=").unwrap(), b"fooba");
assert_eq!(decode_standard("Zm9vYmFy").unwrap(), b"foobar");
assert_eq!(decode_standard("aGVsbG8=").unwrap(), b"hello");
}
#[test]
fn decode_no_padding() {
assert_eq!(decode_standard("Zm9vYmFy").unwrap(), b"foobar");
assert_eq!(decode_standard("Zm9v").unwrap(), b"foo");
}
#[test]
fn url_safe_differs_at_62_63() {
// bytes 0xfb 0xff produce sextets 62 and 63
let data = [0xfb, 0xff];
let std = encode_standard(&data);
let url = encode_url_safe(&data);
assert!(std.contains('+') || std.contains('/'));
assert!(url.contains('-') || url.contains('_'));
assert_ne!(std, url);
assert_eq!(decode_standard(&std).unwrap(), data);
assert_eq!(decode_url_safe(&url).unwrap(), data);
}
#[test]
fn decode_ignores_whitespace() {
assert_eq!(decode_standard("Zm9v\nYmFy").unwrap(), b"foobar");
}
#[test]
fn invalid_input_errors() {
assert!(decode_standard("Zm9!").is_err());
assert!(decode_standard("Z").is_err()); // length %4 == 1
}
#[test]
fn roundtrip_all_lengths() {
let data: Vec<u8> = (0..=200).flat_map(|i| vec![i as u8; i]).collect();
assert_eq!(decode_standard(encode_standard(&data)).unwrap(), data);
assert_eq!(
decode_standard(encode_standard_no_pad(&data)).unwrap(),
data
);
assert_eq!(decode_url_safe(encode_url_safe(&data)).unwrap(), data);
}
}
}
/// Percent-encoding for URLs (replaces the `percent-encoding` crate).
pub mod percent {
/// The set of characters that should be percent-encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncodeSet {
/// Only ASCII control characters (0x00-0x1F) and 0x7F. Matches the
/// `CONTROLS` set from `percent-encoding`.
Controls,
/// Everything except ASCII alphanumeric characters. Matches the
/// `NON_ALPHANUMERIC` set from `percent-encoding`.
NonAlphanumeric,
}
#[inline]
fn should_encode(c: u8, set: EncodeSet) -> bool {
match set {
EncodeSet::Controls => c < 0x20 || c == 0x7f,
EncodeSet::NonAlphanumeric => !c.is_ascii_alphanumeric(),
}
}
const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";
/// Percent-encodes `input` according to `set`. Operates on the raw UTF-8
/// bytes, matching `utf8_percent_encode`.
pub fn encode(input: &str, set: EncodeSet) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(bytes.len());
for &b in bytes {
if should_encode(b, set) {
out.push('%');
out.push(HEX_UPPER[(b >> 4) as usize] as char);
out.push(HEX_UPPER[(b & 0x0f) as usize] as char);
} else {
out.push(b as char);
}
}
out
}
/// Error returned by [`decode`] on malformed percent-encoding or invalid
/// UTF-8.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidPercent {
/// 1-based position in the input where the problem occurred.
pub index: usize,
/// Human-readable description of the problem.
pub reason: &'static str,
}
impl std::fmt::Display for InvalidPercent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"invalid percent-encoding at index {}: {}",
self.index, self.reason
)
}
}
impl std::error::Error for InvalidPercent {}
/// Decodes percent-encoded input (`%XX`) into a UTF-8 string.
pub fn decode(input: &str) -> Result<String, InvalidPercent> {
let bytes = input.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return Err(InvalidPercent {
index: i,
reason: "truncated percent-escape",
});
}
let h = hex_val(bytes[i + 1]).ok_or(InvalidPercent {
index: i + 1,
reason: "invalid hex digit after '%'",
})?;
let l = hex_val(bytes[i + 2]).ok_or(InvalidPercent {
index: i + 2,
reason: "invalid hex digit after '%'",
})?;
out.push((h << 4) | l);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).map_err(|_| InvalidPercent {
index: 0,
reason: "decoded bytes are not valid UTF-8",
})
}
fn hex_val(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encode_non_alphanumeric() {
assert_eq!(
encode("a b", EncodeSet::NonAlphanumeric),
"a%20b"
);
assert_eq!(encode("abc123", EncodeSet::NonAlphanumeric), "abc123");
assert_eq!(encode("", EncodeSet::NonAlphanumeric), "");
}
#[test]
fn encode_controls_only() {
// space is not a control char, so left as-is
assert_eq!(encode("a b", EncodeSet::Controls), "a b");
assert_eq!(encode("a\tb", EncodeSet::Controls), "a%09b");
}
#[test]
fn decode_basic() {
assert_eq!(decode("a%20b").unwrap(), "a b");
assert_eq!(decode("%E4%BD%A0%E5%A5%BD").unwrap(), "ä½ å¥½");
assert_eq!(decode("no-encoding-here").unwrap(), "no-encoding-here");
assert_eq!(decode("").unwrap(), "");
}
#[test]
fn decode_lowercase_hex() {
assert_eq!(decode("%e4%bd%a0").unwrap(), "ä½ ");
}
#[test]
fn decode_errors() {
assert!(decode("%2").is_err()); // truncated
assert!(decode("%ZZ").is_err()); // bad hex
}
#[test]
fn roundtrip_non_alphanumeric() {
let s = "Hello, 世界! a+b=c&d=1";
let enc = encode(s, EncodeSet::NonAlphanumeric);
assert_eq!(decode(&enc).unwrap(), s);
}
}
}
/// RAII temporary directory (replaces the `temp-dir` crate).
///
/// The directory is created with a unique name under the system temp
/// location and removed (recursively) when the value is dropped.
pub mod temp {
use std::path::{Path, PathBuf};
/// An RAII temporary directory. Created on construction and deleted on
/// drop.
#[derive(Debug)]
pub struct TempDir {
path: PathBuf,
}
impl TempDir {
/// Creates a new unique temporary directory.
pub fn new() -> std::io::Result<Self> {
Self::with_prefix("doe-temp")
}
/// Creates a new temporary directory whose name starts with `prefix`.
pub fn with_prefix(prefix: &str) -> std::io::Result<Self> {
let mut dir = std::env::temp_dir();
dir.push(format!(
"{}-{}-{}",
prefix,
std::process::id(),
unique_suffix()
));
std::fs::create_dir_all(&dir)?;
Ok(Self { path: dir })
}
/// Returns the path to the temporary directory.
pub fn path(&self) -> &Path {
&self.path
}
/// Consumes the `TempDir` and returns its path, **without** removing
/// the directory.
pub fn into_path(self) -> PathBuf {
let path = self.path.clone();
std::mem::forget(self);
path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// Generates a short, process-unique suffix using time and an atomic
/// counter, avoiding any feature dependencies.
fn unique_suffix() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
format!("{:x}{:x}", nanos, n)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_and_drop() {
let path;
{
let t = TempDir::new().unwrap();
path = t.path().to_path_buf();
assert!(path.is_dir());
std::fs::write(path.join("a.txt"), b"hi").unwrap();
}
assert!(!path.exists(), "temp dir should be removed on drop");
}
#[test]
fn into_path_keeps_dir() {
let path = {
let t = TempDir::new().unwrap();
t.into_path()
};
assert!(path.exists(), "into_path should keep the directory");
let _ = std::fs::remove_dir_all(&path);
}
#[test]
fn unique_names() {
let a = TempDir::new().unwrap();
let b = TempDir::new().unwrap();
assert_ne!(a.path(), b.path());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_public_api() {
assert_eq!(hex::encode(b"hello"), "68656c6c6f");
assert_eq!(hex::decode("68656c6c6f").unwrap(), b"hello");
}
#[test]
fn base64_public_api() {
assert_eq!(base64::encode_standard(b"hello"), "aGVsbG8=");
assert_eq!(
base64::decode_standard("aGVsbG8=").unwrap(),
b"hello"
);
}
#[test]
fn percent_public_api() {
let enc = percent::encode("a b", percent::EncodeSet::NonAlphanumeric);
assert_eq!(enc, "a%20b");
assert_eq!(percent::decode(&enc).unwrap(), "a b");
}
}