vibe.core.path 0/286(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
/** Contains routines for high level path handling. Copyright: © 2012-2017 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.core.path; import std.algorithm.searching : commonPrefix, endsWith, startsWith; import std.algorithm.comparison : min; import std.algorithm.iteration : map; import std.exception : enforce; import std.range : empty, front, popFront, popFrontExactly, takeExactly; import std.range.primitives : ElementType, isInputRange, isOutputRange; import std.traits : isInstanceOf; /** Computes the relative path from `base_path` to this path. Params: path = The destination path base_path = The path from which the relative path starts See_also: `relativeToWeb` */ Path relativeTo(Path)(Path path, Path base_path) @safe if (isInstanceOf!(GenericPath, Path)) { import std.algorithm.comparison : equal; import std.array : array, replicate; import std.range : chain, drop, take; assert(base_path.absolute, "Base path must be absolute for relativeTo."); assert(path.absolute, "Path must be absolute for relativeTo."); if (is(Path == WindowsPath)) { // FIXME: this shouldn't be a special case here! bool samePrefix(size_t n) { return path.bySegment.map!(n => n.name).take(n).equal(base_path.bySegment.map!(n => n.name).take(n)); } // a path such as ..\C:\windows is not valid, so force the path to stay absolute in this case auto pref = path.bySegment; if (!pref.empty && pref.front.name == "") { pref.popFront(); if (!pref.empty) { // different drive? if (pref.front.name.endsWith(':') && !samePrefix(2)) return path; // different UNC path? if (pref.front.name == "" && !samePrefix(4)) return path; } } } auto nodes = path.bySegment; auto base_nodes = base_path.bySegment; // skip and count common prefix size_t base = 0; while (!nodes.empty && !base_nodes.empty && nodes.front.name == base_nodes.front.name) { nodes.popFront(); base_nodes.popFront(); base++; } enum up = Path.Segment("..", Path.defaultSeparator); auto ret = Path(base_nodes.map!(p => up).chain(nodes)); if (path.endsWithSlash) { if (ret.empty) return Path("." ~ path.toString()[$-1]); else ret.endsWithSlash = true; } return ret; } /// unittest { import std.array : array; import std.conv : to; assert(PosixPath("/some/path").relativeTo(PosixPath("/")) == PosixPath("some/path")); assert(PosixPath("/some/path/").relativeTo(PosixPath("/some/other/path/")) == PosixPath("../../path/")); assert(PosixPath("/some/path/").relativeTo(PosixPath("/some/other/path")) == PosixPath("../../path/")); assert(WindowsPath("C:\\some\\path").relativeTo(WindowsPath("C:\\")) == WindowsPath("some\\path")); assert(WindowsPath("C:\\some\\path\\").relativeTo(WindowsPath("C:\\some\\other\\path/")) == WindowsPath("..\\..\\path\\")); assert(WindowsPath("C:\\some\\path\\").relativeTo(WindowsPath("C:\\some\\other\\path")) == WindowsPath("..\\..\\path\\")); assert(WindowsPath("\\\\server\\share\\some\\path").relativeTo(WindowsPath("\\\\server\\share\\")) == WindowsPath("some\\path")); assert(WindowsPath("\\\\server\\share\\some\\path\\").relativeTo(WindowsPath("\\\\server\\share\\some\\other\\path/")) == WindowsPath("..\\..\\path\\")); assert(WindowsPath("\\\\server\\share\\some\\path\\").relativeTo(WindowsPath("\\\\server\\share\\some\\other\\path")) == WindowsPath("..\\..\\path\\")); assert(WindowsPath("C:\\some\\path").relativeTo(WindowsPath("D:\\")) == WindowsPath("C:\\some\\path")); assert(WindowsPath("C:\\some\\path\\").relativeTo(WindowsPath("\\\\server\\share")) == WindowsPath("C:\\some\\path\\")); assert(WindowsPath("\\\\server\\some\\path\\").relativeTo(WindowsPath("C:\\some\\other\\path")) == WindowsPath("\\\\server\\some\\path\\")); assert(WindowsPath("\\\\server\\some\\path\\").relativeTo(WindowsPath("\\\\otherserver\\path")) == WindowsPath("\\\\server\\some\\path\\")); assert(WindowsPath("\\some\\path\\").relativeTo(WindowsPath("\\other\\path")) == WindowsPath("..\\..\\some\\path\\")); assert(WindowsPath("\\\\server\\share\\path1").relativeTo(WindowsPath("\\\\server\\share\\path2")) == WindowsPath("..\\path1")); assert(WindowsPath("\\\\server\\share\\path1").relativeTo(WindowsPath("\\\\server\\share2\\path2")) == WindowsPath("\\\\server\\share\\path1")); assert(WindowsPath("\\\\server\\share\\path1").relativeTo(WindowsPath("\\\\server2\\share2\\path2")) == WindowsPath("\\\\server\\share\\path1")); } unittest { { auto parentpath = "/path/to/parent"; auto parentpathp = PosixPath(parentpath); auto subpath = "/path/to/parent/sub/"; auto subpathp = PosixPath(subpath); auto subpath_rel = "sub/"; assert(subpathp.relativeTo(parentpathp).toString() == subpath_rel); auto subfile = "/path/to/parent/child"; auto subfilep = PosixPath(subfile); auto subfile_rel = "child"; assert(subfilep.relativeTo(parentpathp).toString() == subfile_rel); } { // relative paths across Windows devices are not allowed auto p1 = WindowsPath("\\\\server\\share"); assert(p1.absolute); auto p2 = WindowsPath("\\\\server\\othershare"); assert(p2.absolute); auto p3 = WindowsPath("\\\\otherserver\\share"); assert(p3.absolute); auto p4 = WindowsPath("C:\\somepath"); assert(p4.absolute); auto p5 = WindowsPath("C:\\someotherpath"); assert(p5.absolute); auto p6 = WindowsPath("D:\\somepath"); assert(p6.absolute); auto p7 = WindowsPath("\\\\server\\share\\path"); assert(p7.absolute); auto p8 = WindowsPath("\\\\server\\share\\otherpath"); assert(p8.absolute); assert(p4.relativeTo(p5) == WindowsPath("..\\somepath")); assert(p4.relativeTo(p6) == WindowsPath("C:\\somepath")); assert(p4.relativeTo(p1) == WindowsPath("C:\\somepath")); assert(p1.relativeTo(p2) == WindowsPath("\\\\server\\share")); assert(p1.relativeTo(p3) == WindowsPath("\\\\server\\share")); assert(p1.relativeTo(p4) == WindowsPath("\\\\server\\share")); assert(p7.relativeTo(p1) == WindowsPath("path")); assert(p7.relativeTo(p8) == WindowsPath("..\\path")); } { // relative path, trailing slash auto p1 = PosixPath("/some/path"); auto p2 = PosixPath("/some/path/"); assert(p1.relativeTo(p1).toString() == ""); assert(p1.relativeTo(p2).toString() == ""); assert(p2.relativeTo(p2).toString() == "./"); } } /** Computes the relative path to this path from `base_path` using web path rules. The difference to `relativeTo` is that a path not ending in a slash will not be considered as a path to a directory and the parent path will instead be used. Params: path = The destination path base_path = The path from which the relative path starts See_also: `relativeTo` */ Path relativeToWeb(Path)(Path path, Path base_path) @safe if (isInstanceOf!(GenericPath, Path)) { if (!base_path.endsWithSlash) { assert(base_path.absolute, "Base path must be absolute for relativeToWeb."); if (base_path.hasParentPath) base_path = base_path.parentPath; else base_path = Path("/"); assert(base_path.absolute); } return path.relativeTo(base_path); } /// /+unittest { assert(InetPath("/some/path").relativeToWeb(InetPath("/")) == InetPath("some/path")); assert(InetPath("/some/path/").relativeToWeb(InetPath("/some/other/path/")) == InetPath("../../path/")); assert(InetPath("/some/path/").relativeToWeb(InetPath("/some/other/path")) == InetPath("../path/")); }+/ /** Converts a path to its system native string representation. */ string toNativeString(P)(P path) { return (cast(NativePath)path).toString(); } /// Represents a path on Windows operating systems. alias WindowsPath = GenericPath!WindowsPathFormat; /// Represents a path on Unix/Posix systems. alias PosixPath = GenericPath!PosixPathFormat; /// Represents a path as part of an URI. alias InetPath = GenericPath!InetPathFormat; /// The path type native to the target operating system. version (Windows) alias NativePath = WindowsPath; else alias NativePath = PosixPath; deprecated("Use NativePath or one the specific path types instead.") alias Path = NativePath; deprecated("Use NativePath.Segment or one the specific path types instead.") alias PathEntry = Path.Segment; /// Provides a common interface to operate on paths of various kinds. struct GenericPath(F) { @safe: alias Format = F; /** A single path segment. */ static struct Segment { @safe: private { string m_name; string m_encodedName; char m_separator = 0; } /** Constructs a new path segment including an optional trailing separator. Params: name = The raw (unencoded) name of the path segment separator = Optional trailing path separator (e.g. `'/'`) Throws: A `PathValidationException` is thrown if the name contains characters that are invalid for the path type. In particular, any path separator characters may not be part of the name. */ this(string name, char separator = '\0') { import std.algorithm.searching : any; enforce!PathValidationException(separator == '\0' || Format.isSeparator(separator), "Invalid path separator."); auto err = Format.validateDecodedSegment(name); enforce!PathValidationException(err is null, err); m_name = name; m_separator = separator; } /** Constructs a path segment without performing validation. Note that in debug builds, there are still assertions in place that verify that the provided values are valid. Params: name = The raw (unencoded) name of the path segment separator = Optional trailing path separator (e.g. `'/'`) */ static Segment fromTrustedString(string name, char separator = '\0') nothrow @nogc pure { import std.algorithm.searching : any; assert(separator == '\0' || Format.isSeparator(separator)); assert(Format.validateDecodedSegment(name) is null, "Invalid path segment."); Segment ret; ret.m_name = name; ret.m_separator = separator; return ret; } deprecated("Use the constructor instead.") static Segment validateFilename(string name) { return Segment(name); } /// The (file/directory) name of the path segment. @property string name() const nothrow @nogc { return m_name; } /// The trailing separator (e.g. `'/'`) or `'\0'`. @property char separator() const nothrow @nogc { return m_separator; } /// ditto @property void separator(char ch) { enforce!PathValidationException(ch == '\0' || Format.isSeparator(ch), "Character is not a valid path separator."); m_separator = ch; } /// Returns `true` $(I iff) the segment has a trailing path separator. @property bool hasSeparator() const nothrow @nogc { return m_separator != '\0'; } deprecated("Use .name instead.") string toString() const nothrow @nogc { return m_name; } /** Converts the segment to another path type. The segment name will be re-validated during the conversion. The separator, if any, will be adopted or replaced by the default separator of the target path type. Throws: A `PathValidationException` is thrown if the segment name cannot be represented in the target path format. */ GenericPath!F.Segment opCast(T : GenericPath!F.Segment, F)() { char dsep = '\0'; if (m_separator) { if (F.isSeparator(m_separator)) dsep = m_separator; else dsep = F.defaultSeparator; } return GenericPath!F.Segment(m_name, dsep); } /// Compares two path segment names bool opEquals(Segment other) const nothrow @nogc { return this.name == other.name && this.hasSeparator == other.hasSeparator; } /// ditto bool opEquals(string name) const nothrow @nogc { return this.name == name; } } /** Represents a path as an forward range of `Segment`s. */ static struct PathRange { import std.traits : ReturnType; private { string m_path; ReturnType!(Format.decodeSegment!Segment) m_fronts; } private this(string path) { m_path = path; if (m_path.length) { auto ap = Format.getAbsolutePrefix(m_path); if (ap.length) { m_fronts = Format.decodeSegment!Segment(ap); m_path = m_path[ap.length .. $]; assert(!m_fronts.empty); } else readFront(); } } @property bool empty() const nothrow @nogc { return m_path.length == 0 && m_fronts.empty; } @property PathRange save() { return this; } @property Segment front() { return m_fronts.front; } void popFront() nothrow { assert(!m_fronts.empty); m_fronts.popFront(); if (m_fronts.empty && m_path.length) readFront(); } private void readFront() { auto n = Format.getFrontNode(m_path); m_fronts = Format.decodeSegment!Segment(n); m_path = m_path[n.length .. $]; assert(!m_fronts.empty); } } private { string m_path; } /// The default path segment separator character. enum char defaultSeparator = Format.defaultSeparator; /** Constructs a path from its string representation. Throws: A `PathValidationException` is thrown if the given path string is not valid. */ this(string p) { auto err = Format.validatePath(p); enforce!PathValidationException(err is null, err); m_path = p; } /** Constructs a path from a single path segment. This is equivalent to calling the range based constructor with a single-element range. */ this(Segment segment) { import std.range : only; this(only(segment)); } /** Constructs a path from an input range of `Segment`s. Throws: Since path segments are pre-validated, this constructor does not throw an exception. */ this(R)(R segments) if (isInputRange!R && is(ElementType!R : Segment)) { import std.array : appender; auto dst = appender!string; Format.toString(segments, dst); m_path = dst.data; } /** Constructs a path from its string representation. This is equivalent to calling the string based constructor. */ static GenericPath fromString(string p) { return GenericPath(p); } /** Constructs a path from its string representation, skipping the validation. Note that it is required to pass a pre-validated path string to this function. Debug builds will enforce this with an assertion. */ static GenericPath fromTrustedString(string p) nothrow @nogc { assert(Format.validatePath(p) is null, "Invalid trusted path."); GenericPath ret; ret.m_path = p; return ret; } /// Tests if a certain character is a path segment separator. static bool isSeparator(dchar ch) { return ch < 0x80 && Format.isSeparator(cast(char)ch); } /// Tests if the path is represented by an empty string. @property bool empty() const nothrow @nogc { return m_path.length == 0; } /// Tests if the path is absolute. @property bool absolute() const nothrow @nogc { return Format.getAbsolutePrefix(m_path).length > 0; } /// Determines whether the path ends with a path separator (i.e. represents a folder specifically). @property bool endsWithSlash() const nothrow @nogc { return m_path.length > 0 && Format.isSeparator(m_path[$-1]); } /// ditto @property void endsWithSlash(bool v) nothrow { bool ews = this.endsWithSlash; if (!ews && v) m_path ~= Format.defaultSeparator; else if (ews && !v) m_path = m_path[0 .. $-1]; // FIXME?: "/test//" -> "/test/" } /// Iterates over the path by `Segment`. @property PathRange bySegment() const { return PathRange(m_path); } /// Returns the trailing segment of the path. @property Segment head() const { auto s = Format.decodeSegment!Segment(Format.getBackNode(m_path)); auto ret = s.front; while (!s.empty) { s.popFront(); if (!s.empty) ret = s.front; } return ret; } /** Determines if the `parentPath` property is valid. */ bool hasParentPath() const @nogc { auto b = Format.getBackNode(m_path); return b.length < m_path.length; } /** Returns a prefix of this path, where the last segment has been dropped. Throws: An `Exception` is thrown if this path has no parent path. Use `hasParentPath` to test this upfront. */ GenericPath parentPath() const @nogc { auto b = Format.getBackNode(m_path); static const Exception e = new Exception("Path has no parent path"); if (b.length >= m_path.length) throw e; return GenericPath.fromTrustedString(m_path[0 .. $ - b.length]); } /** Removes any redundant path segments and replaces all separators by the default one. The resulting path representation is suitable for basic semantic comparison to other normalized paths. Note that there are still ways for different normalized paths to represent the same file. Examples of this are the tilde shortcut to the home directory on Unix and Linux operating systems, symbolic or hard links, and possibly environment variables are examples of this. Throws: Throws an `Exception` if an absolute path contains parent directory segments ("..") that lead to a path that is a parent path of the root path. */ void normalize() { import std.array : appender, join; Segment[] newnodes; bool got_non_sep = false; foreach (n; this.bySegment) { if (n.hasSeparator) n.separator = Format.defaultSeparator; if (!got_non_sep) { if (n.name == "") newnodes ~= n; else got_non_sep = true; } switch (n.name) { default: newnodes ~= n; break; case "", ".": break; case "..": enforce(!this.absolute || newnodes.length > 0, "Path goes below root node."); if (newnodes.length > 0 && newnodes[$-1].name != "..") newnodes = newnodes[0 .. $-1]; else newnodes ~= n; break; } } auto dst = appender!string; Format.toString(newnodes, dst); m_path = dst.data; } /// unittest { auto path = WindowsPath("C:\\test/foo/./bar///../baz"); path.normalize(); assert(path.toString() == "C:\\test\\foo\\baz", path.toString()); path = WindowsPath("foo/../../bar/"); path.normalize(); assert(path.toString() == "..\\bar\\"); } /// Returns the string representation of the path. string toString() const nothrow @nogc { return m_path; } /// Computes a hash sum, enabling storage within associative arrays. hash_t toHash() const nothrow @trusted { try return typeid(string).getHash(&m_path); catch (Exception e) assert(false, "getHash for string throws!?"); } /** Compares two path objects. Note that the exact string representation of the two paths will be compared. To get a basic semantic comparison, the paths must be normalized first. */ bool opEquals(GenericPath other) const @nogc { return this.m_path == other.m_path; } /** Converts the path to a different path format. Throws: A `PathValidationException` will be thrown if the path is not representable in the requested path format. This can happen especially when converting Posix or Internet paths to windows paths, since Windows paths cannot contain a number of characters that the other representations can, in theory. */ P opCast(P)() const if (isInstanceOf!(.GenericPath, P)) { static if (is(P == GenericPath)) return this; else return P(this.bySegment.map!(n => cast(P.Segment)n)); } /** Concatenates two paths. The right hand side must represent a relative path. */ GenericPath opBinary(string op : "~")(string subpath) const { return this ~ GenericPath(subpath); } /// ditto GenericPath opBinary(string op : "~")(Segment subpath) const { return this ~ GenericPath(subpath); } /// ditto GenericPath opBinary(string op : "~", F)(GenericPath!F.Segment subpath) const { return this ~ cast(Segment)(subpath); } /// ditto GenericPath opBinary(string op : "~")(GenericPath subpath) const nothrow { assert(!subpath.absolute || m_path.length == 0, "Cannot append absolute path."); if (endsWithSlash || empty) return GenericPath.fromTrustedString(m_path ~ subpath.m_path); else return GenericPath.fromTrustedString(m_path ~ Format.defaultSeparator ~ subpath.m_path); } /// ditto GenericPath opBinary(string op : "~", F)(GenericPath!F subpath) const if (!is(F == Format)) { return this ~ cast(GenericPath)subpath; } /// ditto GenericPath opBinary(string op : "~", R)(R entries) const nothrow if (isInputRange!R && is(ElementType!R : Segment)) { return this ~ GenericPath(entries); } /// Appends a relative path to this path. void opOpAssign(string op : "~", T)(T op) { this = this ~ op; } /** Tests whether the given path is a prefix of this path. Any path separators will be ignored during the comparison. */ bool startsWith(GenericPath prefix) const nothrow { return bySegment.map!(n => n.name).startsWith(prefix.bySegment.map!(n => n.name)); } } unittest { import std.algorithm.comparison : equal; assert(PosixPath("hello/world").bySegment.equal([PosixPath.Segment("hello",'/'), PosixPath.Segment("world")])); assert(PosixPath("/hello/world/").bySegment.equal([PosixPath.Segment("",'/'), PosixPath.Segment("hello",'/'), PosixPath.Segment("world",'/')])); assert(PosixPath("hello\\world").bySegment.equal([PosixPath.Segment("hello\\world")])); assert(WindowsPath("hello/world").bySegment.equal([WindowsPath.Segment("hello",'/'), WindowsPath.Segment("world")])); assert(WindowsPath("/hello/world/").bySegment.equal([WindowsPath.Segment("",'/'), WindowsPath.Segment("hello",'/'), WindowsPath.Segment("world",'/')])); assert(WindowsPath("hello\\w/orld").bySegment.equal([WindowsPath.Segment("hello",'\\'), WindowsPath.Segment("w",'/'), WindowsPath.Segment("orld")])); assert(WindowsPath("hello/w\\orld").bySegment.equal([WindowsPath.Segment("hello",'/'), WindowsPath.Segment("w",'\\'), WindowsPath.Segment("orld")])); } unittest { import std.algorithm.comparison : equal; { auto unc = "\\\\server\\share\\path"; auto uncp = WindowsPath(unc); assert(uncp.absolute); uncp.normalize(); version(Windows) assert(uncp.toNativeString() == unc); assert(uncp.absolute); assert(!uncp.endsWithSlash); } { auto abspath = "/test/path/"; auto abspathp = PosixPath(abspath); assert(abspathp.toString() == abspath); version(Windows) {} else assert(abspathp.toNativeString() == abspath); assert(abspathp.absolute); assert(abspathp.endsWithSlash); alias S = PosixPath.Segment; assert(abspathp.bySegment.equal([S("", '/'), S("test", '/'), S("path", '/')])); } { auto relpath = "test/path/"; auto relpathp = PosixPath(relpath); assert(relpathp.toString() == relpath); version(Windows) assert(relpathp.toNativeString() == "test/path/"); else assert(relpathp.toNativeString() == relpath); assert(!relpathp.absolute); assert(relpathp.endsWithSlash); alias S = PosixPath.Segment; assert(relpathp.bySegment.equal([S("test", '/'), S("path", '/')])); } { auto winpath = "C:\\windows\\test"; auto winpathp = WindowsPath(winpath); assert(winpathp.toString() == "C:\\windows\\test"); assert((cast(PosixPath)winpathp).toString() == "/C:/windows/test", (cast(PosixPath)winpathp).toString()); version(Windows) assert(winpathp.toNativeString() == winpath); else assert(winpathp.toNativeString() == "/C:/windows/test"); assert(winpathp.absolute); assert(!winpathp.endsWithSlash); alias S = WindowsPath.Segment; assert(winpathp.bySegment.equal([S("", '/'), S("C:", '\\'), S("windows", '\\'), S("test")])); } { auto dotpath = "/test/../test2/././x/y"; auto dotpathp = PosixPath(dotpath); assert(dotpathp.toString() == "/test/../test2/././x/y"); dotpathp.normalize(); assert(dotpathp.toString() == "/test2/x/y", dotpathp.toString()); } { auto dotpath = "/test/..////test2//./x/y"; auto dotpathp = PosixPath(dotpath); assert(dotpathp.toString() == "/test/..////test2//./x/y"); dotpathp.normalize(); assert(dotpathp.toString() == "/test2/x/y"); } assert(WindowsPath("C:\\Windows").absolute); assert((cast(InetPath)WindowsPath("C:\\Windows")).toString() == "/C:/Windows"); assert((WindowsPath("C:\\Windows") ~ InetPath("test/this")).toString() == "C:\\Windows\\test/this"); assert(InetPath("/C:/Windows").absolute); assert((cast(WindowsPath)InetPath("/C:/Windows")).toString() == "C:/Windows"); assert((InetPath("/C:/Windows") ~ WindowsPath("test\\this")).toString() == "/C:/Windows/test/this"); assert((InetPath("") ~ WindowsPath("foo\\bar")).toString() == "foo/bar"); assert((cast(InetPath)WindowsPath("C:\\Windows\\")).toString() == "/C:/Windows/"); assert(NativePath("").empty); assert(PosixPath("/") ~ NativePath("foo/bar") == PosixPath("/foo/bar")); assert(PosixPath("") ~ NativePath("foo/bar") == PosixPath("foo/bar")); assert(PosixPath("foo") ~ NativePath("bar") == PosixPath("foo/bar")); assert(PosixPath("foo/") ~ NativePath("bar") == PosixPath("foo/bar")); } @safe unittest { import std.array : appender; auto app = appender!(PosixPath[]); void test1(PosixPath p) { app.put(p); } void test2(PosixPath[] ps) { app.put(ps); } //void test3(const(PosixPath) p) { app.put(p); } // DMD issue 17251 //void test4(const(PosixPath)[] ps) { app.put(ps); } } unittest { import std.algorithm.comparison : equal; import std.exception : assertThrown, assertNotThrown; assertThrown!PathValidationException(WindowsPath.Segment("foo/bar")); assertThrown!PathValidationException(PosixPath.Segment("foo/bar")); assertNotThrown!PathValidationException(InetPath.Segment("foo/bar")); auto p = InetPath("/foo%2fbar/"); assert(p.bySegment.equal([InetPath.Segment("",'/'), InetPath.Segment("foo/bar",'/')])); p ~= InetPath.Segment("baz/bam"); assert(p.toString() == "/foo%2fbar/baz%2Fbam", p.toString); } unittest { assert(!PosixPath("").hasParentPath); assert(!PosixPath("/").hasParentPath); assert(!PosixPath("foo\\bar").hasParentPath); assert(PosixPath("foo/bar").parentPath.toString() == "foo/"); assert(PosixPath("./foo").parentPath.toString() == "./"); assert(PosixPath("./foo").parentPath.toString() == "./"); assert(!WindowsPath("").hasParentPath); assert(!WindowsPath("/").hasParentPath); assert(WindowsPath("foo\\bar").parentPath.toString() == "foo\\"); assert(WindowsPath("foo/bar").parentPath.toString() == "foo/"); assert(WindowsPath("./foo").parentPath.toString() == "./"); assert(WindowsPath("./foo").parentPath.toString() == "./"); assert(!InetPath("").hasParentPath); assert(!InetPath("/").hasParentPath); assert(InetPath("foo/bar").parentPath.toString() == "foo/"); assert(InetPath("foo/bar%2Fbaz").parentPath.toString() == "foo/"); assert(InetPath("./foo").parentPath.toString() == "./"); assert(InetPath("./foo").parentPath.toString() == "./"); } unittest { assert(WindowsPath([WindowsPath.Segment("foo"), WindowsPath.Segment("bar")]).toString() == "foo\\bar"); } /// Thrown when an invalid string representation of a path is detected. class PathValidationException : Exception { this(string text, string file = __FILE__, size_t line = cast(size_t)__LINE__, Throwable next = null) pure nothrow @nogc @safe { super(text, file, line, next); } } /** Implements Windows path semantics. See_also: `WindowsPath` */ struct WindowsPathFormat { static void toString(I, O)(I segments, O dst) if (isInputRange!I && isOutputRange!(O, char)) { char sep(char s) { return isSeparator(s) ? s : defaultSeparator; } if (segments.empty) return; if (segments.front.name == "" && segments.front.separator) { auto s = segments.front.separator; segments.popFront(); if (segments.empty || !segments.front.name.endsWith(":")) dst.put(sep(s)); } char lastsep = '\0'; bool first = true; foreach (s; segments) { if (!first || lastsep) dst.put(sep(lastsep)); else first = false; dst.put(s.name); lastsep = s.separator; } if (lastsep) dst.put(sep(lastsep)); } unittest { import std.array : appender; struct Segment { string name; char separator = 0; static Segment fromTrustedString(string str, char sep = 0) pure nothrow @nogc { return Segment(str, sep); }} string str(Segment[] segs...) { auto ret = appender!string; toString(segs, ret); return ret.data; } assert(str() == ""); assert(str(Segment("",'/')) == "/"); assert(str(Segment("",'/'), Segment("foo")) == "/foo"); assert(str(Segment("",'\\')) == "\\"); assert(str(Segment("foo",'/'), Segment("bar",'/')) == "foo/bar/"); assert(str(Segment("",'/'), Segment("foo",'\0')) == "/foo"); assert(str(Segment("",'\\'), Segment("foo",'\\')) == "\\foo\\"); assert(str(Segment("f oo")) == "f oo"); assert(str(Segment("",'\\'), Segment("C:")) == "C:"); assert(str(Segment("",'\\'), Segment("C:", '/')) == "C:/"); assert(str(Segment("foo",'\\'), Segment("C:")) == "foo\\C:"); assert(str(Segment("foo"), Segment("bar")) == "foo\\bar"); } @safe nothrow pure: enum defaultSeparator = '\\'; static bool isSeparator(dchar ch) @nogc { import std.algorithm.comparison : among; return ch.among!('\\', '/') != 0; } static string getAbsolutePrefix(string path) @nogc { if (!path.length) return null; if (isSeparator(path[0])) { return path[0 .. 1]; } foreach (i; 1 .. path.length) if (isSeparator(path[i])) { if (path[i-1] == ':') return path[0 .. i+1]; break; } return path[$-1] == ':' ? path : null; } unittest { assert(getAbsolutePrefix("test") == ""); assert(getAbsolutePrefix("test/") == ""); assert(getAbsolutePrefix("/test") == "/"); assert(getAbsolutePrefix("\\test") == "\\"); assert(getAbsolutePrefix("C:\\") == "C:\\"); assert(getAbsolutePrefix("C:") == "C:"); assert(getAbsolutePrefix("C:\\test") == "C:\\"); assert(getAbsolutePrefix("C:\\test\\") == "C:\\"); assert(getAbsolutePrefix("C:/") == "C:/"); assert(getAbsolutePrefix("C:/test") == "C:/"); assert(getAbsolutePrefix("C:/test/") == "C:/"); assert(getAbsolutePrefix("\\\\server") == "\\"); assert(getAbsolutePrefix("\\\\server\\") == "\\"); assert(getAbsolutePrefix("\\\\.\\") == "\\"); assert(getAbsolutePrefix("\\\\?\\") == "\\"); } static string getFrontNode(string path) @nogc { foreach (i; 0 .. path.length) if (isSeparator(path[i])) return path[0 .. i+1]; return path; } unittest { assert(getFrontNode("") == ""); assert(getFrontNode("/bar") == "/"); assert(getFrontNode("foo/bar") == "foo/"); assert(getFrontNode("foo/") == "foo/"); assert(getFrontNode("foo") == "foo"); assert(getFrontNode("\\bar") == "\\"); assert(getFrontNode("foo\\bar") == "foo\\"); assert(getFrontNode("foo\\") == "foo\\"); } static string getBackNode(string path) @nogc { if (!path.length) return path; foreach_reverse (i; 0 .. path.length-1) if (isSeparator(path[i])) return path[i+1 .. $]; return path; } unittest { assert(getBackNode("") == ""); assert(getBackNode("/bar") == "bar"); assert(getBackNode("foo/bar") == "bar"); assert(getBackNode("foo/") == "foo/"); assert(getBackNode("foo") == "foo"); assert(getBackNode("\\bar") == "bar"); assert(getBackNode("foo\\bar") == "bar"); assert(getBackNode("foo\\") == "foo\\"); } static auto decodeSegment(S)(string segment) { static struct R { S[2] items; size_t i; this(S s) { i = 1; items[i] = s; } this(S a, S b) { i = 0; items[0] = a; items[1] = b; } @property ref S front() { return items[i]; } @property bool empty() const { return i >= items.length; } void popFront() { i++; } } assert(segment.length > 0, "Path segment string must not be empty."); char sep = '\0'; if (!segment.length) return R(S.fromTrustedString(null)); if (isSeparator(segment[$-1])) { sep = segment[$-1]; segment = segment[0 .. $-1]; } // output an absolute marker segment for "C:\" style absolute segments if (segment.length > 0 && segment[$-1] == ':') return R(S.fromTrustedString("", '/'), S.fromTrustedString(segment, sep)); return R(S.fromTrustedString(segment, sep)); } unittest { import std.algorithm.comparison : equal; struct Segment { string name; char separator = 0; static Segment fromTrustedString(string str, char sep = 0) pure nothrow @nogc { return Segment(str, sep); }} assert(decodeSegment!Segment("foo").equal([Segment("foo")])); assert(decodeSegment!Segment("foo/").equal([Segment("foo", '/')])); assert(decodeSegment!Segment("fo%20o\\").equal([Segment("fo%20o", '\\')])); assert(decodeSegment!Segment("C:\\").equal([Segment("",'/'), Segment("C:", '\\')])); assert(decodeSegment!Segment("bar:\\").equal([Segment("",'/'), Segment("bar:", '\\')])); } static string validatePath(string path) @nogc { import std.algorithm.comparison : among; // skip UNC prefix if (path.startsWith("\\\\")) { path = path[2 .. $]; while (path.length && !isSeparator(path[0])) { if (path[0] < 32 || path[0].among('<', '>', '|')) return "Invalid character in UNC host name."; path = path[1 .. $]; } if (path.length) path = path[1 .. $]; } // stricter validation for the rest bool had_sep = false; foreach (i, char c; path) { if (c < 32 || c.among!('<', '>', '|', '?')) return "Invalid character in path."; if (isSeparator(c)) had_sep = true; else if (c == ':' && (had_sep || i+1 < path.length && !isSeparator(path[i+1]))) return "Colon in path that is not part of a drive name."; } return null; } static string validateDecodedSegment(string segment) @nogc { auto pe = validatePath(segment); if (pe) return pe; foreach (char c; segment) if (isSeparator(c)) return "Path segment contains separator character."; return null; } unittest { assert(validatePath("c:\\foo") is null); assert(validatePath("\\\\?\\c:\\foo") is null); assert(validatePath("//?\\c:\\foo") !is null); assert(validatePath("-foo/bar\\*\\baz") is null); assert(validatePath("foo\0bar") !is null); assert(validatePath("foo\tbar") !is null); assert(validatePath("\\c:\\foo") !is null); assert(validatePath("c:d\\foo") !is null); assert(validatePath("foo\\b:ar") !is null); assert(validatePath("foo\\bar:\\baz") !is null); } } /** Implements Unix/Linux path semantics. See_also: `WindowsPath` */ struct PosixPathFormat { static void toString(I, O)(I segments, O dst) { char lastsep = '\0'; bool first = true; foreach (s; segments) { if (!first || lastsep) dst.put('/'); else first = false; dst.put(s.name); lastsep = s.separator; } if (lastsep) dst.put('/'); } unittest { import std.array : appender; struct Segment { string name; char separator = 0; static Segment fromTrustedString(string str, char sep = 0) pure nothrow @nogc { return Segment(str, sep); }} string str(Segment[] segs...) { auto ret = appender!string; toString(segs, ret); return ret.data; } assert(str() == ""); assert(str(Segment("",'/')) == "/"); assert(str(Segment("foo",'/'), Segment("bar",'/')) == "foo/bar/"); assert(str(Segment("",'/'), Segment("foo",'\0')) == "/foo"); assert(str(Segment("",'\\'), Segment("foo",'\\')) == "/foo/"); assert(str(Segment("f oo")) == "f oo"); assert(str(Segment("foo"), Segment("bar")) == "foo/bar"); } @safe nothrow pure: enum defaultSeparator = '/'; static bool isSeparator(dchar ch) @nogc { return ch == '/'; } static string getAbsolutePrefix(string path) @nogc { if (path.length > 0 && path[0] == '/') return path[0 .. 1]; return null; } unittest { assert(getAbsolutePrefix("/") == "/"); assert(getAbsolutePrefix("/test") == "/"); assert(getAbsolutePrefix("/test/") == "/"); assert(getAbsolutePrefix("test/") == ""); assert(getAbsolutePrefix("") == ""); assert(getAbsolutePrefix("./") == ""); } static string getFrontNode(string path) @nogc { import std.string : indexOf; auto idx = path.indexOf('/'); return idx < 0 ? path : path[0 .. idx+1]; } unittest { assert(getFrontNode("") == ""); assert(getFrontNode("/bar") == "/"); assert(getFrontNode("foo/bar") == "foo/"); assert(getFrontNode("foo/") == "foo/"); assert(getFrontNode("foo") == "foo"); } static string getBackNode(string path) @nogc { if (!path.length) return path; foreach_reverse (i; 0 .. path.length-1) if (path[i] == '/') return path[i+1 .. $]; return path; } unittest { assert(getBackNode("") == ""); assert(getBackNode("/bar") == "bar"); assert(getBackNode("foo/bar") == "bar"); assert(getBackNode("foo/") == "foo/"); assert(getBackNode("foo") == "foo"); } static string validatePath(string path) @nogc { foreach (char c; path) if (c == '\0') return "Invalid NUL character in file name"; return null; } static string validateDecodedSegment(string segment) @nogc { auto pe = validatePath(segment); if (pe) return pe; foreach (char c; segment) if (isSeparator(c)) return "Path segment contains separator character."; return null; } unittest { assert(validatePath("-foo/bar*/baz?") is null); assert(validatePath("foo\0bar") !is null); } static auto decodeSegment(S)(string segment) { assert(segment.length > 0, "Path segment string must not be empty."); import std.range : only; if (!segment.length) return only(S.fromTrustedString(null, '/')); if (segment[$-1] == '/') return only(S.fromTrustedString(segment[0 .. $-1], '/')); return only(S.fromTrustedString(segment)); } unittest { import std.algorithm.comparison : equal; struct Segment { string name; char separator = 0; static Segment fromTrustedString(string str, char sep = 0) pure nothrow @nogc { return Segment(str, sep); }} assert(decodeSegment!Segment("foo").equal([Segment("foo")])); assert(decodeSegment!Segment("foo/").equal([Segment("foo", '/')])); assert(decodeSegment!Segment("fo%20o\\").equal([Segment("fo%20o\\")])); } } /** Implements URI/Internet path semantics. See_also: `WindowsPath` */ struct InetPathFormat { static void toString(I, O)(I segments, O dst) { import std.format : formattedWrite; char lastsep = '\0'; bool first = true; foreach (e; segments) { if (!first || lastsep) dst.put('/'); else first = false; foreach (char c; e.name) { switch (c) { default: dst.formattedWrite("%%%02X", c); break; case 'a': .. case 'z': case 'A': .. case 'Z': case '0': .. case '9': case '-', '.', '_', '~': case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': case ':', '@': dst.put(c); break; } } lastsep = e.separator; } if (lastsep) dst.put('/'); } unittest { import std.array : appender; struct Segment { string name; char separator = 0; static Segment fromTrustedString(string str, char sep = 0) pure nothrow @nogc { return Segment(str, sep); }} string str(Segment[] segs...) { auto ret = appender!string; toString(segs, ret); return ret.data; } assert(str() == ""); assert(str(Segment("",'/')) == "/"); assert(str(Segment("foo",'/'), Segment("bar",'/')) == "foo/bar/"); assert(str(Segment("",'/'), Segment("foo",'\0')) == "/foo"); assert(str(Segment("",'\\'), Segment("foo",'\\')) == "/foo/"); assert(str(Segment("f oo")) == "f%20oo"); assert(str(Segment("foo"), Segment("bar")) == "foo/bar"); } @safe pure nothrow: enum defaultSeparator = '/'; static bool isSeparator(dchar ch) @nogc { return ch == '/'; } static string getAbsolutePrefix(string path) @nogc { if (path.length > 0 && path[0] == '/') return path[0 .. 1]; return null; } unittest { assert(getAbsolutePrefix("/") == "/"); assert(getAbsolutePrefix("/test") == "/"); assert(getAbsolutePrefix("/test/") == "/"); assert(getAbsolutePrefix("test/") == ""); assert(getAbsolutePrefix("") == ""); assert(getAbsolutePrefix("./") == ""); } static string getFrontNode(string path) @nogc { import std.string : indexOf; auto idx = path.indexOf('/'); return idx < 0 ? path : path[0 .. idx+1]; } unittest { assert(getFrontNode("") == ""); assert(getFrontNode("/bar") == "/"); assert(getFrontNode("foo/bar") == "foo/"); assert(getFrontNode("foo/") == "foo/"); assert(getFrontNode("foo") == "foo"); } static string getBackNode(string path) @nogc { if (!path.length) return path; foreach_reverse (i; 0 .. path.length-1) if (path[i] == '/') return path[i+1 .. $]; return path; } unittest { assert(getBackNode("") == ""); assert(getBackNode("/bar") == "bar"); assert(getBackNode("foo/bar") == "bar"); assert(getBackNode("foo/") == "foo/"); assert(getBackNode("foo") == "foo"); } static string validatePath(string path) @nogc { for (size_t i = 0; i < path.length; i++) { switch (path[i]) { default: return "Invalid character in internet path."; // unreserved case 'A': .. case 'Z': case 'a': .. case 'z': case '0': .. case '9': case '-', '.', '_', '~': // subdelims case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // additional delims case ':', '@': // segment delimiter case '/': break; case '%': // pct encoding if (path.length < i+3) return "Unterminated percent encoding sequence in internet path."; foreach (j; 0 .. 2) { switch (path[++i]) { default: return "Invalid percent encoding sequence in internet path."; case '0': .. case '9': case 'a': .. case 'f': case 'A': .. case 'F': break; } } break; } } return null; } static string validateDecodedSegment(string seg) @nogc { return null; } unittest { assert(validatePath("") is null); assert(validatePath("/") is null); assert(validatePath("/test") is null); assert(validatePath("test") is null); assert(validatePath("/C:/test") is null); assert(validatePath("/test%ab") is null); assert(validatePath("/test%ag") !is null); assert(validatePath("/test%a") !is null); assert(validatePath("/test%") !is null); assert(validatePath("/test§") !is null); assert(validatePath("föö") !is null); } static auto decodeSegment(S)(string segment) { import std.array : appender; import std.format : formattedRead; import std.range : only; import std.string : indexOf; static int hexDigit(char ch) @safe nothrow @nogc { assert(ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f'); if (ch >= '0' && ch <= '9') return ch - '0'; else if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; else return ch - 'A' + 10; } static string urlDecode(string s) @safe nothrow { auto idx = s.indexOf('%'); if (idx < 0) return s; auto ret = appender!string; ret.put(s[0 .. idx]); for (size_t i = idx; i < s.length; i++) { if (s[i] == '%') { assert(i+2 < s.length, "segment string not validated!?"); ret.put(cast(char)(hexDigit(s[i+1]) << 4 | hexDigit(s[i+2]))); i += 2; } else ret.put(s[i]); } return ret.data; } if (!segment.length) return only(S.fromTrustedString(null)); if (segment[$-1] == '/') return only(S.fromTrustedString(urlDecode(segment[0 .. $-1]), '/')); return only(S.fromTrustedString(urlDecode(segment))); } unittest { import std.algorithm.comparison : equal; struct Segment { string name; char separator = 0; static Segment fromTrustedString(string str, char sep = 0) pure nothrow @nogc { return Segment(str, sep); }} assert(decodeSegment!Segment("foo").equal([Segment("foo")])); assert(decodeSegment!Segment("foo/").equal([Segment("foo", '/')])); assert(decodeSegment!Segment("fo%20o\\").equal([Segment("fo o\\")])); assert(decodeSegment!Segment("foo%20").equal([Segment("foo ")])); } }