windows-namespace-request-sys 0.2.1

Owned, marshalable parameter sets for synchronous Win32 namespace calls.
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
// Copyright (c) Mike Grier.
// Copied from windows-file-enumeration-sys/src/path/tests.rs at 126eb5f.

//! Tests for the request path contract.

use super::*;
use std::env;

fn prepare_str(path: &str) -> Result<Wtf16String, PathError> {
    prepare(&Wtf16String::from(path)).map(PreparedPath::into_wtf16)
}

fn text(path: &Wtf16Str) -> String {
    path.to_string_lossy()
}

#[test]
fn an_empty_path_is_rejected() {
    let error = prepare(&Wtf16String::new()).expect_err("an empty path names nothing");
    assert_eq!(error.failure(), PathFailure::EmptyPath);
    assert_eq!(error.raw_os_error(), None);
}

#[test]
fn an_interior_nul_is_rejected() {
    // Win32 would stop at the NUL and open a shorter, different path.
    let path = Wtf16String::from_units(&[0x0043, 0x003A, 0x005C, 0x0000, 0x0061]);
    let error = prepare(&path).expect_err("an interior NUL truncates the path");
    assert_eq!(error.failure(), PathFailure::InteriorNul);
}

#[test]
fn a_verbatim_drive_path_is_kept_exactly() {
    let prepared = prepare_str(r"\\?\C:\Windows\System32").expect("fully qualified");
    assert_eq!(text(&prepared), r"\\?\C:\Windows\System32");
}

