-
Notifications
You must be signed in to change notification settings - Fork 1
/
djinnprint.d
executable file
·1596 lines (1426 loc) · 45.3 KB
/
djinnprint.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
// Authors: tspike (github.com/tspike2k)
// Copyright: Copyright (c) 2020
// License: Boost Software License 1.0 (https://www.boost.org/LICENSE_1_0.txt)
/+
TODO:
- Testing on Windows
- Formatting of classes
- Better documentation (explain the reasononing behind decisions, that ranges serve as an abstract output policy, better usage info, etc)
- Better handling of structs with anonymous union members (see format() in Phobos and search for `#{overlap`)?
- Remove printing to a file? It's a little out of scope, isn't it? And formatting a string directly to a file is very naive. Typically, you want to buffer up output before flushing to a file.
Then again, allowing that does give us the ability to write to stdout/stderr easily, so perhaps we should keep this.
- Format specifier for left-padding with char __c__ for minimum of __n__ chars)?
- Format specifier for converting a string to lowercase/uppercase?
- toPrintIndex should probably be allowed for structs as well as unions. This way we can have a tagged union type
that would store the type outside of the union members.
- It seems that Phobos convention tends to provide toString methods that take OutputRanges and format directly into them.
Perhaps we should look into supporting this somehow? Obviously, the toString method would need to be marked as "nothrow @nogc",
so maybe that's a bit too much to ask for people to do? Then again, if it's there, we could use it. We'll see.
+/
// NOTE: The order of members returned by __traits(allMembers) is not guaranteed to be in the order they appear in the struct definition.
// However, it SEEMS that the .tupleof property is expected (perhaps even required) to be ordered this way. This behavior appears to be expected by
// some code in Phobos, so we'll rely on this behavior. Should this break in the future, we're going to have to make some changes.
//
// See here for some discussions on this topic:
// https://forum.dlang.org/thread/[email protected]%2F
// https://forum.dlang.org/thread/[email protected]
// https://forum.dlang.org/post/[email protected]
public @nogc nothrow:
enum ToPrint; // TODO: Do we still need this? We could force everything with specific requirements to supply a toString method.
private
{
// Library configuration options:
enum outputStructAndUnionNames = false; // Determines if formatting a struct or a union should output the name of the data type in the resulting text.
enum assertOnTruncation = false; // Trigger an assertion when formatting to a buffer results in a string larger than the buffer size
enum use_cstdio = true; // Use the standard C library output functions when printing to the console
static if(use_cstdio)
{
import core.stdc.stdio : FILE, stdout, stderr;
alias FileHandle = FILE*;
alias stdOut = stdout;
alias stdErr = stderr;
}
else
{
version(Posix)
{
alias FileHandle = int;
enum FileHandle stdOut = 1;
enum FileHandle stdErr = 2;
}
else version(Windows)
{
private import core.sys.windows.basetsd : HANDLE;
alias FileHandle = HANDLE;
__gshared FileHandle stdOut;
__gshared FileHandle stdErr;
void init()
{
import core.sys.windows.winbase : GetStdHandle, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE;
stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
assert(stdOut != INVALID_HANDLE_VALUE);
stdErr = GetStdHandle(STD_ERROR_HANDLE);
assert(stdErr != INVALID_HANDLE_VALUE);
}
}
else
{
static assert(0, "Unsupported OS.");
}
}
}
char[] format(Args...)(const(char)[] fmt, char[] buffer, Args args)
{
ArrayRange range;
range.buffer = buffer[];
assert(buffer.length > 0); // TODO: Should we allow this and just return if the buffer is empty?
format(fmt, range, args);
range.buffer[range.bytesWritten] = '\0';
return range.buffer[0..range.bytesWritten];
}
void format(Dest, Args...)(const(char)[] fmt, ref Dest dest, Args args)
if(isOutputRange!(Dest, char) && !isArray!Dest)
{
// TODO: Can this be simplified by using slices instead of fmtCursor/fmtCopyToBufferIndex?
size_t fmtCursor = 0;
size_t fmtCopyToBufferIndex = 0;
enum outputPolicy = `dest.put(fmt[fmtCopyToBufferIndex .. fmtCursor]);`;
while(fmtCursor < fmt.length)
{
if (fmt[fmtCursor] == '{')
{
if (fmtCursor < fmt.length - 1 && fmt[fmtCursor+1] == '{')
{
fmtCursor++;
mixin(outputPolicy);
fmtCursor++;
fmtCopyToBufferIndex = fmtCursor;
}
else
{
mixin(outputPolicy);
fmtCursor++;
size_t commandStart = fmtCursor;
size_t commandEnd = fmtCursor;
while(fmtCursor < fmt.length)
{
if (fmt[fmtCursor] == '}')
{
commandEnd = fmtCursor;
fmtCursor++;
break;
}
fmtCursor++;
}
fmtCopyToBufferIndex = fmtCursor;
auto formatCommand = fmt[commandStart .. commandEnd];
auto argIndex = eatAndReturnArgIndex(formatCommand);
assert(argIndex < args.length, "ERR: Format index exceeds length of provided arguments.");
auto formatSpec = getFormatSpec(formatCommand);
// NOTE: Variadic template argument indexing based on std.format.getNth(...) from Phobos.
outer: switch(argIndex)
{
static foreach(i, _; Args)
{
case i:
{
formatArg(args[i], formatSpec, dest);
} break outer;
}
default:
{
assert(0,"ERR: Unable to access variadic argument.");
} break outer;
}
}
}
else
fmtCursor++;
}
fmtCursor = fmt.length;
mixin(outputPolicy);
}
void formatOut(Args...)(const(char)[] fmt, Args args)
{
auto range = FileRange(stdOut);
format(fmt, range, args);
}
void formatErr(Args...)(const(char)[] fmt, Args args)
{
auto range = FileRange(stdErr);
format(fmt, range, args);
}
void formatFile(Args...)(FileHandle file, const(char)[] fmt, Args args)
{
auto range = FileRange(file);
format(fmt, range, args);
}
void printOut(const(char)[] msg)
{
FileHandle file = stdOut;
printFile(file, msg);
}
void printErr(const(char)[] msg)
{
FileHandle file = stdErr;
printFile(file, msg);
}
void printFile(FileHandle file, const(char)[] msg)
{
static if(use_cstdio)
{
import core.stdc.stdio: fwrite;
assert(file);
fwrite(msg.ptr, msg[0].sizeof, msg.length, file);
}
else
{
version(Posix)
{
import core.sys.posix.unistd : write;
assert(file != -1);
write(file, msg.ptr, msg.length);
}
else version(Windows)
{
import core.sys.windows.winbase : WriteFile, INVALID_HANDLE_VALUE;
assert(file != INVALID_HANDLE_VALUE);
WriteFile(file, msg.ptr, cast(uint)msg.length, null, null);
}
else
{
static assert(0, "Unsupported OS.");
}
}
}
enum FmtFlag : ubyte
{
None = 0,
Hex = 1 << 0,
HexUp = 1 << 1,
Comma = 1 << 2,
ENot = 1 << 3,
ENotUp = 1 << 4,
Sign = 1 << 5,
}
char[] intToString(T)(ref char[30] buffer, T num, FmtFlag flags = FmtFlag.None, ubyte leadingZeroes = 0)
if(isIntegral!T)
{
Unqual!T n = num;
assert(leadingZeroes < buffer.length - 3, "Integer precision must leave enough room in the buffer for at least three characters.");
static if (isSigned!T)
{
// TODO; Does this play well with displaying negative numbers in hex? Is it NORMAL to display negative numbers using hex?
import std.math : abs, sgn;
T sign = cast(T)sgn(n);
n = abs(n); // NOTE: Strip off the sign to prevent the mod operator from giving us a negative array index.
}
ubyte base = (flags & FmtFlag.Hex) || (flags & FmtFlag.HexUp) ? 16 : 10;
auto intToCharTable = (flags & FmtFlag.HexUp) ? intToCharTableUpper[] : intToCharTableLower[];
size_t bufferFill = buffer.length;
size_t place = bufferFill;
size_t loops = 0;
while(true)
{
if(place == 0) break;
place--;
loops++;
auto c = intToCharTable[cast(size_t)(n % base)];
buffer[place] = c;
n /= base;
if ((flags & FmtFlag.Comma) && base == 10 && loops % 3 == 0 && n != 0)
{
buffer[--place] = ',';
}
if(n == 0)
{
{
auto spaceWritten = buffer.length - place;
if(leadingZeroes > spaceWritten)
{
auto zeroesToWrite = leadingZeroes - spaceWritten;
buffer[place - zeroesToWrite .. place] = '0';
place -= zeroesToWrite;
}
}
// TODO: printf doesn't prepend hex values with 0x. Should we actually do this? If the user wants that, they can do it trivially enough.
// Perhaps this should be it's own flag? Or maybe a library customization option?
if(base == 16)
{
buffer[--place] = 'x';
buffer[--place] = '0';
}
static if (isSigned!T)
{
if (sign < 0)
{
buffer[--place] = '-';
}
else if(flags & FmtFlag.Sign)
{
buffer[--place] = '+';
}
}
else
{
if(flags & FmtFlag.Sign)
{
buffer[--place] = '+';
}
}
bufferFill = place;
break;
}
}
return buffer[bufferFill .. $];
}
uint stringToUint(const(char)[] str)
{
uint result = 0;
uint n = 0;
foreach_reverse(ref c; str)
{
result += (c - '0') * (10 ^^ n);
n++;
}
return result;
}
////
//
// Floating point to string conversion code based on stb_sprintf.
// Original author Jeff Roberts. Further developed by Sean Barrett and many others.
// https://github.com/nothings/stb/
// License: Public domain
//
////
char[] doubleToString(return ref char[512] buf, double fv, FmtFlag flags = FmtFlag.None, ubyte precision = 6, ubyte leadingZeroes = 0)
{
//char const *h;
char[512] num = 0;
stbsp__uint32 l, n, cs; // l == length
stbsp__uint64 n64;
stbsp__int32 fw, pr, tz; // pr == precision?
stbsp__uint32 fl;
stbsp__int32 dp; // decimal position
char[8] tail = 0;
char[8] lead = 0;
char* s;
char *sn;
char* bf = buf.ptr;
if(flags & FmtFlag.Comma) fl |= STBSP__TRIPLET_COMMA;
if(flags & FmtFlag.Sign) fl |= STBSP__LEADINGPLUS;
fl |= STBSP__LEADINGZERO;
pr = precision;
fw = leadingZeroes;
void stbsp__cb_buf_clamp(T, U)(ref T cl, ref U v) {
pragma(inline, true);
cl = v;
/*if (callback) { \
int lg = STB_SPRINTF_MIN - (int)(bf - buf); \
if (cl > lg) \
cl = lg; \
}*/
}
void stbsp__chk_cb_buf(size_t bytes){
/*if (callback) { \
stbsp__chk_cb_bufL(bytes); \
} */
}
if((flags & FmtFlag.Hex) || (flags & FmtFlag.HexUp)) // NOTE: Hex float formatting
{
auto h = (flags & FmtFlag.HexUp) ? intToCharTableUpper : intToCharTableLower;
// read the double into a string
if (stbsp__real_to_parts(cast(stbsp__int64*)&n64, &dp, fv))
fl |= STBSP__NEGATIVE;
s = num.ptr + 64;
stbsp__lead_sign(fl, lead.ptr);
if (dp == -1023)
dp = (n64) ? -1022 : 0;
else
n64 |= ((cast(stbsp__uint64)1) << 52);
n64 <<= (64 - 56);
if (pr < 15)
n64 += (((cast(stbsp__uint64)8) << 56) >> (pr * 4));
// add leading chars
lead[1 + lead[0]] = '0';
lead[2 + lead[0]] = 'x';
lead[0] += 2;
*s++ = h[(n64 >> 60) & 15];
n64 <<= 4;
if (pr)
*s++ = stbsp__period;
sn = s;
// print the bits
n = pr;
if (n > 13)
n = 13;
if (pr > cast(stbsp__int32)n)
tz = pr - n;
pr = 0;
while (n--) {
*s++ = h[(n64 >> 60) & 15];
n64 <<= 4;
}
// print the expo
tail[1] = h[17];
if (dp < 0) {
tail[2] = '-';
dp = -dp;
} else
tail[2] = '+';
n = (dp >= 1000) ? 6 : ((dp >= 100) ? 5 : ((dp >= 10) ? 4 : 3));
tail[0] = cast(char)n;
for (;;) {
tail[n] = '0' + dp % 10;
if (n <= 3)
break;
--n;
dp /= 10;
}
dp = cast(int)(s - sn);
l = cast(int)(s - (num.ptr + 64));
s = num.ptr + 64;
cs = 1 + (3 << 24);
goto scopy;
}
else if((flags & FmtFlag.ENot) || (flags & FmtFlag.ENotUp)) // NOTE: Scientific notation
{
auto h = (flags & FmtFlag.ENotUp) ? intToCharTableUpper : intToCharTableLower;
// read the double into a string
if (stbsp__real_to_str(&sn, &l, num.ptr, &dp, fv, pr | 0x80000000))
fl |= STBSP__NEGATIVE;
doexpfromg:
tail[0] = 0;
stbsp__lead_sign(fl, lead.ptr);
if (dp == STBSP__SPECIAL) {
s = cast(char*)sn;
cs = 0;
pr = 0;
goto scopy;
}
s = num.ptr + 64;
// handle leading chars
*s++ = sn[0];
if (pr)
*s++ = stbsp__period;
// handle after decimal
if ((l - 1) > cast(stbsp__uint32)pr)
l = pr + 1;
for (n = 1; n < l; n++)
*s++ = sn[n];
// trailing zeros
tz = pr - (l - 1);
pr = 0;
// dump expo
tail[1] = h[0xe];
dp -= 1;
if (dp < 0) {
tail[2] = '-';
dp = -dp;
} else
tail[2] = '+';
n = (dp >= 100) ? 5 : 4;
tail[0] = cast(char)n;
for (;;) {
tail[n] = '0' + dp % 10;
if (n <= 3)
break;
--n;
dp /= 10;
}
cs = 1 + (3 << 24); // how many tens
goto flt_lead;
}
else // NOTE: Regular float formatting
{
// read the double into a string
if (stbsp__real_to_str(&sn, &l, num.ptr, &dp, fv, pr))
fl |= STBSP__NEGATIVE;
stbsp__lead_sign(fl, lead.ptr);
if (dp == STBSP__SPECIAL) {
s = cast(char *)sn;
cs = 0;
pr = 0;
goto scopy;
}
s = num.ptr + 64;
// handle the three decimal varieties
if (dp <= 0) {
stbsp__int32 i;
// handle 0.000*000xxxx
*s++ = '0';
if (pr)
*s++ = stbsp__period;
n = -dp;
if (cast(stbsp__int32)n > pr)
n = pr;
i = n;
while (i) {
if (((cast(stbsp__uintptr)s) & 3) == 0)
break;
*s++ = '0';
--i;
}
while (i >= 4) {
*(cast(stbsp__uint32 *)s) = 0x30303030;
s += 4;
i -= 4;
}
while (i) {
*s++ = '0';
--i;
}
if (cast(stbsp__int32)(l + n) > pr)
l = pr - n;
i = l;
while (i) {
*s++ = *sn++;
--i;
}
tz = pr - (n + l);
cs = 1 + (3 << 24); // how many tens did we write (for commas below)
} else {
cs = (fl & STBSP__TRIPLET_COMMA) ? ((600 - cast(stbsp__uint32)dp) % 3) : 0;
if (cast(stbsp__uint32)dp >= l) {
// handle xxxx000*000.0
n = 0;
for (;;) {
if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) {
cs = 0;
*s++ = stbsp__comma;
} else {
*s++ = sn[n];
++n;
if (n >= l)
break;
}
}
if (n < cast(stbsp__uint32)dp) {
n = dp - n;
if ((fl & STBSP__TRIPLET_COMMA) == 0) {
while (n) {
if (((cast(stbsp__uintptr)s) & 3) == 0)
break;
*s++ = '0';
--n;
}
while (n >= 4) {
*(cast(stbsp__uint32 *)s) = 0x30303030;
s += 4;
n -= 4;
}
}
while (n) {
if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) {
cs = 0;
*s++ = stbsp__comma;
} else {
*s++ = '0';
--n;
}
}
}
cs = cast(int)(s - (num.ptr + 64)) + (3 << 24); // cs is how many tens
if (pr) {
*s++ = stbsp__period;
tz = pr;
}
} else {
// handle xxxxx.xxxx000*000
n = 0;
for (;;) {
if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) {
cs = 0;
*s++ = stbsp__comma;
} else {
*s++ = sn[n];
++n;
if (n >= cast(stbsp__uint32)dp)
break;
}
}
cs = cast(int)(s - (num.ptr + 64)) + (3 << 24); // cs is how many tens
if (pr)
*s++ = stbsp__period;
if ((l - dp) > cast(stbsp__uint32)pr)
l = pr + dp;
while (n < l) {
*s++ = sn[n];
++n;
}
tz = pr - (l - dp);
}
}
pr = 0;
flt_lead:
// get the length that we copied
l = cast(stbsp__uint32)(s - (num.ptr + 64));
s = num.ptr + 64;
goto scopy;
}
scopy:
// get fw=leading/trailing space, pr=leading zeros
if (pr < cast(stbsp__int32)l)
pr = l;
//n = pr + lead[0] + tail[0] + tz; // Original line
n = pr + tail[0] + tz; // NOTE: For our lib, we want to ignore the leading when calculating the trailing zeroes
if (fw < cast(stbsp__int32)n)
fw = n;
fw -= n;
pr -= l;
// handle right justify and leading zeros
if ((fl & STBSP__LEFTJUST) == 0) {
if (fl & STBSP__LEADINGZERO) // if leading zeros, everything is in pr
{
pr = (fw > pr) ? fw : pr;
fw = 0;
} else {
fl &= ~STBSP__TRIPLET_COMMA; // if no leading zeros, then no commas
}
}
// copy the spaces and/or zeros
if (fw + pr) {
stbsp__int32 i;
stbsp__uint32 c;
// copy leading spaces (or when doing %8.4d stuff)
if ((fl & STBSP__LEFTJUST) == 0)
while (fw > 0) {
stbsp__cb_buf_clamp(i, fw);
fw -= i;
while (i) {
if (((cast(stbsp__uintptr)bf) & 3) == 0)
break;
*bf++ = ' ';
--i;
}
while (i >= 4) {
*(cast(stbsp__uint32 *)bf) = 0x20202020;
bf += 4;
i -= 4;
}
while (i) {
*bf++ = ' ';
--i;
}
stbsp__chk_cb_buf(1);
}
// copy leader
sn = lead.ptr + 1;
while (lead[0]) {
stbsp__cb_buf_clamp(i, lead[0]);
lead[0] -= cast(char)i;
while (i) {
*bf++ = *sn++;
--i;
}
stbsp__chk_cb_buf(1);
}
// copy leading zeros
c = cs >> 24;
cs &= 0xffffff;
cs = (fl & STBSP__TRIPLET_COMMA) ? (cast(stbsp__uint32)(c - ((pr + cs) % (c + 1)))) : 0;
while (pr > 0) {
stbsp__cb_buf_clamp(i, pr);
pr -= i;
if ((fl & STBSP__TRIPLET_COMMA) == 0) {
while (i) {
if (((cast(stbsp__uintptr)bf) & 3) == 0)
break;
*bf++ = '0';
--i;
}
while (i >= 4) {
*(cast(stbsp__uint32 *)bf) = 0x30303030;
bf += 4;
i -= 4;
}
}
while (i) {
if ((fl & STBSP__TRIPLET_COMMA) && (cs++ == c)) {
cs = 0;
*bf++ = stbsp__comma;
} else
*bf++ = '0';
--i;
}
stbsp__chk_cb_buf(1);
}
}
// copy leader if there is still one
sn = lead.ptr + 1;
while (lead[0]) {
stbsp__int32 i;
stbsp__cb_buf_clamp(i, lead[0]);
lead[0] -= cast(char)i;
while (i) {
*bf++ = *sn++;
--i;
}
stbsp__chk_cb_buf(1);
}
// copy the string
n = l;
while (n) {
stbsp__int32 i;
stbsp__cb_buf_clamp(i, n);
n -= i;
/+
STBSP__UNALIGNED(while (i >= 4) {
*(stbsp__uint32 volatile *)bf = *(stbsp__uint32 volatile *)s;
bf += 4;
s += 4;
i -= 4;
})
+/
while (i) {
*bf++ = *s++;
--i;
}
stbsp__chk_cb_buf(1);
}
// copy trailing zeros
while (tz) {
stbsp__int32 i;
stbsp__cb_buf_clamp(i, tz);
tz -= i;
while (i) {
if (((cast(stbsp__uintptr)bf) & 3) == 0)
break;
*bf++ = '0';
--i;
}
while (i >= 4) {
*(cast(stbsp__uint32 *)bf) = 0x30303030;
bf += 4;
i -= 4;
}
while (i) {
*bf++ = '0';
--i;
}
stbsp__chk_cb_buf(1);
}
// copy tail if there is one
sn = tail.ptr + 1;
while (tail[0]) {
stbsp__int32 i;
stbsp__cb_buf_clamp(i, tail[0]);
tail[0] -= cast(char)i;
while (i) {
*bf++ = *sn++;
--i;
}
stbsp__chk_cb_buf(1);
}
// handle the left justify
if (fl & STBSP__LEFTJUST)
if (fw > 0) {
while (fw) {
stbsp__int32 i;
stbsp__cb_buf_clamp(i, fw);
fw -= i;
while (i) {
if (((cast(stbsp__uintptr)bf) & 3) == 0)
break;
*bf++ = ' ';
--i;
}
while (i >= 4) {
*(cast(stbsp__uint32 *)bf) = 0x20202020;
bf += 4;
i -= 4;
}
while (i--)
*bf++ = ' ';
stbsp__chk_cb_buf(1);
}
}
return buf[0 .. bf - buf.ptr];
}
private:
import std.traits;
import std.range : isInputRange, isOutputRange, isInfinite;
import core.stdc.string : memcpy;
alias ArrayTarget(T : U[], U) = U;
enum bool isCString(T) = is(T == char*) || is(T == const(char)*) || is(T == immutable(char)*);
enum bool isCharArray(T) = isArray!T && (is(ArrayTarget!(T) == char) || is(ArrayTarget!(T) == immutable char) || is(ArrayTarget!(T) == const char));
template useQuotes(T)
{
enum useQuotes = isCharArray!T || isCString!T;
}
struct ArrayRange
{
nothrow @nogc:
char[] buffer;
uint bytesWritten;
void put(const(char)[] source)
{
auto dest = buffer[bytesWritten .. $-1]; // NOTE: Leave at least one char at the end to place the null terminator.
static if (assertOnTruncation) assert(source.length <= dest.length, "Buffer truncation during text formatting.");
size_t bytesToCopy = source.length;
if(dest.length < bytesToCopy)
bytesToCopy = dest.length;
// Issue #1: Using memcpy rather than the built-in slice copy operator for compatability with LDC when using the -betterC switch.
// https://github.com/tspike2k/djinnprint/issues/1
memcpy(dest.ptr, source.ptr, bytesToCopy);
bytesWritten += bytesToCopy;
}
}
struct FileRange
{
nothrow @nogc:
FileHandle handle;
void put(const(char)[] source)
{
printFile(handle, source);
}
}
immutable char[] intToCharTableLower = "0123456789abcdefxp";
immutable char[] intToCharTableUpper = "0123456789ABCDEFXP";
size_t length(const(char*) s)
{
size_t result = 0;
while(s[result] != '\0')
{
result++;
}
return result;
}
void formatArg(Type, Dest)(ref Type t, in FormatSpec spec, ref Dest dest)
if(isOutputRange!(Dest, char) && !isArray!Dest)
{
alias T = Unqual!Type;
// NOTE: Used to detect anonymous unions
size_t getHighestOffsetUntil(T)(size_t memberCutoffIndex)
if(is(T == struct) || is(T == union))
{
size_t result = 0;
static foreach(i; 0 .. t.tupleof.length)
{
if(i < memberCutoffIndex)
{
result = result < t.tupleof[i].offsetof ? t.tupleof[i].offsetof : result;
}
}
return result;
}
static if (is(T == enum))
{
outer: final switch(t)
{
static foreach (i, member; EnumMembers!T)
{
case EnumMembers!T[i]:
{
dest.put(__traits(identifier, EnumMembers!T[i]));
} break outer;
}
}
}
else static if(is(T == bool))
{
if(t)
{
dest.put("true");
}
else
{
dest.put("false");
}
}
else static if (isIntegral!T)
{
char[30] intBuffer;
auto result = intToString(intBuffer, t, spec.flags, spec.leadingZeroes);
dest.put(result);
}
else static if (is(T == char))
{
char[1] temp = t;
dest.put(temp);
}
else static if (is(T == float) || is(T == double))
{
char[512] buffer;
auto result = doubleToString(buffer, t, spec.flags, spec.precision == 0 ? 6 : spec.precision, spec.leadingZeroes);
dest.put(result);
}
else static if(isCString!T)
{
size_t srcLength = 0;
while(t[srcLength] != '\0') srcLength++;
dest.put(t[0 .. srcLength]);
}
else static if(isCharArray!T)
{
size_t endIndex = t.length;
foreach(i; 0 .. t.length)
{
if(t[i] == '\0')
{
endIndex = i;
break;
}
}
dest.put(t[0 .. endIndex]);
}
else static if(isInputRange!T)
{
static assert(!isInfinite!T);
dest.put("[");
size_t i = 0;
foreach(ref v; t)
{
if(i > 0) dest.put(", ");
formatArg(v, spec, dest);
i++;
}
dest.put("]");
}
else static if(is(T == struct))
{
static if(outputStructAndUnionNames) dest.put(T.stringof);
dest.put("(");
foreach(i, member; t.tupleof)
{
static if(i == 0 || t.tupleof[i].offsetof > getHighestOffsetUntil!T(i))
{
static if(i > 0) dest.put(", ");
enum surroundWithQuotes = useQuotes!(typeof(member));
static if(surroundWithQuotes) dest.put("\"");
formatArg(member, spec, dest);
static if(surroundWithQuotes) dest.put("\"");
}