/
windows.rs
2340 lines (2192 loc) · 94.7 KB
/
windows.rs
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Windows file path handling
use ascii::AsciiCast;
use c_str::{CString, ToCStr};
use clone::Clone;
use cmp::{PartialEq, Eq};
use collections::Collection;
use from_str::FromStr;
use hash;
use io::Writer;
use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Iterator, Map};
use mem;
use option::{Option, Some, None};
use slice::{Vector, ImmutableVector};
use str::{CharSplits, Str, StrAllocating, StrVector, StrSlice};
use string::String;
use vec::Vec;
use super::{contains_nul, BytesContainer, GenericPath, GenericPathUnsafe};
/// Iterator that yields successive components of a Path as &str
///
/// Each component is yielded as Option<&str> for compatibility with PosixPath, but
/// every component in WindowsPath is guaranteed to be Some.
pub type StrComponents<'a> = Map<'a, &'a str, Option<&'a str>,
CharSplits<'a, char>>;
/// Iterator that yields successive components of a Path as &[u8]
pub type Components<'a> = Map<'a, Option<&'a str>, &'a [u8],
StrComponents<'a>>;
/// Represents a Windows path
// Notes for Windows path impl:
// The MAX_PATH is 260, but 253 is the practical limit due to some API bugs
// See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx for good information
// about windows paths.
// That same page puts a bunch of restrictions on allowed characters in a path.
// `\foo.txt` means "relative to current drive", but will not be considered to be absolute here
// as `∃P | P.join("\foo.txt") != "\foo.txt"`.
// `C:` is interesting, that means "the current directory on drive C".
// Long absolute paths need to have \\?\ prefix (or, for UNC, \\?\UNC\). I think that can be
// ignored for now, though, and only added in a hypothetical .to_pwstr() function.
// However, if a path is parsed that has \\?\, this needs to be preserved as it disables the
// processing of "." and ".." components and / as a separator.
// Experimentally, \\?\foo is not the same thing as \foo.
// Also, \\foo is not valid either (certainly not equivalent to \foo).
// Similarly, C:\\Users is not equivalent to C:\Users, although C:\Users\\foo is equivalent
// to C:\Users\foo. In fact the command prompt treats C:\\foo\bar as UNC path. But it might be
// best to just ignore that and normalize it to C:\foo\bar.
//
// Based on all this, I think the right approach is to do the following:
// * Require valid utf-8 paths. Windows API may use WCHARs, but we don't, and utf-8 is convertible
// to UTF-16 anyway (though does Windows use UTF-16 or UCS-2? Not sure).
// * Parse the prefixes \\?\UNC\, \\?\, and \\.\ explicitly.
// * If \\?\UNC\, treat following two path components as server\share. Don't error for missing
// server\share.
// * If \\?\, parse disk from following component, if present. Don't error for missing disk.
// * If \\.\, treat rest of path as just regular components. I don't know how . and .. are handled
// here, they probably aren't, but I'm not going to worry about that.
// * Else if starts with \\, treat following two components as server\share. Don't error for missing
// server\share.
// * Otherwise, attempt to parse drive from start of path.
//
// The only error condition imposed here is valid utf-8. All other invalid paths are simply
// preserved by the data structure; let the Windows API error out on them.
#[deriving(Clone)]
pub struct Path {
repr: String, // assumed to never be empty
prefix: Option<PathPrefix>,
sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr
}
impl PartialEq for Path {
#[inline]
fn eq(&self, other: &Path) -> bool {
self.repr == other.repr
}
}
impl Eq for Path {}
impl FromStr for Path {
fn from_str(s: &str) -> Option<Path> {
Path::new_opt(s)
}
}
// FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
// we cannot usefully take ToCStr arguments by reference (without forcing an
// additional & around &str). So we are instead temporarily adding an instance
// for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
// instance should be removed, and arguments bound by ToCStr should be passed by
// reference.
impl ToCStr for Path {
#[inline]
fn to_c_str(&self) -> CString {
// The Path impl guarantees no internal NUL
unsafe { self.to_c_str_unchecked() }
}
#[inline]
unsafe fn to_c_str_unchecked(&self) -> CString {
self.as_vec().to_c_str_unchecked()
}
}
impl<'a> ToCStr for &'a Path {
#[inline]
fn to_c_str(&self) -> CString {
(*self).to_c_str()
}
#[inline]
unsafe fn to_c_str_unchecked(&self) -> CString {
(*self).to_c_str_unchecked()
}
}
impl<S: hash::Writer> hash::Hash<S> for Path {
#[cfg(not(test))]
#[inline]
fn hash(&self, state: &mut S) {
self.repr.hash(state)
}
#[cfg(test)]
#[inline]
fn hash(&self, _: &mut S) {
// No-op because the `hash` implementation will be wrong.
}
}
impl BytesContainer for Path {
#[inline]
fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
self.as_vec()
}
#[inline]
fn container_into_owned_bytes(self) -> Vec<u8> {
self.into_vec()
}
#[inline]
fn container_as_str<'a>(&'a self) -> Option<&'a str> {
self.as_str()
}
#[inline]
fn is_str(_: Option<Path>) -> bool { true }
}
impl<'a> BytesContainer for &'a Path {
#[inline]
fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
self.as_vec()
}
#[inline]
fn container_as_str<'a>(&'a self) -> Option<&'a str> {
self.as_str()
}
#[inline]
fn is_str(_: Option<&'a Path>) -> bool { true }
}
impl GenericPathUnsafe for Path {
/// See `GenericPathUnsafe::from_vec_unchecked`.
///
/// # Failure
///
/// Fails if not valid UTF-8.
#[inline]
unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
let (prefix, path) = Path::normalize_(path.container_as_str().unwrap());
assert!(!path.is_empty());
let mut ret = Path{ repr: path, prefix: prefix, sepidx: None };
ret.update_sepidx();
ret
}
/// See `GenericPathUnsafe::set_filename_unchecked`.
///
/// # Failure
///
/// Fails if not valid UTF-8.
unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
let filename = filename.container_as_str().unwrap();
match self.sepidx_or_prefix_len() {
None if ".." == self.repr.as_slice() => {
let mut s = String::with_capacity(3 + filename.len());
s.push_str("..");
s.push_char(SEP);
s.push_str(filename);
self.update_normalized(s);
}
None => {
self.update_normalized(filename);
}
Some((_,idxa,end)) if self.repr.as_slice().slice(idxa,end) == ".." => {
let mut s = String::with_capacity(end + 1 + filename.len());
s.push_str(self.repr.as_slice().slice_to(end));
s.push_char(SEP);
s.push_str(filename);
self.update_normalized(s);
}
Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => {
let mut s = String::with_capacity(idxb + filename.len());
s.push_str(self.repr.as_slice().slice_to(idxb));
s.push_str(filename);
self.update_normalized(s);
}
Some((idxb,_,_)) => {
let mut s = String::with_capacity(idxb + 1 + filename.len());
s.push_str(self.repr.as_slice().slice_to(idxb));
s.push_char(SEP);
s.push_str(filename);
self.update_normalized(s);
}
}
}
/// See `GenericPathUnsafe::push_unchecked`.
///
/// Concatenating two Windows Paths is rather complicated.
/// For the most part, it will behave as expected, except in the case of
/// pushing a volume-relative path, e.g. `C:foo.txt`. Because we have no
/// concept of per-volume cwds like Windows does, we can't behave exactly
/// like Windows will. Instead, if the receiver is an absolute path on
/// the same volume as the new path, it will be treated as the cwd that
/// the new path is relative to. Otherwise, the new path will be treated
/// as if it were absolute and will replace the receiver outright.
unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
let path = path.container_as_str().unwrap();
fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool {
// assume prefix is Some(DiskPrefix)
let rest = path.slice_from(prefix_len(prefix));
!rest.is_empty() && rest[0].is_ascii() && is_sep(rest[0] as char)
}
fn shares_volume(me: &Path, path: &str) -> bool {
// path is assumed to have a prefix of Some(DiskPrefix)
let repr = me.repr.as_slice();
match me.prefix {
Some(DiskPrefix) => repr[0] == path[0].to_ascii().to_upper().to_byte(),
Some(VerbatimDiskPrefix) => repr[4] == path[0].to_ascii().to_upper().to_byte(),
_ => false
}
}
fn is_sep_(prefix: Option<PathPrefix>, u: u8) -> bool {
if prefix_is_verbatim(prefix) { is_sep_verbatim(u as char) }
else { is_sep(u as char) }
}
fn replace_path(me: &mut Path, path: &str, prefix: Option<PathPrefix>) {
let newpath = Path::normalize__(path, prefix);
me.repr = match newpath {
Some(p) => p,
None => String::from_str(path)
};
me.prefix = prefix;
me.update_sepidx();
}
fn append_path(me: &mut Path, path: &str) {
// appends a path that has no prefix
// if me is verbatim, we need to pre-normalize the new path
let path_ = if is_verbatim(me) { Path::normalize__(path, None) }
else { None };
let pathlen = path_.as_ref().map_or(path.len(), |p| p.len());
let mut s = String::with_capacity(me.repr.len() + 1 + pathlen);
s.push_str(me.repr.as_slice());
let plen = me.prefix_len();
// if me is "C:" we don't want to add a path separator
match me.prefix {
Some(DiskPrefix) if me.repr.len() == plen => (),
_ if !(me.repr.len() > plen && me.repr.as_slice()[me.repr.len()-1] == SEP_BYTE) => {
s.push_char(SEP);
}
_ => ()
}
match path_ {
None => s.push_str(path),
Some(p) => s.push_str(p.as_slice())
};
me.update_normalized(s)
}
if !path.is_empty() {
let prefix = parse_prefix(path);
match prefix {
Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => {
// cwd-relative path, self is on the same volume
append_path(self, path.slice_from(prefix_len(prefix)));
}
Some(_) => {
// absolute path, or cwd-relative and self is not same volume
replace_path(self, path, prefix);
}
None if !path.is_empty() && is_sep_(self.prefix, path[0]) => {
// volume-relative path
if self.prefix.is_some() {
// truncate self down to the prefix, then append
let n = self.prefix_len();
self.repr.truncate(n);
append_path(self, path);
} else {
// we have no prefix, so nothing to be relative to
replace_path(self, path, prefix);
}
}
None => {
// relative path
append_path(self, path);
}
}
}
}
}
impl GenericPath for Path {
#[inline]
fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
match path.container_as_str() {
None => None,
Some(ref s) => {
if contains_nul(s) {
None
} else {
Some(unsafe { GenericPathUnsafe::new_unchecked(*s) })
}
}
}
}
/// See `GenericPath::as_str` for info.
/// Always returns a `Some` value.
#[inline]
fn as_str<'a>(&'a self) -> Option<&'a str> {
Some(self.repr.as_slice())
}
#[inline]
fn as_vec<'a>(&'a self) -> &'a [u8] {
self.repr.as_bytes()
}
#[inline]
fn into_vec(self) -> Vec<u8> {
Vec::from_slice(self.repr.as_bytes())
}
#[inline]
fn dirname<'a>(&'a self) -> &'a [u8] {
self.dirname_str().unwrap().as_bytes()
}
/// See `GenericPath::dirname_str` for info.
/// Always returns a `Some` value.
fn dirname_str<'a>(&'a self) -> Option<&'a str> {
Some(match self.sepidx_or_prefix_len() {
None if ".." == self.repr.as_slice() => self.repr.as_slice(),
None => ".",
Some((_,idxa,end)) if self.repr.as_slice().slice(idxa, end) == ".." => {
self.repr.as_slice()
}
Some((idxb,_,end)) if self.repr.as_slice().slice(idxb, end) == "\\" => {
self.repr.as_slice()
}
Some((0,idxa,_)) => self.repr.as_slice().slice_to(idxa),
Some((idxb,idxa,_)) => {
match self.prefix {
Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => {
self.repr.as_slice().slice_to(idxa)
}
_ => self.repr.as_slice().slice_to(idxb)
}
}
})
}
#[inline]
fn filename<'a>(&'a self) -> Option<&'a [u8]> {
self.filename_str().map(|x| x.as_bytes())
}
/// See `GenericPath::filename_str` for info.
/// Always returns a `Some` value if `filename` returns a `Some` value.
fn filename_str<'a>(&'a self) -> Option<&'a str> {
let repr = self.repr.as_slice();
match self.sepidx_or_prefix_len() {
None if "." == repr || ".." == repr => None,
None => Some(repr),
Some((_,idxa,end)) if repr.slice(idxa, end) == ".." => None,
Some((_,idxa,end)) if idxa == end => None,
Some((_,idxa,end)) => Some(repr.slice(idxa, end))
}
}
/// See `GenericPath::filestem_str` for info.
/// Always returns a `Some` value if `filestem` returns a `Some` value.
#[inline]
fn filestem_str<'a>(&'a self) -> Option<&'a str> {
// filestem() returns a byte vector that's guaranteed valid UTF-8
self.filestem().map(|t| unsafe { mem::transmute(t) })
}
#[inline]
fn extension_str<'a>(&'a self) -> Option<&'a str> {
// extension() returns a byte vector that's guaranteed valid UTF-8
self.extension().map(|t| unsafe { mem::transmute(t) })
}
fn dir_path(&self) -> Path {
unsafe { GenericPathUnsafe::new_unchecked(self.dirname_str().unwrap()) }
}
#[inline]
fn pop(&mut self) -> bool {
match self.sepidx_or_prefix_len() {
None if "." == self.repr.as_slice() => false,
None => {
self.repr = String::from_str(".");
self.sepidx = None;
true
}
Some((idxb,idxa,end)) if idxb == idxa && idxb == end => false,
Some((idxb,_,end)) if self.repr.as_slice().slice(idxb, end) == "\\" => false,
Some((idxb,idxa,_)) => {
let trunc = match self.prefix {
Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => {
let plen = self.prefix_len();
if idxb == plen { idxa } else { idxb }
}
_ => idxb
};
self.repr.truncate(trunc);
self.update_sepidx();
true
}
}
}
fn root_path(&self) -> Option<Path> {
if self.prefix.is_some() {
Some(Path::new(match self.prefix {
Some(DiskPrefix) if self.is_absolute() => {
self.repr.as_slice().slice_to(self.prefix_len()+1)
}
Some(VerbatimDiskPrefix) => {
self.repr.as_slice().slice_to(self.prefix_len()+1)
}
_ => self.repr.as_slice().slice_to(self.prefix_len())
}))
} else if is_vol_relative(self) {
Some(Path::new(self.repr.as_slice().slice_to(1)))
} else {
None
}
}
/// See `GenericPath::is_absolute` for info.
///
/// A Windows Path is considered absolute only if it has a non-volume prefix,
/// or if it has a volume prefix and the path starts with '\'.
/// A path of `\foo` is not considered absolute because it's actually
/// relative to the "current volume". A separate method `Path::is_vol_relative`
/// is provided to indicate this case. Similarly a path of `C:foo` is not
/// considered absolute because it's relative to the cwd on volume C:. A
/// separate method `Path::is_cwd_relative` is provided to indicate this case.
#[inline]
fn is_absolute(&self) -> bool {
match self.prefix {
Some(DiskPrefix) => {
let rest = self.repr.as_slice().slice_from(self.prefix_len());
rest.len() > 0 && rest[0] == SEP_BYTE
}
Some(_) => true,
None => false
}
}
#[inline]
fn is_relative(&self) -> bool {
self.prefix.is_none() && !is_vol_relative(self)
}
fn is_ancestor_of(&self, other: &Path) -> bool {
if !self.equiv_prefix(other) {
false
} else if self.is_absolute() != other.is_absolute() ||
is_vol_relative(self) != is_vol_relative(other) {
false
} else {
let mut ita = self.str_components().map(|x|x.unwrap());
let mut itb = other.str_components().map(|x|x.unwrap());
if "." == self.repr.as_slice() {
return itb.next() != Some("..");
}
loop {
match (ita.next(), itb.next()) {
(None, _) => break,
(Some(a), Some(b)) if a == b => { continue },
(Some(a), _) if a == ".." => {
// if ita contains only .. components, it's an ancestor
return ita.all(|x| x == "..");
}
_ => return false
}
}
true
}
}
fn path_relative_from(&self, base: &Path) -> Option<Path> {
fn comp_requires_verbatim(s: &str) -> bool {
s == "." || s == ".." || s.contains_char(SEP2)
}
if !self.equiv_prefix(base) {
// prefixes differ
if self.is_absolute() {
Some(self.clone())
} else if self.prefix == Some(DiskPrefix) && base.prefix == Some(DiskPrefix) {
// both drives, drive letters must differ or they'd be equiv
Some(self.clone())
} else {
None
}
} else if self.is_absolute() != base.is_absolute() {
if self.is_absolute() {
Some(self.clone())
} else {
None
}
} else if is_vol_relative(self) != is_vol_relative(base) {
if is_vol_relative(self) {
Some(self.clone())
} else {
None
}
} else {
let mut ita = self.str_components().map(|x|x.unwrap());
let mut itb = base.str_components().map(|x|x.unwrap());
let mut comps = vec![];
let a_verb = is_verbatim(self);
let b_verb = is_verbatim(base);
loop {
match (ita.next(), itb.next()) {
(None, None) => break,
(Some(a), None) if a_verb && comp_requires_verbatim(a) => {
return Some(self.clone())
}
(Some(a), None) => {
comps.push(a);
if !a_verb {
comps.extend(ita.by_ref());
break;
}
}
(None, _) => comps.push(".."),
(Some(a), Some(b)) if comps.is_empty() && a == b => (),
(Some(a), Some(b)) if !b_verb && b == "." => {
if a_verb && comp_requires_verbatim(a) {
return Some(self.clone())
} else { comps.push(a) }
}
(Some(_), Some(b)) if !b_verb && b == ".." => return None,
(Some(a), Some(_)) if a_verb && comp_requires_verbatim(a) => {
return Some(self.clone())
}
(Some(a), Some(_)) => {
comps.push("..");
for _ in itb {
comps.push("..");
}
comps.push(a);
if !a_verb {
comps.extend(ita.by_ref());
break;
}
}
}
}
Some(Path::new(comps.connect("\\")))
}
}
fn ends_with_path(&self, child: &Path) -> bool {
if !child.is_relative() { return false; }
let mut selfit = self.str_components().rev();
let mut childit = child.str_components().rev();
loop {
match (selfit.next(), childit.next()) {
(Some(a), Some(b)) => if a != b { return false; },
(Some(_), None) => break,
(None, Some(_)) => return false,
(None, None) => break
}
}
true
}
}
impl Path {
/// Returns a new Path from a byte vector or string
///
/// # Failure
///
/// Fails the task if the vector contains a NUL.
/// Fails if invalid UTF-8.
#[inline]
pub fn new<T: BytesContainer>(path: T) -> Path {
GenericPath::new(path)
}
/// Returns a new Path from a byte vector or string, if possible
#[inline]
pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
GenericPath::new_opt(path)
}
/// Returns an iterator that yields each component of the path in turn as a Option<&str>.
/// Every component is guaranteed to be Some.
/// Does not yield the path prefix (including server/share components in UNC paths).
/// Does not distinguish between volume-relative and relative paths, e.g.
/// \a\b\c and a\b\c.
/// Does not distinguish between absolute and cwd-relative paths, e.g.
/// C:\foo and C:foo.
pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
let repr = self.repr.as_slice();
let s = match self.prefix {
Some(_) => {
let plen = self.prefix_len();
if repr.len() > plen && repr[plen] == SEP_BYTE {
repr.slice_from(plen+1)
} else { repr.slice_from(plen) }
}
None if repr[0] == SEP_BYTE => repr.slice_from(1),
None => repr
};
let ret = s.split_terminator(SEP).map(Some);
ret
}
/// Returns an iterator that yields each component of the path in turn as a &[u8].
/// See str_components() for details.
pub fn components<'a>(&'a self) -> Components<'a> {
fn convert<'a>(x: Option<&'a str>) -> &'a [u8] {
#![inline]
x.unwrap().as_bytes()
}
self.str_components().map(convert)
}
fn equiv_prefix(&self, other: &Path) -> bool {
let s_repr = self.repr.as_slice();
let o_repr = other.repr.as_slice();
match (self.prefix, other.prefix) {
(Some(DiskPrefix), Some(VerbatimDiskPrefix)) => {
self.is_absolute() &&
s_repr[0].to_ascii().eq_ignore_case(o_repr[4].to_ascii())
}
(Some(VerbatimDiskPrefix), Some(DiskPrefix)) => {
other.is_absolute() &&
s_repr[4].to_ascii().eq_ignore_case(o_repr[0].to_ascii())
}
(Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => {
s_repr[4].to_ascii().eq_ignore_case(o_repr[4].to_ascii())
}
(Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => {
s_repr.slice(2, self.prefix_len()) == o_repr.slice(8, other.prefix_len())
}
(Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => {
s_repr.slice(8, self.prefix_len()) == o_repr.slice(2, other.prefix_len())
}
(None, None) => true,
(a, b) if a == b => {
s_repr.slice_to(self.prefix_len()) == o_repr.slice_to(other.prefix_len())
}
_ => false
}
}
fn normalize_<S: StrAllocating>(s: S) -> (Option<PathPrefix>, String) {
// make borrowck happy
let (prefix, val) = {
let prefix = parse_prefix(s.as_slice());
let path = Path::normalize__(s.as_slice(), prefix);
(prefix, path)
};
(prefix, match val {
None => s.into_string(),
Some(val) => val
})
}
fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<String> {
if prefix_is_verbatim(prefix) {
// don't do any normalization
match prefix {
Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => {
// the server component has no trailing '\'
let mut s = String::from_str(s);
s.push_char(SEP);
Some(s)
}
_ => None
}
} else {
let (is_abs, comps) = normalize_helper(s, prefix);
let mut comps = comps;
match (comps.is_some(),prefix) {
(false, Some(DiskPrefix)) => {
if s[0] >= 'a' as u8 && s[0] <= 'z' as u8 {
comps = Some(vec![]);
}
}
(false, Some(VerbatimDiskPrefix)) => {
if s[4] >= 'a' as u8 && s[0] <= 'z' as u8 {
comps = Some(vec![]);
}
}
_ => ()
}
match comps {
None => None,
Some(comps) => {
if prefix.is_some() && comps.is_empty() {
match prefix.unwrap() {
DiskPrefix => {
let len = prefix_len(prefix) + is_abs as uint;
let mut s = String::from_str(s.slice_to(len));
unsafe {
let v = s.as_mut_vec();
*v.get_mut(0) = v.get(0)
.to_ascii()
.to_upper()
.to_byte();
}
if is_abs {
// normalize C:/ to C:\
unsafe {
*s.as_mut_vec().get_mut(2) = SEP_BYTE;
}
}
Some(s)
}
VerbatimDiskPrefix => {
let len = prefix_len(prefix) + is_abs as uint;
let mut s = String::from_str(s.slice_to(len));
unsafe {
let v = s.as_mut_vec();
*v.get_mut(4) = v.get(4).to_ascii().to_upper().to_byte();
}
Some(s)
}
_ => {
let plen = prefix_len(prefix);
if s.len() > plen {
Some(String::from_str(s.slice_to(plen)))
} else { None }
}
}
} else if is_abs && comps.is_empty() {
Some(String::from_char(1, SEP))
} else {
let prefix_ = s.slice_to(prefix_len(prefix));
let n = prefix_.len() +
if is_abs { comps.len() } else { comps.len() - 1} +
comps.iter().map(|v| v.len()).sum();
let mut s = String::with_capacity(n);
match prefix {
Some(DiskPrefix) => {
s.push_char(prefix_[0].to_ascii().to_upper().to_char());
s.push_char(':');
}
Some(VerbatimDiskPrefix) => {
s.push_str(prefix_.slice_to(4));
s.push_char(prefix_[4].to_ascii().to_upper().to_char());
s.push_str(prefix_.slice_from(5));
}
Some(UNCPrefix(a,b)) => {
s.push_str("\\\\");
s.push_str(prefix_.slice(2, a+2));
s.push_char(SEP);
s.push_str(prefix_.slice(3+a, 3+a+b));
}
Some(_) => s.push_str(prefix_),
None => ()
}
let mut it = comps.move_iter();
if !is_abs {
match it.next() {
None => (),
Some(comp) => s.push_str(comp)
}
}
for comp in it {
s.push_char(SEP);
s.push_str(comp);
}
Some(s)
}
}
}
}
}
fn update_sepidx(&mut self) {
let s = if self.has_nonsemantic_trailing_slash() {
self.repr.as_slice().slice_to(self.repr.len()-1)
} else { self.repr.as_slice() };
let idx = s.rfind(if !prefix_is_verbatim(self.prefix) { is_sep }
else { is_sep_verbatim });
let prefixlen = self.prefix_len();
self.sepidx = idx.and_then(|x| if x < prefixlen { None } else { Some(x) });
}
fn prefix_len(&self) -> uint {
prefix_len(self.prefix)
}
// Returns a tuple (before, after, end) where before is the index of the separator
// and after is the index just after the separator.
// end is the length of the string, normally, or the index of the final character if it is
// a non-semantic trailing separator in a verbatim string.
// If the prefix is considered the separator, before and after are the same.
fn sepidx_or_prefix_len(&self) -> Option<(uint,uint,uint)> {
match self.sepidx {
None => match self.prefix_len() { 0 => None, x => Some((x,x,self.repr.len())) },
Some(x) => {
if self.has_nonsemantic_trailing_slash() {
Some((x,x+1,self.repr.len()-1))
} else { Some((x,x+1,self.repr.len())) }
}
}
}
fn has_nonsemantic_trailing_slash(&self) -> bool {
is_verbatim(self) && self.repr.len() > self.prefix_len()+1 &&
self.repr.as_slice()[self.repr.len()-1] == SEP_BYTE
}
fn update_normalized<S: Str>(&mut self, s: S) {
let (prefix, path) = Path::normalize_(s.as_slice());
self.repr = path;
self.prefix = prefix;
self.update_sepidx();
}
}
/// Returns whether the path is considered "volume-relative", which means a path
/// that looks like "\foo". Paths of this form are relative to the current volume,
/// but absolute within that volume.
#[inline]
pub fn is_vol_relative(path: &Path) -> bool {
path.prefix.is_none() && is_sep_byte(&path.repr.as_slice()[0])
}
/// Returns whether the path is considered "cwd-relative", which means a path
/// with a volume prefix that is not absolute. This look like "C:foo.txt". Paths
/// of this form are relative to the cwd on the given volume.
#[inline]
pub fn is_cwd_relative(path: &Path) -> bool {
path.prefix == Some(DiskPrefix) && !path.is_absolute()
}
/// Returns the PathPrefix for this Path
#[inline]
pub fn prefix(path: &Path) -> Option<PathPrefix> {
path.prefix
}
/// Returns whether the Path's prefix is a verbatim prefix, i.e. `\\?\`
#[inline]
pub fn is_verbatim(path: &Path) -> bool {
prefix_is_verbatim(path.prefix)
}
/// Returns the non-verbatim equivalent of the input path, if possible.
/// If the input path is a device namespace path, None is returned.
/// If the input path is not verbatim, it is returned as-is.
/// If the input path is verbatim, but the same path can be expressed as
/// non-verbatim, the non-verbatim version is returned.
/// Otherwise, None is returned.
pub fn make_non_verbatim(path: &Path) -> Option<Path> {
let repr = path.repr.as_slice();
let new_path = match path.prefix {
Some(VerbatimPrefix(_)) | Some(DeviceNSPrefix(_)) => return None,
Some(UNCPrefix(_,_)) | Some(DiskPrefix) | None => return Some(path.clone()),
Some(VerbatimDiskPrefix) => {
// \\?\D:\
Path::new(repr.slice_from(4))
}
Some(VerbatimUNCPrefix(_,_)) => {
// \\?\UNC\server\share
Path::new(format!(r"\{}", repr.slice_from(7)))
}
};
if new_path.prefix.is_none() {
// \\?\UNC\server is a VerbatimUNCPrefix
// but \\server is nothing
return None;
}
// now ensure normalization didn't change anything
if repr.slice_from(path.prefix_len()) ==
new_path.repr.as_slice().slice_from(new_path.prefix_len()) {
Some(new_path)
} else {
None
}
}
/// The standard path separator character
pub static SEP: char = '\\';
/// The standard path separator byte
pub static SEP_BYTE: u8 = SEP as u8;
/// The alternative path separator character
pub static SEP2: char = '/';
/// The alternative path separator character
pub static SEP2_BYTE: u8 = SEP2 as u8;
/// Returns whether the given char is a path separator.
/// Allows both the primary separator '\' and the alternative separator '/'.
#[inline]
pub fn is_sep(c: char) -> bool {
c == SEP || c == SEP2
}
/// Returns whether the given char is a path separator.
/// Only allows the primary separator '\'; use is_sep to allow '/'.
#[inline]
pub fn is_sep_verbatim(c: char) -> bool {
c == SEP
}
/// Returns whether the given byte is a path separator.
/// Allows both the primary separator '\' and the alternative separator '/'.
#[inline]
pub fn is_sep_byte(u: &u8) -> bool {
*u == SEP_BYTE || *u == SEP2_BYTE
}
/// Returns whether the given byte is a path separator.
/// Only allows the primary separator '\'; use is_sep_byte to allow '/'.
#[inline]
pub fn is_sep_byte_verbatim(u: &u8) -> bool {
*u == SEP_BYTE
}
/// Prefix types for Path
#[deriving(PartialEq, Clone)]
pub enum PathPrefix {
/// Prefix `\\?\`, uint is the length of the following component
VerbatimPrefix(uint),
/// Prefix `\\?\UNC\`, uints are the lengths of the UNC components
VerbatimUNCPrefix(uint, uint),
/// Prefix `\\?\C:\` (for any alphabetic character)
VerbatimDiskPrefix,
/// Prefix `\\.\`, uint is the length of the following component
DeviceNSPrefix(uint),
/// UNC prefix `\\server\share`, uints are the lengths of the server/share
UNCPrefix(uint, uint),
/// Prefix `C:` for any alphabetic character
DiskPrefix
}
fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> {
if path.starts_with("\\\\") {
// \\
path = path.slice_from(2);
if path.starts_with("?\\") {
// \\?\
path = path.slice_from(2);
if path.starts_with("UNC\\") {
// \\?\UNC\server\share
path = path.slice_from(4);
let (idx_a, idx_b) = match parse_two_comps(path, is_sep_verbatim) {
Some(x) => x,
None => (path.len(), 0)
};
return Some(VerbatimUNCPrefix(idx_a, idx_b));
} else {
// \\?\path
let idx = path.find('\\');
if idx == Some(2) && path[1] == ':' as u8 {
let c = path[0];
if c.is_ascii() && ::char::is_alphabetic(c as char) {
// \\?\C:\ path
return Some(VerbatimDiskPrefix);
}
}