#[test]
fn a_verbatim_path_keeps_its_trailing_separator() {
    // In verbatim form a trailing separator is a literal component boundary,
    // not syntax this crate may tidy away.
    let prepared = prepare_str(r"\\?\C:\Windows\").expect("fully qualified");
    assert_eq!(text(&prepared), r"\\?\C:\Windows\");
}

#[test]
fn a_verbatim_path_keeps_dot_components_verbatim() {
    let prepared = prepare_str(r"\\?\C:\a\..\b").expect("fully qualified");
    assert_eq!(text(&prepared), r"\\?\C:\a\..\b");
}

#[test]
fn a_verbatim_path_may_exceed_max_path() {
    let long = format!(r"\\?\C:\{}", "a".repeat(400));
    let prepared = prepare_str(&long).expect("verbatim paths carry no MAX_PATH limit");
    assert_eq!(text(&prepared), long);
}

#[test]
fn a_verbatim_unc_path_is_accepted() {
    let prepared = prepare_str(r"\\?\UNC\server\share\dir").expect("fully qualified");
    assert_eq!(text(&prepared), r"\\?\UNC\server\share\dir");
    // The share alone, with no trailing component, is still a directory.
    prepare_str(r"\\?\UNC\server\share").expect("a share root is fully qualified");
}

#[test]
fn a_verbatim_volume_guid_path_is_accepted() {
    prepare_str(r"\\?\Volume{12345678-1234-1234-1234-123456789abc}\dir")
        .expect("a volume GUID names an absolute root");
}

#[test]
fn a_drive_relative_verbatim_path_is_rejected() {
    // `\\?\C:foo` is drive-*relative*, and verbatim parsing would treat the
    // whole thing as one literal name rather than resolving it.
    let error = prepare_str(r"\\?\C:foo").expect_err("not fully qualified");
    assert_eq!(error.failure(), PathFailure::NotFullyQualified);
}

#[test]
fn a_rootless_verbatim_path_is_rejected() {
    let error = prepare_str(r"\\?\name").expect_err("no root component");
    assert_eq!(error.failure(), PathFailure::NotFullyQualified);
}

#[test]
fn a_verbatim_path_with_an_empty_root_is_rejected() {
    let error = prepare_str(r"\\?\\dir").expect_err("the root component is empty");
    assert_eq!(error.failure(), PathFailure::NotFullyQualified);
}

#[test]
fn an_incomplete_verbatim_unc_path_is_rejected() {
    for path in [
        r"\\?\UNC\server",
        r"\\?\UNC\server\",
        r"\\?\UNC\\share",
        r"\\?\UNC\",
    ] {
        let error = prepare_str(path).expect_err("a server without a share names no filesystem");
        assert_eq!(
            error.failure(),
            PathFailure::NotFullyQualified,
            "for {path}"
        );
    }
}

#[test]
fn an_ordinary_absolute_path_is_resolved_and_kept() {
    let prepared = prepare_str(r"C:\Windows\System32").expect("resolvable");
    assert_eq!(text(&prepared), r"C:\Windows\System32");
}

#[test]
fn an_ordinary_path_is_normalised_by_win32() {
    // Unlike a verbatim path, an ordinary one is the form Win32 itself parses,
    // so resolving it here yields exactly what a later open would have used.
    let prepared = prepare_str(r"C:\Windows\..\Windows\System32").expect("resolvable");
    assert_eq!(text(&prepared), r"C:\Windows\System32");
}

#[test]
fn forward_slashes_are_normalised() {
    let prepared = prepare_str("C:/Windows/System32").expect("resolvable");
    assert_eq!(text(&prepared), r"C:\Windows\System32");
}

#[test]
fn a_relative_path_is_snapshotted_against_the_current_directory() {
    // The whole point of resolving at build time: the answer must not depend on
    // what the current directory happens to be when a worker later runs.
    let current = env::current_dir().expect("a current directory");
    let prepared = prepare_str("subdir").expect("resolvable");
    let expected = current.join("subdir");
    assert_eq!(text(&prepared), expected.to_string_lossy());
}

#[test]
fn an_ordinary_path_longer_than_max_path_is_rejected() {
    let long = format!(r"C:\{}", "a".repeat(400));
    let error = prepare_str(&long).expect_err("beyond the ordinary limit");
    assert_eq!(error.failure(), PathFailure::PathTooLong);
}

#[test]
fn a_relative_path_that_resolves_past_max_path_is_rejected() {
    // Short enough on input, too long once the current directory is prepended:
    // the limit has to be applied to the resolved form as well.
    let current = env::current_dir().expect("a current directory");
    let room = 259usize.saturating_sub(current.to_string_lossy().len());
    let error = prepare_str(&"a".repeat(room + 8)).expect_err("resolves past the ordinary limit");
    assert_eq!(error.failure(), PathFailure::PathTooLong);
}

#[test]
fn a_reserved_device_name_resolves_into_the_device_namespace() {
    // `NUL` is not a directory, but that is discovered when it is opened; the
    // path contract only has to produce a well-formed stored path.
    let prepared = prepare_str("NUL").expect("resolvable");
    assert_eq!(text(&prepared), r"\\.\NUL");
}

#[test]
fn a_device_namespace_path_is_resolved_rather_than_kept_verbatim() {
    // Only `\\?\` disables path parsing; `\\.\` is normalised like any other
    // ordinary form.
    let prepared = prepare_str(r"\\.\C:\Windows\..\Windows").expect("resolvable");
    assert_eq!(text(&prepared), r"\\.\C:\Windows");
}

// The cases below are new here rather than copied: they cover the surface this
// crate added around the relocated preparation.

#[test]
fn a_prepared_path_exposes_its_units_both_ways() {
    let prepared = prepare(&Wtf16String::from(r"\\?\C:\Windows")).expect("fully qualified");

    assert_eq!(prepared.as_wtf16().to_string_lossy(), r"\\?\C:\Windows");
    assert_eq!(
        prepared.into_wtf16().to_string_lossy(),
        r"\\?\C:\Windows",
        "borrowing and taking must agree"
    );
}

#[test]
fn a_prepared_path_is_comparable_and_cloneable() {
    let first = prepare(&Wtf16String::from(r"\\?\C:\Windows")).expect("fully qualified");
    let second = prepare(&Wtf16String::from(r"\\?\C:\Windows")).expect("fully qualified");
    let other = prepare(&Wtf16String::from(r"\\?\C:\Users")).expect("fully qualified");

    assert_eq!(first, second);
    assert_eq!(first, first.clone());
    assert_ne!(first, other);
}

#[test]
fn a_prepared_path_moves_across_threads() {
    const fn assert_send<T: Send>() {}
    const fn assert_sync<T: Sync>() {}

    assert_send::<PreparedPath>();
    assert_sync::<PreparedPath>();

    let prepared = prepare(&Wtf16String::from(r"\\?\C:\Windows")).expect("fully qualified");

    let observed = std::thread::spawn(move || prepared.as_wtf16().to_string_lossy())
        .join()
        .expect("the worker did not panic");

    assert_eq!(observed, r"\\?\C:\Windows");
}

#[test]
fn every_failure_describes_itself_without_a_raw_code() {
    for failure in [
        PathFailure::EmptyPath,
        PathFailure::InteriorNul,
        PathFailure::PathTooLong,
        PathFailure::NotFullyQualified,
        PathFailure::PathResolution,
    ] {
        assert!(
            !failure.description().is_empty(),
            "{failure:?} must describe itself"
        );
    }
}

#[test]
fn an_error_without_an_os_code_renders_only_its_description() {
    let error = prepare(&Wtf16String::new()).expect_err("an empty path names nothing");

    assert_eq!(error.to_string(), PathFailure::EmptyPath.description());
    assert!(std::error::Error::source(&error).is_none());
}

// ---------------------------------------------------------------------------
// Boundaries.
//
// A mutation sweep moved the ordinary path limit by one in both directions and
// changed `>` to `>=` and `==`, and every one of those survived: the tests
// above use comfortably-wrong lengths, which prove a check exists but not that
// it sits at the right unit.
//
// This is the same block, and for the same reason, as the one in
// `windows-file-enumeration-sys`'s path module -- the two crates carry
// near-identical path contracts, and the sweep found the same gap in both.
// ---------------------------------------------------------------------------

/// An absolute path of exactly `units` UTF-16 units, already in normal form so
/// `GetFullPathNameW` returns it unchanged and the resolved length equals the
/// input length.
///
/// UTF-16 units and not bytes or `char`s, because that is the unit Win32
/// measures a path in: `MAX_PATH` is a count of `WCHAR`. The three coincide for
/// the ASCII this builds, so counting the prefix any other way would pass today
/// and quietly measure the wrong thing the moment a case uses a character that
/// is not one byte, one scalar, and one unit at once.
fn absolute_path_of_length(units: usize) -> String {
    let prefix = r"C:\";
    let prefix_units = prefix.encode_utf16().count();
    assert!(
        units >= prefix_units,
        "asked for a {units}-unit path, but the {prefix} prefix is already \
         {prefix_units} units; the subtraction below would underflow and panic \
         without saying why"
    );
    format!("{prefix}{}", "a".repeat(units - prefix_units))
}

#[test]
fn an_ordinary_path_of_exactly_max_path_content_is_accepted() {
    // 259 = MAX_PATH - 1, the longest path that leaves room for the terminator.
    // Rejecting it is the off-by-one a "much too long" test cannot see, and it
    // is the expensive direction: it refuses a path Windows would have opened.
    let path = absolute_path_of_length(259);
    assert_eq!(path.encode_utf16().count(), 259);

    let prepared = prepare_str(&path).expect("259 units is within the ordinary limit");
    assert_eq!(text(&prepared), path);
}

#[test]
fn an_ordinary_path_one_unit_past_max_path_content_is_rejected() {
    let path = absolute_path_of_length(260);
    assert_eq!(path.encode_utf16().count(), 260);

    let error = prepare_str(&path).expect_err("260 units leaves no room for the terminator");
    assert_eq!(error.failure(), PathFailure::PathTooLong);
}

#[test]
fn the_ordinary_limit_is_one_less_than_max_path() {
    // The relationship the two tests above rest on, stated directly so a change
    // to the constant fails here with its reason rather than only as a puzzling
    // length assertion elsewhere.
    assert_eq!(MAX_PATH_CONTENT, MAX_PATH - 1);
    assert_eq!(MAX_PATH_CONTENT, 259);
}

#[test]
fn a_path_whose_character_count_hides_its_utf16_length_is_still_refused() {
    // The two tests above build ASCII, where bytes, `char`s and UTF-16 units are
    // the same number, so a path they accept or refuse says nothing about which
    // unit was counted. This one separates them: a character above `U+FFFF` (a
    // supplementary character) is one `char` but *two* UTF-16 units, because
    // UTF-16 encodes it as a surrogate pair. A path built from those measured in
    // scalars looks about half as long as Windows considers it.
    //
    // What this pins is the **contract** -- such a path is still refused -- and
    // not any single site's arithmetic. Measured, because the distinction is not
    // obvious: `prepare` checks the length twice, and sabotaging only the
    // pre-check leaves this test passing, because `GetFullPathNameW` reports the
    // resolved length in UTF-16 units and the post-check refuses on that. It
    // takes disabling *both* to make this test fail. That second guard is the
    // stronger one -- its count comes from Windows and so cannot be in the wrong
    // unit -- which is worth knowing before anyone "simplifies" the pre-check
    // away as redundant.
    let supplementary = '\u{1F600}';
    assert_eq!(supplementary.len_utf16(), 2, "the premise of this test");

    // 3 units of `C:\` plus 128 two-unit characters is exactly the limit.
    let accepted = format!(r"C:\{}", supplementary.to_string().repeat(128));
    assert_eq!(accepted.encode_utf16().count(), 259);
    assert_eq!(accepted.chars().count(), 131);

    let prepared = prepare_str(&accepted).expect("259 UTF-16 units is within the limit");
    assert_eq!(text(&prepared), accepted);

    // One more unit is over it. A limit enforced on `chars().count()` would see
    // 132 against a bound of 259 and admit a path Windows refuses -- which is
    // the expensive direction, since the caller is told the open may proceed.
    let rejected = format!("{accepted}a");
    assert_eq!(rejected.encode_utf16().count(), 260);
    assert_eq!(rejected.chars().count(), 132);

    let error = prepare_str(&rejected).expect_err("260 UTF-16 units is past the limit");
    assert_eq!(error.failure(), PathFailure::PathTooLong);
}

#[test]
fn a_verbatim_drive_relative_path_with_a_separator_is_rejected() {
    // `\\?\C:foo` has no separator at all, so it is refused before the root is
    // ever inspected and never reaches the drive-designator check. This form
    // does reach it: the root is `C:foo`, which contains a colon but is not a
    // drive. Without it, the check could report every root as a drive and
    // nothing would notice.
    let error = prepare_str(r"\\?\C:foo\bar").expect_err("drive-relative, not fully qualified");
    assert_eq!(error.failure(), PathFailure::NotFullyQualified);
}

#[test]
fn a_verbatim_root_needs_a_letter_before_its_colon_not_merely_a_colon() {
    // Both halves of the drive-designator rule are load-bearing, and only a
    // root that satisfies one but not the other separates them. `1:` has the
    // colon in the right place and is still not a drive, so a check accepting
    // *either* condition would wave it through.
    for path in [r"\\?\1:\", r"\\?\1:\dir"] {
        let error = prepare_str(path).expect_err("a digit is not a drive letter");
        assert_eq!(
            error.failure(),
            PathFailure::NotFullyQualified,
            "for {path}"
        );
    }

    // Deliberately no companion case for "second unit is not a colon": the
    // check is guarded by `root.contains(&COLON)`, so a colonless root -- a
    // volume GUID, say -- never reaches it and is accepted on its own terms.
    let prepared = prepare_str(r"\\?\Ca\dir").expect("a colonless root is not a drive at all");
    assert_eq!(text(&prepared), r"\\?\Ca\dir");
}

#[test]
fn every_path_failure_describes_itself_distinctly() {
    // `PathFailure::description -> "xyzzy"` survived: the tests above assert
    // which *failure* was reported, never what it says, so a description that
    // collapsed every variant onto one string would go unnoticed.
    //
    // Distinctness is the assertion that matters. A description exists to tell
    // one failure from another, so it catches every constant substitution at
    // once rather than one string at a time -- and non-emptiness alone would
    // not, because a constant is non-empty too.
    let cases = [
        ("EmptyPath", PathFailure::EmptyPath),
        ("InteriorNul", PathFailure::InteriorNul),
        ("PathTooLong", PathFailure::PathTooLong),
        ("NotFullyQualified", PathFailure::NotFullyQualified),
        ("PathResolution", PathFailure::PathResolution),
    ];

    for (name, failure) in cases {
        assert!(
            !failure.description().is_empty(),
            "{name} has no description, so a reader learns nothing from it"
        );
    }
    for (index, (name, failure)) in cases.iter().enumerate() {
        for (other_name, other) in &cases[index + 1..] {
            assert_ne!(
                failure.description(),
                other.description(),
                "{name} and {other_name} describe themselves identically, so the \
                 description cannot tell them apart"
            );
        }
    }
}

#[test]
fn a_failure_decided_here_carries_no_os_error_and_renders_as_its_description() {
    // The half of `PathError` that has no Win32 call behind it. Asserting the
    // exact rendering -- rather than merely that it is non-empty -- is what
    // binds `Display` to `description`: without it the formatter could drop the
    // description entirely and nothing would fail.
    let error = prepare_str("").expect_err("an empty path names nothing");

    assert_eq!(error.failure(), PathFailure::EmptyPath);
    assert_eq!(error.raw_os_error(), None);
    assert!(std::error::Error::source(&error).is_none());
    assert_eq!(error.to_string(), PathFailure::EmptyPath.description());
}