forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.d
8925 lines (7111 loc) · 252 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;
static if(__traits(compiles, () { import core.interpolation; })) {
import core.interpolation;
alias InterpolationHeader = core.interpolation.InterpolationHeader;
alias InterpolationFooter = core.interpolation.InterpolationFooter;
alias InterpolatedLiteral = core.interpolation.InterpolatedLiteral;
alias InterpolatedExpression = core.interpolation.InterpolatedExpression;
} else {
// polyfill for old versions
struct InterpolationHeader {}
struct InterpolationFooter {}
struct InterpolatedLiteral(string literal) {}
struct InterpolatedExpression(string code) {}
}
version(use_arsd_core)
enum use_arsd_core = true;
else
enum use_arsd_core = false;
import core.attribute;
static if(__traits(hasMember, core.attribute, "implicit"))
alias implicit = core.attribute.implicit;
else
enum implicit;
static if(__traits(hasMember, core.attribute, "standalone"))
alias standalone = core.attribute.standalone;
else
enum standalone;
// 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(OSX) version(DigitalMars) {
version=OSXCocoa;
}
version = HasFile;
version = HasSocket;
version = HasThread;
version = HasErrno;
version(Windows)
version = HasTimer;
version(linux)
version = HasTimer;
version(OSXCocoa)
version = HasTimer;
}
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;
// the version in druntime doesn't have the default arg making it a pain to use when the freebsd
// version adds a new field
extern(D) void EV_SET(kevent_t* kevp, typeof(kevent_t.tupleof) args = kevent_t.tupleof.init)
{
*kevp = kevent_t(args);
}
} 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(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
=========================
+/
/++
Casts value `v` to type `T`.
$(TIP
This is a helper function for readability purposes.
The idea is to make type-casting as accessible as `to()` from `std.conv`.
)
---
int i = cast(int)(foo * bar);
int i = castTo!int(foo * bar);
int j = cast(int) round(floatValue);
int j = round(floatValue).castTo!int;
int k = cast(int) floatValue + foobar;
int k = floatValue.castTo!int + foobar;
auto m = Point(
cast(int) calc(a.x, b.x),
cast(int) calc(a.y, b.y),
);
auto m = Point(
calc(a.x, b.x).castTo!int,
calc(a.y, b.y).castTo!int,
);
---
History:
Added on April 24, 2024.
Renamed from `typeCast` to `castTo` on May 24, 2024.
+/
auto ref T castTo(T, S)(auto ref S v) {
return cast(T) v;
}
///
alias typeCast = castTo;
// 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 @system {
if(raw is null)
return null;
const(char)* p = raw;
int length;
while(*p++) length++;
return raw[0 .. length];
}
}
/+
DateTime
year: 16 bits (-32k to +32k)
month: 4 bits
day: 5 bits
hour: 5 bits
minute: 6 bits
second: 6 bits
total: 25 bits + 17 bits = 42 bits
fractional seconds: 10 bits
accuracy flags: date_valid | time_valid = 2 bits
54 bits used, 8 bits remain. reserve 1 for signed.
would need 11 bits for minute-precise dt offset but meh.
+/
/++
A packed date/time/datetime representation added for use with LimitedVariant.
You should probably not use this much directly, it is mostly an internal storage representation.
+/
struct PackedDateTime {
private ulong packedData;
string toString() const {
char[64] buffer;
size_t pos;
if(hasDate) {
pos += intToString(year, buffer[pos .. $], IntToStringArgs().withPadding(4)).length;
buffer[pos++] = '-';
pos += intToString(month, buffer[pos .. $], IntToStringArgs().withPadding(2)).length;
buffer[pos++] = '-';
pos += intToString(day, buffer[pos .. $], IntToStringArgs().withPadding(2)).length;
}
if(hasTime) {
if(pos)
buffer[pos++] = 'T';
pos += intToString(hours, buffer[pos .. $], IntToStringArgs().withPadding(2)).length;
buffer[pos++] = ':';
pos += intToString(minutes, buffer[pos .. $], IntToStringArgs().withPadding(2)).length;
buffer[pos++] = ':';
pos += intToString(seconds, buffer[pos .. $], IntToStringArgs().withPadding(2)).length;
if(fractionalSeconds) {
buffer[pos++] = '.';
pos += intToString(fractionalSeconds, buffer[pos .. $], IntToStringArgs().withPadding(4)).length;
}
}
return buffer[0 .. pos].idup;
}
/++
+/
int fractionalSeconds() const { return getFromMask(00, 10); }
/// ditto
void fractionalSeconds(int a) { setWithMask(a, 00, 10); }
/// ditto
int seconds() const { return getFromMask(10, 6); }
/// ditto
void seconds(int a) { setWithMask(a, 10, 6); }
/// ditto
int minutes() const { return getFromMask(16, 6); }
/// ditto
void minutes(int a) { setWithMask(a, 16, 6); }
/// ditto
int hours() const { return getFromMask(22, 5); }
/// ditto
void hours(int a) { setWithMask(a, 22, 5); }
/// ditto
int day() const { return getFromMask(27, 5); }
/// ditto
void day(int a) { setWithMask(a, 27, 5); }
/// ditto
int month() const { return getFromMask(32, 4); }
/// ditto
void month(int a) { setWithMask(a, 32, 4); }
/// ditto
int year() const { return getFromMask(36, 16); }
/// ditto
void year(int a) { setWithMask(a, 36, 16); }
/// ditto
bool hasTime() const { return cast(bool) getFromMask(52, 1); }
/// ditto
void hasTime(bool a) { setWithMask(a, 52, 1); }
/// ditto
bool hasDate() const { return cast(bool) getFromMask(53, 1); }
/// ditto
void hasDate(bool a) { setWithMask(a, 53, 1); }
private void setWithMask(int a, int bitOffset, int bitCount) {
auto mask = (1UL << bitCount) - 1;
packedData &= ~(mask << bitOffset);
packedData |= (a & mask) << bitOffset;
}
private int getFromMask(int bitOffset, int bitCount) const {
ulong packedData = this.packedData;
packedData >>= bitOffset;
ulong mask = (1UL << bitCount) - 1;
return cast(int) (packedData & mask);
}
}
unittest {
PackedDateTime dt;
dt.hours = 14;
dt.minutes = 30;
dt.seconds = 25;
dt.hasTime = true;
assert(dt.toString() == "14:30:25", dt.toString());
dt.hasTime = false;
dt.year = 2024;
dt.month = 5;
dt.day = 31;
dt.hasDate = true;
assert(dt.toString() == "2024-05-31", dt.toString());
dt.hasTime = true;
assert(dt.toString() == "2024-05-31T14:30:25", dt.toString());
}
/++
Basically a Phobos SysTime but standing alone as a simple 6 4 bit integer (but wrapped) for compatibility with LimitedVariant.
+/
struct SimplifiedUtcTimestamp {
long timestamp;
string toString() const {
import core.stdc.time;
char[128] buffer;
auto ut = toUnixTime();
tm* t = gmtime(&ut);
if(t is null)
return "null time";
return buffer[0 .. strftime(buffer.ptr, buffer.length, "%Y-%m-%dT%H:%M:%SZ", t)].idup;
}
version(Windows)
alias time_t = int;
static SimplifiedUtcTimestamp fromUnixTime(time_t t) {
return SimplifiedUtcTimestamp(621_355_968_000_000_000L + t * 1_000_000_000L / 100);
}
time_t toUnixTime() const {
return cast(time_t) ((timestamp - 621_355_968_000_000_000L) / 1_000_000_0); // hnsec = 7 digits
}
}
unittest {
SimplifiedUtcTimestamp sut = SimplifiedUtcTimestamp.fromUnixTime(86_400);
assert(sut.toString() == "1970-01-02T00:00:00Z");
}
/++
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 and some transit across virtual function boundaries.
+/
/+
ALL OF THESE ARE SUBJECT TO CHANGE
* 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 == 6, length is an Object ref (reinterpret casted to void*)
* if ptr == 7, length is a ticks count (from MonoTime)
* if ptr == 8, length is a utc timestamp (hnsecs)
* if ptr == 9, length is a duration (signed hnsecs)
* if ptr == 10, length is a date or date time (bit packed, see flags in data to determine if it is a Date, Time, or DateTime)
* if ptr == 11, length is a dchar
* if ptr == 12, length is a bool (redundant to int?)
13, 14 reserved. prolly decimals. (4, 8 digits after decimal)
* 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.
It basically can store:
null
type details = must be 0
int (actually long)
type details = formatting hints
float (actually double)
type details = formatting hints
dchar (actually enum - upper half is the type tag, lower half is the member tag)
type details = ???
decimal
type details = precision specifier
object
type details = ???
timestamp
type details: ticks, utc timestamp, relative duration
sso
stringz
or it is bytes or a string; a normal D array (just bytes has a high bit set on length).
But there are subtypes of some of those; ints can just have formatting hints attached.
Could reserve 0-7 as low level type flag (null, int, float, pointer, object)
15-24 still can be the sso thing
We have 10 bits really.
00000 00000
????? OOLLL
The ????? are type details bits.
64 bits decmial to 4 points of precision needs... 14 bits for the small part (so max of 4 digits)? so 50 bits for the big part (max of about 1 quadrillion)
...actually it can just be a dollars * 10000 + cents * 100.
+/
struct LimitedVariant {
/++
+/
enum Contains {
null_,
intDecimal,
intHex,
intBinary,
intOctal,
double_,
object,
monoTime,
utcTimestamp,
duration,
dateTime,
// FIXME boolean? char? decimal?
// could do enums by way of a pointer but kinda iffy
// maybe some kind of prefixed string too for stuff like xml and json or enums etc.
// fyi can also use stringzs or length-prefixed string pointers
emptySso,
stringSso,
stringz,
string,
bytes,
invalid,
}
/++
Each datum stored in the LimitedVariant has a tag associated with it.
Each tag belongs to one or more data families.
+/
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 6: return Contains.object;
case 7: return Contains.monoTime;
case 8: return Contains.utcTimestamp;
case 9: return Contains.duration;
case 10: return Contains.dateTime;
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 containsNull() const {
return contains() == Contains.null_;
}
/// ditto
bool containsInt() const {
with(Contains)
switch(contains) {
case intDecimal, intHex, intBinary, intOctal:
return true;
default:
return false;
}
}
// all specializations of int...
/// ditto
bool containsMonoTime() const {
return contains() == Contains.monoTime;
}
/// ditto
bool containsUtcTimestamp() const {
return contains() == Contains.utcTimestamp;
}
/// ditto
bool containsDuration() const {
return contains() == Contains.duration;
}
/// ditto
bool containsDateTime() const {
return contains() == Contains.dateTime;
}
// done int specializations
/// 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];
case stringz:
return arsd.core.stringz(cast(char*) ptr).borrow;
default:
Throw(); assert(0);
}
}
/// ditto
long getInt() const {
if(containsInt)
return cast(long) length;
else
Throw();
assert(0);
}
/// ditto
double getDouble() const {
if(containsDouble) {
floathack hack;
hack.e = cast(void*) length; // casting away const
return hack.d;
} 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);
}
}
/// ditto
Object getObject() const {
with(Contains)
switch(contains()) {
case null_:
return null;
case object:
return cast(Object) length; // FIXME const correctness sigh
default:
Throw(); assert(0);
}
}
/// ditto
MonoTime getMonoTime() const {
if(containsMonoTime) {
MonoTime time;
__traits(getMember, time, "_ticks") = cast(long) length;
return time;
} else
Throw();
assert(0);
}
/// ditto
SimplifiedUtcTimestamp getUtcTimestamp() const {
if(containsUtcTimestamp)
return SimplifiedUtcTimestamp(cast(long) length);
else
Throw();
assert(0);
}
/// ditto
Duration getDuration() const {
if(containsDuration)
return hnsecs(cast(long) length);
else
Throw();
assert(0);
}
/// ditto
PackedDateTime getDateTime() const {
if(containsDateTime)
return PackedDateTime(cast(long) length);
else
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, stringz:
return getString().idup;
case bytes:
auto b = getBytes();
return "<bytes>"; // FIXME
case object:
auto o = getObject();
return o is null ? "null" : o.toString();
case monoTime:
return getMonoTime.toString();
case utcTimestamp:
return getUtcTimestamp().toString();
case duration:
return getDuration().toString();
case dateTime:
return getDateTime().toString();
case double_:
auto d = getDouble();
import core.stdc.stdio;
char[128] buffer;
auto count = snprintf(buffer.ptr, buffer.length, "%.17lf", d);
return buffer[0 .. count].idup;
case invalid:
return "<invalid>";
}
}
/++
Note for integral types that are not `int` and `long` (for example, `short` or `ubyte`), you might want to explicitly convert them to `int`.
+/
this(string s) {
ptr = cast(const(ubyte)*) s.ptr;
length = cast(void*) s.length;
}
/// ditto
this(const(char)* stringz) {
if(stringz !is null) {
ptr = cast(const(ubyte)*) stringz;
length = cast(void*) size_t.max;
} else {
ptr = null;
length = null;
}
}
/// 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
this(int i, int base = 10) {
this(cast(long) i, base);
}
/// ditto
this(bool i) {
// FIXME?
this(cast(long) i);
}
/// ditto
this(double d) {
// the reinterpret cast hack crashes dmd! omg
ptr = cast(ubyte*) 5;
floathack h;
h.d = d;
this.length = h.e;
}
/// ditto
this(Object o) {
this.ptr = cast(ubyte*) 6;
this.length = cast(void*) o;
}
/// ditto
this(MonoTime a) {
this.ptr = cast(ubyte*) 7;
this.length = cast(void*) a.ticks;
}
/// ditto
this(SimplifiedUtcTimestamp a) {
this.ptr = cast(ubyte*) 8;
this.length = cast(void*) a.timestamp;
}
/// ditto
this(Duration a) {
this.ptr = cast(ubyte*) 9;
this.length = cast(void*) a.total!"hnsecs";
}
/// ditto
this(PackedDateTime a) {
this.ptr = cast(ubyte*) 10;
this.length = cast(void*) a.packedData;
}
}
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]);
}
private union floathack {
// in 32 bit we'll use float instead since it at least fits in the void*
static if(double.sizeof == (void*).sizeof) {
double d;
} else {
float d;
}
void* e;
}
/++
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;