forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.d
7504 lines (5950 loc) · 216 KB
/
core.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
/++
$(PITFALL
Please note: the api and behavior of this module is not externally stable at this time. See the documentation on specific functions for details.
)
Shared core functionality including exception helpers, library loader, event loop, and possibly more. Maybe command line processor and uda helper and some basic shared annotation types.
I'll probably move the url, websocket, and ssl stuff in here too as they are often shared. Maybe a small internationalization helper type (a hook for external implementation) and COM helpers too. I might move the process helpers out to their own module - even things in here are not considered stable to library users at this time!
If you use this directly outside the arsd library despite its current instability caveats, you might consider using `static import` since names in here are likely to clash with Phobos if you use them together. `static import` will let you easily disambiguate and avoid name conflict errors if I add more here. Some names even clash deliberately to remind me to avoid some antipatterns inside the arsd modules!
## Contributor notes
arsd.core should be focused on things that enable interoperability primarily and secondarily increased code quality between other, otherwise independent arsd modules. As a foundational library, it is not permitted to import anything outside the druntime `core` namespace, except in templates and examples not normally compiled in. This keeps it independent and avoids transitive dependency spillover to end users while also keeping compile speeds fast. To help keep builds snappy, also avoid significant use of ctfe inside this module.
On my linux computer, `dmd -unittest -main core.d` takes about a quarter second to run. We do not want this to grow.
`@safe` compatibility is ok when it isn't too big of a hassle. `@nogc` is a non-goal. I might accept it on some of the trivial functions but if it means changing the logic in any way to support, you will need a compelling argument to justify it. The arsd libs are supposed to be reliable and easy to use. That said, of course, don't be unnecessarily wasteful - if you can easily provide a reliable and easy to use way to let advanced users do their thing without hurting the other cases, let's discuss it.
If functionality is not needed by multiple existing arsd modules, consider adding a new module instead of adding it to the core.
Unittests should generally be hidden behind a special version guard so they don't interfere with end user tests.
History:
Added March 2023 (dub v11.0). Several functions were migrated in here at that time, noted individually. Members without a note were added with the module.
+/
module arsd.core;
// FIXME: add callbacks on file open for tracing dependencies dynamically
// see for useful info: https://devblogs.microsoft.com/dotnet/how-async-await-really-works/
// see: https://wiki.openssl.org/index.php/Simple_TLS_Server
// see: When you only want to track changes on a file or directory, be sure to open it using the O_EVTONLY flag.
///ArsdUseCustomRuntime is used since other derived work from WebAssembly may be used and thus specified in the CLI
version(WebAssembly) version = ArsdUseCustomRuntime;
// note that kqueue might run an i/o loop on mac, ios, etc. but then NSApp.run on the io thread
// but on bsd, you want the kqueue loop in i/o too....
version(iOS)
{
version = EmptyEventLoop;
version = EmptyCoreEvent;
}
version(ArsdUseCustomRuntime)
{
version = EmptyEventLoop;
version = UseStdioWriteln;
}
else
{
version = HasFile;
version = HasSocket;
version = HasThread;
version = HasErrno;
}
version(HasThread)
{
import core.thread;
import core.volatile;
import core.atomic;
import core.time;
}
else
{
// polyfill for missing core.time
struct Duration {
static Duration max() { return Duration(); }
}
}
version(OSX) {
version(ArsdNoCocoa)
enum bool UseCocoa = false;
else
enum bool UseCocoa = true;
}
version(HasErrno)
import core.stdc.errno;
import core.attribute;
static if(!__traits(hasMember, core.attribute, "mustuse"))
enum mustuse;
// FIXME: add an arena allocator? can do task local destruction maybe.
// the three implementations are windows, epoll, and kqueue
version(Windows) {
version=Arsd_core_windows;
// import core.sys.windows.windows;
import core.sys.windows.winbase;
import core.sys.windows.windef;
import core.sys.windows.winnls;
import core.sys.windows.winuser;
import core.sys.windows.winsock2;
pragma(lib, "user32");
pragma(lib, "ws2_32");
} else version(linux) {
version=Arsd_core_epoll;
static if(__VERSION__ >= 2098) {
version=Arsd_core_has_cloexec;
}
} else version(FreeBSD) {
version=Arsd_core_kqueue;
import core.sys.freebsd.sys.event;
} else version(DragonFlyBSD) {
// NOT ACTUALLY TESTED
version=Arsd_core_kqueue;
import core.sys.dragonflybsd.sys.event;
} else version(NetBSD) {
// NOT ACTUALLY TESTED
version=Arsd_core_kqueue;
import core.sys.netbsd.sys.event;
} else version(OpenBSD) {
version=Arsd_core_kqueue;
// THIS FILE DOESN'T ACTUALLY EXIST, WE NEED TO MAKE IT
import core.sys.openbsd.sys.event;
} else version(OSX) {
version=Arsd_core_kqueue;
import core.sys.darwin.sys.event;
version(DigitalMars) {
version=OSXCocoa;
}
}
version(OSXCocoa)
enum CocoaAvailable = true;
else
enum CocoaAvailable = false;
version(Posix) {
import core.sys.posix.signal;
import core.sys.posix.unistd;
import core.sys.posix.sys.un;
import core.sys.posix.sys.socket;
import core.sys.posix.netinet.in_;
}
// FIXME: the exceptions should actually give some explanatory text too (at least sometimes)
/+
=========================
GENERAL UTILITY FUNCTIONS
=========================
+/
// enum stringz : const(char)* { init = null }
/++
A wrapper around a `const(char)*` to indicate that it is a zero-terminated C string.
+/
struct stringz {
private const(char)* raw;
/++
Wraps the given pointer in the struct. Note that it retains a copy of the pointer.
+/
this(const(char)* raw) {
this.raw = raw;
}
/++
Returns the original raw pointer back out.
+/
const(char)* ptr() const {
return raw;
}
/++
Borrows a slice of the pointer up to (but not including) the zero terminator.
+/
const(char)[] borrow() const {
if(raw is null)
return null;
const(char)* p = raw;
int length;
while(*p++) length++;
return raw[0 .. length];
}
}
/++
A limited variant to hold just a few types. It is made for the use of packing a small amount of extra data into error messages.
+/
/+
* if length and ptr are both 0, it is null
* if ptr == 1, length is an integer
* if ptr == 2, length is an unsigned integer (suggest printing in hex)
* if ptr == 3, length is a combination of flags (suggest printing in binary)
* if ptr == 4, length is a unix permission thing (suggest printing in octal)
* if ptr == 5, length is a double float
* if ptr == 15, length must be 0. this holds an empty, non-null, SSO string.
* if ptr >= 16 && < 24, length is reinterpret-casted a small string of length of (ptr & 0x7) + 1
* if length == size_t.max, ptr is interpreted as a stringz
* if ptr >= 1024, it is a non-null D string or byte array. It is a string if the length high bit is clear, a byte array if it is set. the length is what is left after you mask that out.
All other ptr values are reserved for future expansion.
+/
struct LimitedVariant {
/++
+/
enum Contains {
null_,
intDecimal,
intHex,
intBinary,
intOctal,
double_,
emptySso,
stringSso,
stringz,
string,
bytes,
invalid,
}
/++
+/
Contains contains() const {
auto tag = cast(size_t) ptr;
if(ptr is null && length is null)
return Contains.null_;
else switch(tag) {
case 1: return Contains.intDecimal;
case 2: return Contains.intHex;
case 3: return Contains.intBinary;
case 4: return Contains.intOctal;
case 5: return Contains.double_;
case 15: return length is null ? Contains.emptySso : Contains.invalid;
default:
if(tag >= 16 && tag < 24) {
return Contains.stringSso;
} else if(tag >= 1024) {
if(cast(size_t) length == size_t.max)
return Contains.stringz;
else
return isHighBitSet ? Contains.bytes : Contains.string;
} else {
return Contains.invalid;
}
}
}
/// ditto
bool containsInt() const {
with(Contains)
switch(contains) {
case intDecimal, intHex, intBinary, intOctal:
return true;
default:
return false;
}
}
/// ditto
bool containsString() const {
with(Contains)
switch(contains) {
case null_, emptySso, stringSso, string:
// case stringz:
return true;
default:
return false;
}
}
/// ditto
bool containsDouble() const {
with(Contains)
switch(contains) {
case double_:
return true;
default:
return false;
}
}
/// ditto
bool containsBytes() const {
with(Contains)
switch(contains) {
case bytes, null_:
return true;
default:
return false;
}
}
private const(void)* length;
private const(ubyte)* ptr;
private void Throw() const {
throw ArsdException!"LimitedVariant"(cast(size_t) length, cast(size_t) ptr);
}
private bool isHighBitSet() const {
return (cast(size_t) length >> (size_t.sizeof * 8 - 1) & 0x1) != 0;
}
/++
getString gets a reference to the string stored internally, see [toString] to get a string representation or whatever is inside.
+/
const(char)[] getString() const return {
with(Contains)
switch(contains()) {
case null_:
return null;
case emptySso:
return (cast(const(char)*) ptr)[0 .. 0]; // zero length, non-null
case stringSso:
auto len = ((cast(size_t) ptr) & 0x7) + 1;
return (cast(char*) &length)[0 .. len];
case string:
return (cast(const(char)*) ptr)[0 .. cast(size_t) length];
default:
Throw(); assert(0);
}
}
/// ditto
long getInt() const {
if(containsInt)
return cast(long) length;
else
Throw();
assert(0);
}
/// ditto
double getDouble() const {
if(containsDouble)
return *cast(double*) &length;
else
Throw();
assert(0);
}
/// ditto
const(ubyte)[] getBytes() const {
with(Contains)
switch(contains()) {
case null_:
return null;
case bytes:
return ptr[0 .. (cast(size_t) length) & ((1UL << (size_t.sizeof * 8 - 1)) - 1)];
default:
Throw(); assert(0);
}
}
/++
+/
string toString() const {
string intHelper(string prefix, int radix) {
char[128] buffer;
buffer[0 .. prefix.length] = prefix[];
char[] toUse = buffer[prefix.length .. $];
auto got = intToString(getInt(), toUse[], IntToStringArgs().withRadix(radix));
return buffer[0 .. prefix.length + got.length].idup;
}
with(Contains)
final switch(contains()) {
case null_:
return "<null>";
case intDecimal:
return intHelper("", 10);
case intHex:
return intHelper("0x", 16);
case intBinary:
return intHelper("0b", 2);
case intOctal:
return intHelper("0o", 8);
case emptySso, stringSso, string:
return getString().idup;
case bytes:
auto b = getBytes();
return "<bytes>"; // FIXME
case double_:
assert(0); // FIXME
case stringz:
assert(0); // FIXME
case invalid:
return "<invalid>";
}
}
/++
+/
this(string s) {
ptr = cast(const(ubyte)*) s.ptr;
length = cast(void*) s.length;
}
/// ditto
this(const(ubyte)[] b) {
ptr = cast(const(ubyte)*) b.ptr;
length = cast(void*) (b.length | (1UL << (size_t.sizeof * 8 - 1)));
}
/// ditto
this(long l, int base = 10) {
int tag;
switch(base) {
case 10: tag = 1; break;
case 16: tag = 2; break;
case 2: tag = 3; break;
case 8: tag = 4; break;
default: assert(0, "You passed an invalid base to LimitedVariant");
}
ptr = cast(ubyte*) tag;
length = cast(void*) l;
}
/// ditto
version(none)
this(double d) {
// this crashes dmd! omg
assert(0);
// ptr = cast(ubyte*) 15;
// length = cast(void*) *cast(size_t*) &d;
}
}
unittest {
LimitedVariant v = LimitedVariant("foo");
assert(v.containsString());
assert(!v.containsInt());
assert(v.getString() == "foo");
LimitedVariant v2 = LimitedVariant(4);
assert(v2.containsInt());
assert(!v2.containsString());
assert(v2.getInt() == 4);
LimitedVariant v3 = LimitedVariant(cast(ubyte[]) [1, 2, 3]);
assert(v3.containsBytes());
assert(!v3.containsString());
assert(v3.getBytes() == [1, 2, 3]);
}
/++
This is a dummy type to indicate the end of normal arguments and the beginning of the file/line inferred args. It is meant to ensure you don't accidentally send a string that is interpreted as a filename when it was meant to be a normal argument to the function and trigger the wrong overload.
+/
struct ArgSentinel {}
/++
A trivial wrapper around C's malloc that creates a D slice. It multiples n by T.sizeof and returns the slice of the pointer from 0 to n.
Please note that the ptr might be null - it is your responsibility to check that, same as normal malloc. Check `ret is null` specifically, since `ret.length` will always be `n`, even if the `malloc` failed.
Remember to `free` the returned pointer with `core.stdc.stdlib.free(ret.ptr);`
$(TIP
I strongly recommend you simply use the normal garbage collector unless you have a very specific reason not to.
)
See_Also:
[mallocedStringz]
+/
T[] mallocSlice(T)(size_t n) {
import c = core.stdc.stdlib;
return (cast(T*) c.malloc(n * T.sizeof))[0 .. n];
}
/++
Uses C's malloc to allocate a copy of `original` with an attached zero terminator. It may return a slice with a `null` pointer (but non-zero length!) if `malloc` fails and you are responsible for freeing the returned pointer with `core.stdc.stdlib.free(ret.ptr)`.
$(TIP
I strongly recommend you use [CharzBuffer] or Phobos' [std.string.toStringz] instead unless there's a special reason not to.
)
See_Also:
[CharzBuffer] for a generally better alternative. You should only use `mallocedStringz` where `CharzBuffer` cannot be used (e.g. when druntime is not usable or you have no stack space for the temporary buffer).
[mallocSlice] is the function this function calls, so the notes in its documentation applies here too.
+/
char[] mallocedStringz(in char[] original) {
auto slice = mallocSlice!char(original.length + 1);
if(slice is null)
return null;
slice[0 .. original.length] = original[];
slice[original.length] = 0;
return slice;
}
/++
Basically a `scope class` you can return from a function or embed in another aggregate.
+/
struct OwnedClass(Class) {
ubyte[__traits(classInstanceSize, Class)] rawData;
static OwnedClass!Class defaultConstructed() {
OwnedClass!Class i = OwnedClass!Class.init;
i.initializeRawData();
return i;
}
private void initializeRawData() @trusted {
if(!this)
rawData[] = cast(ubyte[]) typeid(Class).initializer[];
}
this(T...)(T t) {
initializeRawData();
rawInstance.__ctor(t);
}
bool opCast(T : bool)() @trusted {
return !(*(cast(void**) rawData.ptr) is null);
}
@disable this();
@disable this(this);
Class rawInstance() return @trusted {
if(!this)
throw new Exception("null");
return cast(Class) rawData.ptr;
}
alias rawInstance this;
~this() @trusted {
if(this)
.destroy(rawInstance());
}
}
// might move RecyclableMemory here
version(Posix)
package(arsd) void makeNonBlocking(int fd) {
import core.sys.posix.fcntl;
auto flags = fcntl(fd, F_GETFL, 0);
if(flags == -1)
throw new ErrnoApiException("fcntl get", errno);
flags |= O_NONBLOCK;
auto s = fcntl(fd, F_SETFL, flags);
if(s == -1)
throw new ErrnoApiException("fcntl set", errno);
}
version(Posix)
package(arsd) void setCloExec(int fd) {
import core.sys.posix.fcntl;
auto flags = fcntl(fd, F_GETFD, 0);
if(flags == -1)
throw new ErrnoApiException("fcntl get", errno);
flags |= FD_CLOEXEC;
auto s = fcntl(fd, F_SETFD, flags);
if(s == -1)
throw new ErrnoApiException("fcntl set", errno);
}
/++
A helper object for temporarily constructing a string appropriate for the Windows API from a D UTF-8 string.
It will use a small internal static buffer is possible, and allocate a new buffer if the string is too big.
History:
Moved from simpledisplay.d to core.d in March 2023 (dub v11.0).
+/
version(Windows)
struct WCharzBuffer {
private wchar[] buffer;
private wchar[128] staticBuffer = void;
/// Length of the string, excluding the zero terminator.
size_t length() {
return buffer.length;
}
// Returns the pointer to the internal buffer. You must assume its lifetime is less than that of the WCharzBuffer. It is zero-terminated.
wchar* ptr() {
return buffer.ptr;
}
/// Returns the slice of the internal buffer, excluding the zero terminator (though there is one present right off the end of the slice). You must assume its lifetime is less than that of the WCharzBuffer.
wchar[] slice() {
return buffer;
}
/// Copies it into a static array of wchars
void copyInto(R)(ref R r) {
static if(is(R == wchar[N], size_t N)) {
r[0 .. this.length] = slice[];
r[this.length] = 0;
} else static assert(0, "can only copy into wchar[n], not " ~ R.stringof);
}
/++
conversionFlags = [WindowsStringConversionFlags]
+/
this(in char[] data, int conversionFlags = 0) {
conversionFlags |= WindowsStringConversionFlags.zeroTerminate; // this ALWAYS zero terminates cuz of its name
auto sz = sizeOfConvertedWstring(data, conversionFlags);
if(sz > staticBuffer.length)
buffer = new wchar[](sz);
else
buffer = staticBuffer[];
buffer = makeWindowsString(data, buffer, conversionFlags);
}
}
/++
Alternative for toStringz
History:
Added March 18, 2023 (dub v11.0)
+/
struct CharzBuffer {
private char[] buffer;
private char[128] staticBuffer = void;
/// Length of the string, excluding the zero terminator.
size_t length() {
assert(buffer.length > 0);
return buffer.length - 1;
}
// Returns the pointer to the internal buffer. You must assume its lifetime is less than that of the CharzBuffer. It is zero-terminated.
char* ptr() {
return buffer.ptr;
}
/// Returns the slice of the internal buffer, excluding the zero terminator (though there is one present right off the end of the slice). You must assume its lifetime is less than that of the CharzBuffer.
char[] slice() {
assert(buffer.length > 0);
return buffer[0 .. $-1];
}
/// Copies it into a static array of chars
void copyInto(R)(ref R r) {
static if(is(R == char[N], size_t N)) {
r[0 .. this.length] = slice[];
r[this.length] = 0;
} else static assert(0, "can only copy into char[n], not " ~ R.stringof);
}
@disable this();
@disable this(this);
/++
Copies `data` into the CharzBuffer, allocating a new one if needed, and zero-terminates it.
+/
this(in char[] data) {
if(data.length + 1 > staticBuffer.length)
buffer = new char[](data.length + 1);
else
buffer = staticBuffer[];
buffer[0 .. data.length] = data[];
buffer[data.length] = 0;
}
}
/++
Given the string `str`, converts it to a string compatible with the Windows API and puts the result in `buffer`, returning the slice of `buffer` actually used. `buffer` must be at least [sizeOfConvertedWstring] elements long.
History:
Moved from simpledisplay.d to core.d in March 2023 (dub v11.0).
+/
version(Windows)
wchar[] makeWindowsString(in char[] str, wchar[] buffer, int conversionFlags = WindowsStringConversionFlags.zeroTerminate) {
if(str.length == 0)
return null;
int pos = 0;
dchar last;
foreach(dchar c; str) {
if(c <= 0xFFFF) {
if((conversionFlags & WindowsStringConversionFlags.convertNewLines) && c == 10 && last != 13)
buffer[pos++] = 13;
buffer[pos++] = cast(wchar) c;
} else if(c <= 0x10FFFF) {
buffer[pos++] = cast(wchar)((((c - 0x10000) >> 10) & 0x3FF) + 0xD800);
buffer[pos++] = cast(wchar)(((c - 0x10000) & 0x3FF) + 0xDC00);
}
last = c;
}
if(conversionFlags & WindowsStringConversionFlags.zeroTerminate) {
buffer[pos] = 0;
}
return buffer[0 .. pos];
}
/++
Converts the Windows API string `str` to a D UTF-8 string, storing it in `buffer`. Returns the slice of `buffer` actually used.
History:
Moved from simpledisplay.d to core.d in March 2023 (dub v11.0).
+/
version(Windows)
char[] makeUtf8StringFromWindowsString(in wchar[] str, char[] buffer) {
if(str.length == 0)
return null;
auto got = WideCharToMultiByte(CP_UTF8, 0, str.ptr, cast(int) str.length, buffer.ptr, cast(int) buffer.length, null, null);
if(got == 0) {
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
throw new object.Exception("not enough buffer");
else
throw new object.Exception("conversion"); // FIXME: GetLastError
}
return buffer[0 .. got];
}
/++
Converts the Windows API string `str` to a newly-allocated D UTF-8 string.
History:
Moved from simpledisplay.d to core.d in March 2023 (dub v11.0).
+/
version(Windows)
string makeUtf8StringFromWindowsString(in wchar[] str) {
char[] buffer;
auto got = WideCharToMultiByte(CP_UTF8, 0, str.ptr, cast(int) str.length, null, 0, null, null);
buffer.length = got;
// it is unique because we just allocated it above!
return cast(string) makeUtf8StringFromWindowsString(str, buffer);
}
/// ditto
version(Windows)
string makeUtf8StringFromWindowsString(wchar* str) {
char[] buffer;
auto got = WideCharToMultiByte(CP_UTF8, 0, str, -1, null, 0, null, null);
buffer.length = got;
got = WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.ptr, cast(int) buffer.length, null, null);
if(got == 0) {
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER)
throw new object.Exception("not enough buffer");
else
throw new object.Exception("conversion"); // FIXME: GetLastError
}
return cast(string) buffer[0 .. got];
}
// only used from minigui rn
package int findIndexOfZero(in wchar[] str) {
foreach(idx, wchar ch; str)
if(ch == 0)
return cast(int) idx;
return cast(int) str.length;
}
package int findIndexOfZero(in char[] str) {
foreach(idx, char ch; str)
if(ch == 0)
return cast(int) idx;
return cast(int) str.length;
}
/++
Returns a minimum buffer length to hold the string `s` with the given conversions. It might be slightly larger than necessary, but is guaranteed to be big enough to hold it.
History:
Moved from simpledisplay.d to core.d in March 2023 (dub v11.0).
+/
version(Windows)
int sizeOfConvertedWstring(in char[] s, int conversionFlags) {
int size = 0;
if(conversionFlags & WindowsStringConversionFlags.convertNewLines) {
// need to convert line endings, which means the length will get bigger.
// BTW I betcha this could be faster with some simd stuff.
char last;
foreach(char ch; s) {
if(ch == 10 && last != 13)
size++; // will add a 13 before it...
size++;
last = ch;
}
} else {
// no conversion necessary, just estimate based on length
/*
I don't think there's any string with a longer length
in code units when encoded in UTF-16 than it has in UTF-8.
This will probably over allocate, but that's OK.
*/
size = cast(int) s.length;
}
if(conversionFlags & WindowsStringConversionFlags.zeroTerminate)
size++;
return size;
}
/++
Used by [makeWindowsString] and [WCharzBuffer]
History:
Moved from simpledisplay.d to core.d in March 2023 (dub v11.0).
+/
version(Windows)
enum WindowsStringConversionFlags : int {
/++
Append a zero terminator to the string.
+/
zeroTerminate = 1,
/++
Converts newlines from \n to \r\n.
+/
convertNewLines = 2,
}
/++
An int printing function that doesn't need to import Phobos. Can do some of the things std.conv.to and std.format.format do.
The buffer must be sized to hold the converted number. 32 chars is enough for most anything.
Returns: the slice of `buffer` containing the converted number.
+/
char[] intToString(long value, char[] buffer, IntToStringArgs args = IntToStringArgs.init) {
const int radix = args.radix ? args.radix : 10;
const int digitsPad = args.padTo;
const int groupSize = args.groupSize;
int pos;
if(value < 0) {
buffer[pos++] = '-';
value = -value;
}
int start = pos;
int digitCount;
do {
auto remainder = value % radix;
value = value / radix;
buffer[pos++] = cast(char) (remainder < 10 ? (remainder + '0') : (remainder - 10 + args.ten));
digitCount++;
} while(value);
if(digitsPad > 0) {
while(digitCount < digitsPad) {
buffer[pos++] = args.padWith;
digitCount++;
}
}
assert(pos >= 1);
assert(pos - start > 0);
auto reverseSlice = buffer[start .. pos];
for(int i = 0; i < reverseSlice.length / 2; i++) {
auto paired = cast(int) reverseSlice.length - i - 1;
char tmp = reverseSlice[i];
reverseSlice[i] = reverseSlice[paired];
reverseSlice[paired] = tmp;
}
return buffer[0 .. pos];
}
/// ditto
struct IntToStringArgs {
private {
ubyte padTo;
char padWith;
ubyte radix;
char ten;
ubyte groupSize;
char separator;
}
IntToStringArgs withPadding(int padTo, char padWith = '0') {
IntToStringArgs args = this;
args.padTo = cast(ubyte) padTo;
args.padWith = padWith;
return args;
}
IntToStringArgs withRadix(int radix, char ten = 'a') {
IntToStringArgs args = this;
args.radix = cast(ubyte) radix;
args.ten = ten;
return args;
}
IntToStringArgs withGroupSeparator(int groupSize, char separator = '_') {
IntToStringArgs args = this;
args.groupSize = cast(ubyte) groupSize;
args.separator = separator;
return args;
}
}
unittest {
char[32] buffer;
assert(intToString(0, buffer[]) == "0");
assert(intToString(-1, buffer[]) == "-1");
assert(intToString(-132, buffer[]) == "-132");
assert(intToString(-1932, buffer[]) == "-1932");
assert(intToString(1, buffer[]) == "1");
assert(intToString(132, buffer[]) == "132");
assert(intToString(1932, buffer[]) == "1932");
assert(intToString(0x1, buffer[], IntToStringArgs().withRadix(16)) == "1");
assert(intToString(0x1b, buffer[], IntToStringArgs().withRadix(16)) == "1b");
assert(intToString(0xef1, buffer[], IntToStringArgs().withRadix(16)) == "ef1");
assert(intToString(0xef1, buffer[], IntToStringArgs().withRadix(16).withPadding(8)) == "00000ef1");
assert(intToString(-0xef1, buffer[], IntToStringArgs().withRadix(16).withPadding(8)) == "-00000ef1");
assert(intToString(-0xef1, buffer[], IntToStringArgs().withRadix(16, 'A').withPadding(8, ' ')) == "- EF1");
}
/++
History:
Moved from color.d to core.d in March 2023 (dub v11.0).
+/
nothrow @safe @nogc pure
inout(char)[] stripInternal(return inout(char)[] s) {
bool isAllWhitespace = true;
foreach(i, char c; s)
if(c != ' ' && c != '\t' && c != '\n' && c != '\r') {
s = s[i .. $];
isAllWhitespace = false;
break;
}
if(isAllWhitespace)
return s[$..$];
for(int a = cast(int)(s.length - 1); a > 0; a--) {
char c = s[a];
if(c != ' ' && c != '\t' && c != '\n' && c != '\r') {
s = s[0 .. a + 1];
break;
}
}
return s;
}
/// ditto
nothrow @safe @nogc pure
inout(char)[] stripRightInternal(return inout(char)[] s) {
bool isAllWhitespace = true;
foreach_reverse(a, c; s) {
if(c != ' ' && c != '\t' && c != '\n' && c != '\r') {
s = s[0 .. a + 1];
isAllWhitespace = false;
break;
}
}
if(isAllWhitespace)
s = s[0..0];
return s;
}
/++
Shortcut for converting some types to string without invoking Phobos (but it will as a last resort).
History:
Moved from color.d to core.d in March 2023 (dub v11.0).