forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.d
5171 lines (4378 loc) · 143 KB
/
file.d
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
// Written in the D programming language.
/**
Utilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module $(MREF std, stdio).
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD General) $(TD
$(LREF exists)
$(LREF isDir)
$(LREF isFile)
$(LREF isSymlink)
$(LREF rename)
$(LREF thisExePath)
))
$(TR $(TD Directories) $(TD
$(LREF chdir)
$(LREF dirEntries)
$(LREF getcwd)
$(LREF mkdir)
$(LREF mkdirRecurse)
$(LREF rmdir)
$(LREF rmdirRecurse)
$(LREF tempDir)
))
$(TR $(TD Files) $(TD
$(LREF append)
$(LREF copy)
$(LREF read)
$(LREF readText)
$(LREF remove)
$(LREF slurp)
$(LREF write)
))
$(TR $(TD Symlinks) $(TD
$(LREF symlink)
$(LREF readLink)
))
$(TR $(TD Attributes) $(TD
$(LREF attrIsDir)
$(LREF attrIsFile)
$(LREF attrIsSymlink)
$(LREF getAttributes)
$(LREF getLinkAttributes)
$(LREF getSize)
$(LREF setAttributes)
))
$(TR $(TD Timestamp) $(TD
$(LREF getTimes)
$(LREF getTimesWin)
$(LREF setTimes)
$(LREF timeLastModified)
))
$(TR $(TD Other) $(TD
$(LREF DirEntry)
$(LREF FileException)
$(LREF PreserveAttributes)
$(LREF SpanMode)
))
)
Copyright: Copyright Digital Mars 2007 - 2011.
See_Also: The $(HTTP ddili.org/ders/d.en/files.html, official tutorial) for an
introduction to working with files in D, module
$(MREF std, stdio) for opening files and manipulating them via handles,
and module $(MREF std, path) for manipulating path strings.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP digitalmars.com, Walter Bright),
$(HTTP erdani.org, Andrei Alexandrescu),
$(HTTP jmdavisprog.com, Jonathan M Davis)
Source: $(PHOBOSSRC std/file.d)
*/
module std.file;
import core.stdc.errno, core.stdc.stdlib, core.stdc.string;
import core.time : abs, dur, hnsecs, seconds;
import std.datetime.date : DateTime;
import std.datetime.systime : Clock, SysTime, unixTimeToStdTime;
import std.internal.cstring;
import std.meta;
import std.range.primitives;
import std.traits;
import std.typecons;
version (Windows)
{
import core.sys.windows.windows, std.windows.syserror;
}
else version (Posix)
{
import core.sys.posix.dirent, core.sys.posix.fcntl, core.sys.posix.sys.stat,
core.sys.posix.sys.time, core.sys.posix.unistd, core.sys.posix.utime;
}
else
static assert(false, "Module " ~ .stringof ~ " not implemented for this OS.");
// Character type used for operating system filesystem APIs
version (Windows)
{
private alias FSChar = wchar;
}
else version (Posix)
{
private alias FSChar = char;
}
else
static assert(0);
// Purposefully not documented. Use at your own risk
@property string deleteme() @safe
{
import std.conv : to;
import std.path : buildPath;
import std.process : thisProcessID;
static _deleteme = "deleteme.dmd.unittest.pid";
static _first = true;
if (_first)
{
_deleteme = buildPath(tempDir(), _deleteme) ~ to!string(thisProcessID);
_first = false;
}
return _deleteme;
}
version(unittest) private struct TestAliasedString
{
string get() @safe @nogc pure nothrow { return _s; }
alias get this;
@disable this(this);
string _s;
}
version(Android)
{
package enum system_directory = "/system/etc";
package enum system_file = "/system/etc/hosts";
}
else version(Posix)
{
package enum system_directory = "/usr/include";
package enum system_file = "/usr/include/assert.h";
}
/++
Exception thrown for file I/O errors.
+/
class FileException : Exception
{
import std.conv : text, to;
/++
OS error code.
+/
immutable uint errno;
private this(scope const(char)[] name, scope const(char)[] msg, string file, size_t line, uint errno) @safe pure
{
if (msg.empty)
super(name.idup, file, line);
else
super(text(name, ": ", msg), file, line);
this.errno = errno;
}
/++
Constructor which takes an error message.
Params:
name = Name of file for which the error occurred.
msg = Message describing the error.
file = The file where the error occurred.
line = The _line where the error occurred.
+/
this(scope const(char)[] name, scope const(char)[] msg, string file = __FILE__, size_t line = __LINE__) @safe pure
{
this(name, msg, file, line, 0);
}
/++
Constructor which takes the error number ($(LUCKY GetLastError)
in Windows, $(D_PARAM errno) in Posix).
Params:
name = Name of file for which the error occurred.
errno = The error number.
file = The file where the error occurred.
Defaults to `__FILE__`.
line = The _line where the error occurred.
Defaults to `__LINE__`.
+/
version(Windows) this(scope const(char)[] name,
uint errno = .GetLastError(),
string file = __FILE__,
size_t line = __LINE__) @safe
{
this(name, sysErrorString(errno), file, line, errno);
}
else version(Posix) this(scope const(char)[] name,
uint errno = .errno,
string file = __FILE__,
size_t line = __LINE__) @trusted
{
import std.exception : errnoString;
this(name, errnoString(errno), file, line, errno);
}
}
///
@safe unittest
{
import std.exception : assertThrown;
assertThrown!FileException("non.existing.file.".readText);
}
private T cenforce(T)(T condition, lazy scope const(char)[] name, string file = __FILE__, size_t line = __LINE__)
{
if (condition)
return condition;
version (Windows)
{
throw new FileException(name, .GetLastError(), file, line);
}
else version (Posix)
{
throw new FileException(name, .errno, file, line);
}
}
version (Windows)
@trusted
private T cenforce(T)(T condition, scope const(char)[] name, scope const(FSChar)* namez,
string file = __FILE__, size_t line = __LINE__)
{
if (condition)
return condition;
if (!name)
{
import core.stdc.wchar_ : wcslen;
import std.conv : to;
auto len = namez ? wcslen(namez) : 0;
name = to!string(namez[0 .. len]);
}
throw new FileException(name, .GetLastError(), file, line);
}
version (Posix)
@trusted
private T cenforce(T)(T condition, scope const(char)[] name, scope const(FSChar)* namez,
string file = __FILE__, size_t line = __LINE__)
{
if (condition)
return condition;
if (!name)
{
import core.stdc.string : strlen;
auto len = namez ? strlen(namez) : 0;
name = namez[0 .. len].idup;
}
throw new FileException(name, .errno, file, line);
}
@safe unittest
{
// issue 17102
try
{
cenforce(false, null, null,
__FILE__, __LINE__);
}
catch (FileException) {}
}
/* **********************************
* Basic File operations.
*/
/********************************************
Read entire contents of file `name` and returns it as an untyped
array. If the file size is larger than `upTo`, only `upTo`
bytes are _read.
Params:
name = string or range of characters representing the file _name
upTo = if present, the maximum number of bytes to _read
Returns: Untyped array of bytes _read.
Throws: $(LREF FileException) on error.
*/
void[] read(R)(R name, size_t upTo = size_t.max)
if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isInfinite!R &&
!isConvertibleToString!R)
{
static if (isNarrowString!R && is(Unqual!(ElementEncodingType!R) == char))
return readImpl(name, name.tempCString!FSChar(), upTo);
else
return readImpl(null, name.tempCString!FSChar(), upTo);
}
///
@safe unittest
{
import std.utf : byChar;
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file
assert(read(deleteme, 2) == "12");
assert(read(deleteme.byChar) == "1234");
assert((cast(const(ubyte)[])read(deleteme)).length == 4);
}
/// ditto
void[] read(R)(auto ref R name, size_t upTo = size_t.max)
if (isConvertibleToString!R)
{
return read!(StringTypeOf!R)(name, upTo);
}
@safe unittest
{
static assert(__traits(compiles, read(TestAliasedString(null))));
}
version (Posix) private void[] readImpl(scope const(char)[] name, scope const(FSChar)* namez,
size_t upTo = size_t.max) @trusted
{
import core.memory : GC;
import std.algorithm.comparison : min;
import std.array : uninitializedArray;
import std.conv : to;
import std.experimental.checkedint : checked;
// A few internal configuration parameters {
enum size_t
minInitialAlloc = 1024 * 4,
maxInitialAlloc = size_t.max / 2,
sizeIncrement = 1024 * 16,
maxSlackMemoryAllowed = 1024;
// }
immutable fd = core.sys.posix.fcntl.open(namez,
core.sys.posix.fcntl.O_RDONLY);
cenforce(fd != -1, name);
scope(exit) core.sys.posix.unistd.close(fd);
stat_t statbuf = void;
cenforce(fstat(fd, &statbuf) == 0, name, namez);
immutable initialAlloc = min(upTo, to!size_t(statbuf.st_size
? min(statbuf.st_size + 1, maxInitialAlloc)
: minInitialAlloc));
void[] result = uninitializedArray!(ubyte[])(initialAlloc);
scope(failure) GC.free(result.ptr);
auto size = checked(size_t(0));
for (;;)
{
immutable actual = core.sys.posix.unistd.read(fd, result.ptr + size.get,
(min(result.length, upTo) - size).get);
cenforce(actual != -1, name, namez);
if (actual == 0) break;
size += actual;
if (size >= upTo) break;
if (size < result.length) continue;
immutable newAlloc = size + sizeIncrement;
result = GC.realloc(result.ptr, newAlloc.get, GC.BlkAttr.NO_SCAN)[0 .. newAlloc.get];
}
return result.length - size >= maxSlackMemoryAllowed
? GC.realloc(result.ptr, size.get, GC.BlkAttr.NO_SCAN)[0 .. size.get]
: result[0 .. size.get];
}
version (Windows) private void[] readImpl(scope const(char)[] name, scope const(FSChar)* namez,
size_t upTo = size_t.max) @safe
{
import core.memory : GC;
import std.algorithm.comparison : min;
import std.array : uninitializedArray;
static trustedCreateFileW(scope const(wchar)* namez, DWORD dwDesiredAccess, DWORD dwShareMode,
SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) @trusted
{
return CreateFileW(namez, dwDesiredAccess, dwShareMode,
lpSecurityAttributes, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
}
static trustedCloseHandle(HANDLE hObject) @trusted
{
return CloseHandle(hObject);
}
static trustedGetFileSize(HANDLE hFile, out ulong fileSize) @trusted
{
DWORD sizeHigh;
DWORD sizeLow = GetFileSize(hFile, &sizeHigh);
const bool result = sizeLow != INVALID_FILE_SIZE;
if (result)
fileSize = makeUlong(sizeLow, sizeHigh);
return result;
}
static trustedReadFile(HANDLE hFile, void *lpBuffer, ulong nNumberOfBytesToRead) @trusted
{
// Read by chunks of size < 4GB (Windows API limit)
ulong totalNumRead = 0;
while (totalNumRead != nNumberOfBytesToRead)
{
const uint chunkSize = min(nNumberOfBytesToRead - totalNumRead, 0xffff_0000);
DWORD numRead = void;
const result = ReadFile(hFile, lpBuffer + totalNumRead, chunkSize, &numRead, null);
if (result == 0 || numRead != chunkSize)
return false;
totalNumRead += chunkSize;
}
return true;
}
alias defaults =
AliasSeq!(GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, (SECURITY_ATTRIBUTES*).init,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init);
auto h = trustedCreateFileW(namez, defaults);
cenforce(h != INVALID_HANDLE_VALUE, name, namez);
scope(exit) cenforce(trustedCloseHandle(h), name, namez);
ulong fileSize = void;
cenforce(trustedGetFileSize(h, fileSize), name, namez);
size_t size = min(upTo, fileSize);
auto buf = uninitializedArray!(ubyte[])(size);
scope(failure)
{
() @trusted { GC.free(buf.ptr); } ();
}
if (size)
cenforce(trustedReadFile(h, &buf[0], size), name, namez);
return buf[0 .. size];
}
version (linux) @safe unittest
{
// A file with "zero" length that doesn't have 0 length at all
auto s = std.file.readText("/proc/sys/kernel/osrelease");
assert(s.length > 0);
//writefln("'%s'", s);
}
@safe unittest
{
scope(exit) if (exists(deleteme)) remove(deleteme);
import std.stdio;
auto f = File(deleteme, "w");
f.write("abcd"); f.flush();
assert(read(deleteme) == "abcd");
}
/++
Reads and validates (using $(REF validate, std, utf)) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
Params:
S = the string type of the file
name = string or range of characters representing the file _name
Returns: Array of characters read.
Throws: $(LREF FileException) if there is an error reading the file,
$(REF UTFException, std, utf) on UTF decoding error.
+/
S readText(S = string, R)(auto ref R name)
if (isSomeString!S && (isInputRange!R && !isInfinite!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R)))
{
import std.algorithm.searching : startsWith;
import std.encoding : getBOM, BOM;
import std.exception : enforce;
import std.format : format;
import std.utf : UTFException, validate;
static if (is(StringTypeOf!R))
StringTypeOf!R filename = name;
else
auto filename = name;
static auto trustedCast(T)(void[] buf) @trusted { return cast(T) buf; }
auto data = trustedCast!(ubyte[])(read(filename));
immutable bomSeq = getBOM(data);
immutable bom = bomSeq.schema;
static if (is(Unqual!(ElementEncodingType!S) == char))
{
with(BOM) switch (bom)
{
case utf16be:
case utf16le: throw new UTFException("UTF-8 requested. BOM is for UTF-16");
case utf32be:
case utf32le: throw new UTFException("UTF-8 requested. BOM is for UTF-32");
default: break;
}
}
else static if (is(Unqual!(ElementEncodingType!S) == wchar))
{
with(BOM) switch (bom)
{
case utf8: throw new UTFException("UTF-16 requested. BOM is for UTF-8");
case utf16be:
{
version(BigEndian)
break;
else
throw new UTFException("BOM is for UTF-16 LE on Big Endian machine");
}
case utf16le:
{
version(BigEndian)
throw new UTFException("BOM is for UTF-16 BE on Little Endian machine");
else
break;
}
case utf32be:
case utf32le: throw new UTFException("UTF-8 requested. BOM is for UTF-32");
default: break;
}
}
else
{
with(BOM) switch (bom)
{
case utf8: throw new UTFException("UTF-16 requested. BOM is for UTF-8");
case utf16be:
case utf16le: throw new UTFException("UTF-8 requested. BOM is for UTF-16");
case utf32be:
{
version(BigEndian)
break;
else
throw new UTFException("BOM is for UTF-32 LE on Big Endian machine");
}
case utf32le:
{
version(BigEndian)
throw new UTFException("BOM is for UTF-32 BE on Little Endian machine");
else
break;
}
default: break;
}
}
if (data.length % ElementEncodingType!S.sizeof != 0)
throw new UTFException(format!"The content of %s is not UTF-%s"(filename, ElementEncodingType!S.sizeof * 8));
auto result = trustedCast!S(data);
validate(result);
return result;
}
/// Read file with UTF-8 text.
@safe unittest
{
write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
assert(content == "abc");
}
// Read file with UTF-8 text but try to read it as UTF-16.
@safe unittest
{
import std.exception : assertThrown;
import std.utf : UTFException;
write(deleteme, "abc");
scope(exit) remove(deleteme);
// Throws because the file is not valid UTF-16.
assertThrown!UTFException(readText!wstring(deleteme));
}
// Read file with UTF-16 text.
@safe unittest
{
import std.algorithm.searching : skipOver;
write(deleteme, "\uFEFFabc"w); // With BOM
scope(exit) remove(deleteme);
auto content = readText!wstring(deleteme);
assert(content == "\uFEFFabc"w);
// Strips BOM if present.
content.skipOver('\uFEFF');
assert(content == "abc"w);
}
@safe unittest
{
static assert(__traits(compiles, readText(TestAliasedString(null))));
}
@system unittest
{
import std.array : appender;
import std.bitmanip : append, Endian;
import std.exception : assertThrown;
import std.path : buildPath;
import std.string : representation;
import std.utf : UTFException;
mkdir(deleteme);
scope(exit) rmdirRecurse(deleteme);
immutable none8 = buildPath(deleteme, "none8");
immutable none16 = buildPath(deleteme, "none16");
immutable utf8 = buildPath(deleteme, "utf8");
immutable utf16be = buildPath(deleteme, "utf16be");
immutable utf16le = buildPath(deleteme, "utf16le");
immutable utf32be = buildPath(deleteme, "utf32be");
immutable utf32le = buildPath(deleteme, "utf32le");
immutable utf7 = buildPath(deleteme, "utf7");
write(none8, "京都市");
write(none16, "京都市"w);
write(utf8, (cast(char[])[0xEF, 0xBB, 0xBF]) ~ "京都市");
{
auto str = "\uFEFF京都市"w;
auto arr = appender!(ubyte[])();
foreach (c; str)
arr.append(c);
write(utf16be, arr.data);
}
{
auto str = "\uFEFF京都市"w;
auto arr = appender!(ubyte[])();
foreach (c; str)
arr.append!(ushort, Endian.littleEndian)(c);
write(utf16le, arr.data);
}
{
auto str = "\U0000FEFF京都市"d;
auto arr = appender!(ubyte[])();
foreach (c; str)
arr.append(c);
write(utf32be, arr.data);
}
{
auto str = "\U0000FEFF京都市"d;
auto arr = appender!(ubyte[])();
foreach (c; str)
arr.append!(uint, Endian.littleEndian)(c);
write(utf32le, arr.data);
}
write(utf7, (cast(ubyte[])[0x2B, 0x2F, 0x76, 0x38, 0x2D]) ~ "foobar".representation);
assertThrown!UTFException(readText(none16));
assert(readText(utf8) == (cast(char[])[0xEF, 0xBB, 0xBF]) ~ "京都市");
assertThrown!UTFException(readText(utf16be));
assertThrown!UTFException(readText(utf16le));
assertThrown!UTFException(readText(utf32be));
assertThrown!UTFException(readText(utf32le));
assert(readText(utf7) == (cast(char[])[0x2B, 0x2F, 0x76, 0x38, 0x2D]) ~ "foobar");
assertThrown!UTFException(readText!wstring(none8));
assert(readText!wstring(none16) == "京都市"w);
assertThrown!UTFException(readText!wstring(utf8));
version(BigEndian)
{
assert(readText!wstring(utf16be) == "\uFEFF京都市"w);
assertThrown!UTFException(readText!wstring(utf16le));
}
else
{
assertThrown!UTFException(readText!wstring(utf16be));
assert(readText!wstring(utf16le) == "\uFEFF京都市"w);
}
assertThrown!UTFException(readText!wstring(utf32be));
assertThrown!UTFException(readText!wstring(utf32le));
assertThrown!UTFException(readText!wstring(utf7));
assertThrown!UTFException(readText!dstring(utf8));
assertThrown!UTFException(readText!dstring(utf16be));
assertThrown!UTFException(readText!dstring(utf16le));
version(BigEndian)
{
assert(readText!dstring(utf32be) == "\U0000FEFF京都市"d);
assertThrown!UTFException(readText!dstring(utf32le));
}
else
{
assertThrown!UTFException(readText!dstring(utf32be));
assert(readText!dstring(utf32le) == "\U0000FEFF京都市"d);
}
assertThrown!UTFException(readText!dstring(utf7));
}
/*********************************************
Write `buffer` to file `name`.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be written to file
Throws: $(LREF FileException) on error.
See_also: $(REF toFile, std,stdio)
*/
void write(R)(R name, const void[] buffer)
if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) &&
!isConvertibleToString!R)
{
static if (isNarrowString!R && is(Unqual!(ElementEncodingType!R) == char))
writeImpl(name, name.tempCString!FSChar(), buffer, false);
else
writeImpl(null, name.tempCString!FSChar(), buffer, false);
}
///
@system unittest
{
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
assert(cast(int[]) read(deleteme) == a);
}
/// ditto
void write(R)(auto ref R name, const void[] buffer)
if (isConvertibleToString!R)
{
write!(StringTypeOf!R)(name, buffer);
}
@safe unittest
{
static assert(__traits(compiles, write(TestAliasedString(null), null)));
}
/*********************************************
Appends `buffer` to file `name`.
Creates the file if it does not already exist.
Params:
name = string or range of characters representing the file _name
buffer = data to be appended to file
Throws: $(LREF FileException) on error.
*/
void append(R)(R name, const void[] buffer)
if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) &&
!isConvertibleToString!R)
{
static if (isNarrowString!R && is(Unqual!(ElementEncodingType!R) == char))
writeImpl(name, name.tempCString!FSChar(), buffer, true);
else
writeImpl(null, name.tempCString!FSChar(), buffer, true);
}
///
@system unittest
{
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write(deleteme, a); // deleteme is the name of a temporary file
int[] b = [ 13, 21 ];
append(deleteme, b);
assert(cast(int[]) read(deleteme) == a ~ b);
}
/// ditto
void append(R)(auto ref R name, const void[] buffer)
if (isConvertibleToString!R)
{
append!(StringTypeOf!R)(name, buffer);
}
@safe unittest
{
static assert(__traits(compiles, append(TestAliasedString("foo"), [0, 1, 2, 3])));
}
// Posix implementation helper for write and append
version(Posix) private void writeImpl(scope const(char)[] name, scope const(FSChar)* namez,
scope const(void)[] buffer, bool append) @trusted
{
import std.conv : octal;
// append or write
auto mode = append ? O_CREAT | O_WRONLY | O_APPEND
: O_CREAT | O_WRONLY | O_TRUNC;
immutable fd = core.sys.posix.fcntl.open(namez, mode, octal!666);
cenforce(fd != -1, name, namez);
{
scope(failure) core.sys.posix.unistd.close(fd);
immutable size = buffer.length;
size_t sum, cnt = void;
while (sum != size)
{
cnt = (size - sum < 2^^30) ? (size - sum) : 2^^30;
const numwritten = core.sys.posix.unistd.write(fd, buffer.ptr + sum, cnt);
if (numwritten != cnt)
break;
sum += numwritten;
}
cenforce(sum == size, name, namez);
}
cenforce(core.sys.posix.unistd.close(fd) == 0, name, namez);
}
// Windows implementation helper for write and append
version(Windows) private void writeImpl(scope const(char)[] name, scope const(FSChar)* namez,
scope const(void)[] buffer, bool append) @trusted
{
HANDLE h;
if (append)
{
alias defaults =
AliasSeq!(GENERIC_WRITE, 0, null, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init);
h = CreateFileW(namez, defaults);
cenforce(h != INVALID_HANDLE_VALUE, name, namez);
cenforce(SetFilePointer(h, 0, null, FILE_END) != INVALID_SET_FILE_POINTER,
name, namez);
}
else // write
{
alias defaults =
AliasSeq!(GENERIC_WRITE, 0, null, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init);
h = CreateFileW(namez, defaults);
cenforce(h != INVALID_HANDLE_VALUE, name, namez);
}
immutable size = buffer.length;
size_t sum, cnt = void;
DWORD numwritten = void;
while (sum != size)
{
cnt = (size - sum < 2^^30) ? (size - sum) : 2^^30;
WriteFile(h, buffer.ptr + sum, cast(uint) cnt, &numwritten, null);
if (numwritten != cnt)
break;
sum += numwritten;
}
cenforce(sum == size && CloseHandle(h), name, namez);
}
/***************************************************
* Rename file `from` _to `to`.
* If the target file exists, it is overwritten.
* Params:
* from = string or range of characters representing the existing file name
* to = string or range of characters representing the target file name
* Throws: $(LREF FileException) on error.
*/
void rename(RF, RT)(RF from, RT to)
if ((isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) || isSomeString!RF)
&& !isConvertibleToString!RF &&
(isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) || isSomeString!RT)
&& !isConvertibleToString!RT)
{
// Place outside of @trusted block
auto fromz = from.tempCString!FSChar();
auto toz = to.tempCString!FSChar();
static if (isNarrowString!RF && is(Unqual!(ElementEncodingType!RF) == char))
alias f = from;
else
enum string f = null;
static if (isNarrowString!RT && is(Unqual!(ElementEncodingType!RT) == char))
alias t = to;
else
enum string t = null;
renameImpl(f, t, fromz, toz);
}
/// ditto
void rename(RF, RT)(auto ref RF from, auto ref RT to)
if (isConvertibleToString!RF || isConvertibleToString!RT)
{
import std.meta : staticMap;
alias Types = staticMap!(convertToString, RF, RT);
rename!Types(from, to);
}
@safe unittest
{
static assert(__traits(compiles, rename(TestAliasedString(null), TestAliasedString(null))));
static assert(__traits(compiles, rename("", TestAliasedString(null))));
static assert(__traits(compiles, rename(TestAliasedString(null), "")));
import std.utf : byChar;
static assert(__traits(compiles, rename(TestAliasedString(null), "".byChar)));
}
///
@safe unittest
{
auto t1 = deleteme, t2 = deleteme~"2";
scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();
t1.write("1");
t1.rename(t2);
assert(t2.readText == "1");
t1.write("2");
t1.rename(t2);
assert(t2.readText == "2");
}
private void renameImpl(scope const(char)[] f, scope const(char)[] t,
scope const(FSChar)* fromz, scope const(FSChar)* toz) @trusted
{
version(Windows)
{
import std.exception : enforce;
const result = MoveFileExW(fromz, toz, MOVEFILE_REPLACE_EXISTING);
if (!result)
{
import core.stdc.wchar_ : wcslen;
import std.conv : to, text;
if (!f)
f = to!(typeof(f))(fromz[0 .. wcslen(fromz)]);
if (!t)
t = to!(typeof(t))(toz[0 .. wcslen(toz)]);
enforce(false,
new FileException(
text("Attempting to rename file ", f, " to ", t)));
}
}
else version(Posix)
{
static import core.stdc.stdio;
cenforce(core.stdc.stdio.rename(fromz, toz) == 0, t, toz);
}
}
@safe unittest
{
import std.utf : byWchar;
auto t1 = deleteme, t2 = deleteme~"2";
scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();
write(t1, "1");
rename(t1, t2);
assert(readText(t2) == "1");
write(t1, "2");
rename(t1, t2.byWchar);
assert(readText(t2) == "2");