-
-
Notifications
You must be signed in to change notification settings - Fork 700
/
bitmanip.d
4630 lines (3938 loc) · 119 KB
/
bitmanip.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.
/**
Bit-level manipulation facilities.
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Bit constructs) $(TD
$(LREF BitArray)
$(LREF bitfields)
$(LREF bitsSet)
))
$(TR $(TD Endianness conversion) $(TD
$(LREF bigEndianToNative)
$(LREF littleEndianToNative)
$(LREF nativeToBigEndian)
$(LREF nativeToLittleEndian)
$(LREF swapEndian)
))
$(TR $(TD Integral ranges) $(TD
$(LREF append)
$(LREF peek)
$(LREF read)
$(LREF write)
))
$(TR $(TD Floating-Point manipulation) $(TD
$(LREF DoubleRep)
$(LREF FloatRep)
))
$(TR $(TD Tagging) $(TD
$(LREF taggedClassRef)
$(LREF taggedPointer)
))
))
Copyright: Copyright The D Language Foundation 2007 - 2011.
License: $(HTTP www.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),
Alex Rønne Petersen,
Damian Ziemba,
Amaury SECHET
Source: $(PHOBOSSRC std/bitmanip.d)
*/
/*
Copyright The D Language Foundation 2007 - 2012.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.bitmanip;
import std.range.primitives;
public import std.system : Endian;
import std.traits;
private string myToString(ulong n) pure @safe
{
import core.internal.string : UnsignedStringBuf, unsignedToTempString;
UnsignedStringBuf buf;
auto s = unsignedToTempString(n, buf);
// pure allows implicit cast to string
return s ~ (n > uint.max ? "UL" : "U");
}
@safe pure unittest
{
assert(myToString(5) == "5U");
assert(myToString(uint.max) == "4294967295U");
assert(myToString(uint.max + 1UL) == "4294967296UL");
}
private template createAccessors(
string store, T, string name, size_t len, size_t offset)
{
static if (!name.length)
{
// No need to create any accessor
enum result = "";
}
else static if (len == 0)
{
// Fields of length 0 are always zero
enum result = "enum "~T.stringof~" "~name~" = 0;\n";
}
else
{
enum ulong
maskAllElse = ((~0uL) >> (64 - len)) << offset,
signBitCheck = 1uL << (len - 1);
static if (T.min < 0)
{
enum long minVal = -(1uL << (len - 1));
enum ulong maxVal = (1uL << (len - 1)) - 1;
alias UT = Unsigned!(T);
enum UT extendSign = cast(UT)~((~0uL) >> (64 - len));
}
else
{
enum ulong minVal = 0;
enum ulong maxVal = (~0uL) >> (64 - len);
enum extendSign = 0;
}
static if (is(T == bool))
{
static assert(len == 1, "`" ~ name ~
"` definition problem: type `bool` is only allowed for single-bit fields");
enum result =
// getter
"@property bool " ~ name ~ "() @safe pure nothrow @nogc const { return "
~"("~store~" & "~myToString(maskAllElse)~") != 0;}\n"
// setter
~"@property void " ~ name ~ "(bool v) @safe pure nothrow @nogc { "
~"if (v) "~store~" |= "~myToString(maskAllElse)~";"
~"else "~store~" &= cast(typeof("~store~"))(-1-cast(typeof("~store~"))"~myToString(maskAllElse)~");}\n";
}
else
{
// getter
enum result = "@property "~T.stringof~" "~name~"() @safe pure nothrow @nogc const { auto result = "
~"("~store~" & "
~ myToString(maskAllElse) ~ ") >>"
~ myToString(offset) ~ ";"
~ (T.min < 0
? "if (result >= " ~ myToString(signBitCheck)
~ ") result |= " ~ myToString(extendSign) ~ ";"
: "")
~ " return cast("~T.stringof~") result;}\n"
// setter
~"@property void "~name~"("~T.stringof~" v) @safe pure nothrow @nogc { "
~"assert(v >= "~name~`_min, "Value is smaller than the minimum value of bitfield '`~name~`'"); `
~"assert(v <= "~name~`_max, "Value is greater than the maximum value of bitfield '`~name~`'"); `
~store~" = cast(typeof("~store~"))"
~" (("~store~" & (-1-cast(typeof("~store~"))"~myToString(maskAllElse)~"))"
~" | ((cast(typeof("~store~")) v << "~myToString(offset)~")"
~" & "~myToString(maskAllElse)~"));}\n"
// constants
~"enum "~T.stringof~" "~name~"_min = cast("~T.stringof~")"
~myToString(minVal)~"; "
~" enum "~T.stringof~" "~name~"_max = cast("~T.stringof~")"
~myToString(maxVal)~"; ";
}
}
}
private template createStoreName(Ts...)
{
static if (Ts.length < 2)
enum createStoreName = "";
else
enum createStoreName = "_" ~ Ts[1] ~ createStoreName!(Ts[3 .. $]);
}
private template createStorageAndFields(Ts...)
{
enum Name = createStoreName!Ts;
enum Size = sizeOfBitField!Ts;
static if (Size == ubyte.sizeof * 8)
alias StoreType = ubyte;
else static if (Size == ushort.sizeof * 8)
alias StoreType = ushort;
else static if (Size == uint.sizeof * 8)
alias StoreType = uint;
else static if (Size == ulong.sizeof * 8)
alias StoreType = ulong;
else
{
static assert(false, "Field widths must sum to 8, 16, 32, or 64");
alias StoreType = ulong; // just to avoid another error msg
}
enum result
= "private " ~ StoreType.stringof ~ " " ~ Name ~ ";"
~ createFields!(Name, 0, Ts).result;
}
private template createFields(string store, size_t offset, Ts...)
{
static if (Ts.length > 0)
enum result
= createAccessors!(store, Ts[0], Ts[1], Ts[2], offset).result
~ createFields!(store, offset + Ts[2], Ts[3 .. $]).result;
else
enum result = "";
}
private ulong getBitsForAlign(ulong a)
{
ulong bits = 0;
while ((a & 0x01) == 0)
{
bits++;
a >>= 1;
}
assert(a == 1, "alignment is not a power of 2");
return bits;
}
private template createReferenceAccessor(string store, T, ulong bits, string name)
{
enum storage = "private void* " ~ store ~ "_ptr;\n";
enum storage_accessor = "@property ref size_t " ~ store ~ "() return @trusted pure nothrow @nogc const { "
~ "return *cast(size_t*) &" ~ store ~ "_ptr;}\n"
~ "@property void " ~ store ~ "(size_t v) @trusted pure nothrow @nogc { "
~ "" ~ store ~ "_ptr = cast(void*) v;}\n";
enum mask = (1UL << bits) - 1;
// getter
enum ref_accessor = "@property "~T.stringof~" "~name~"() @trusted pure nothrow @nogc const { auto result = "
~ "("~store~" & "~myToString(~mask)~"); "
~ "return cast("~T.stringof~") cast(void*) result;}\n"
// setter
~"@property void "~name~"("~T.stringof~" v) @trusted pure nothrow @nogc { "
~"assert(((cast(typeof("~store~")) cast(void*) v) & "~myToString(mask)
~`) == 0, "Value not properly aligned for '`~name~`'"); `
~store~" = cast(typeof("~store~"))"
~" (("~store~" & (cast(typeof("~store~")) "~myToString(mask)~"))"
~" | ((cast(typeof("~store~")) cast(void*) v) & (cast(typeof("~store~")) "~myToString(~mask)~")));}\n";
enum result = storage ~ storage_accessor ~ ref_accessor;
}
private template sizeOfBitField(T...)
{
static if (T.length < 2)
enum sizeOfBitField = 0;
else
enum sizeOfBitField = T[2] + sizeOfBitField!(T[3 .. $]);
}
private template createTaggedReference(T, ulong a, string name, Ts...)
{
static assert(
sizeOfBitField!Ts <= getBitsForAlign(a),
"Fields must fit in the bits know to be zero because of alignment."
);
enum StoreName = createStoreName!(T, name, 0, Ts);
enum result
= createReferenceAccessor!(StoreName, T, sizeOfBitField!Ts, name).result
~ createFields!(StoreName, 0, Ts, size_t, "", T.sizeof * 8 - sizeOfBitField!Ts).result;
}
/**
Allows creating bit fields inside $(D_PARAM struct)s and $(D_PARAM
class)es.
The type of a bit field can be any integral type or enumerated
type. The most efficient type to store in bitfields is $(D_PARAM
bool), followed by unsigned types, followed by signed types.
See_Also: $(REF BitFlags, std,typecons)
*/
template bitfields(T...)
{
enum { bitfields = createStorageAndFields!T.result }
}
/**
Create a bitfield pack of eight bits, which fit in
one $(D_PARAM ubyte). The bitfields are allocated starting from the
least significant bit, i.e. x occupies the two least significant bits
of the bitfields storage.
*/
@safe unittest
{
struct A
{
int a;
mixin(bitfields!(
uint, "x", 2,
int, "y", 3,
uint, "z", 2,
bool, "flag", 1));
}
A obj;
obj.x = 2;
obj.z = obj.x;
assert(obj.x == 2);
assert(obj.y == 0);
assert(obj.z == 2);
assert(obj.flag == false);
}
/**
The sum of all bit lengths in one $(D_PARAM bitfield) instantiation
must be exactly 8, 16, 32, or 64. If padding is needed, just allocate
one bitfield with an empty name.
*/
@safe unittest
{
struct A
{
mixin(bitfields!(
bool, "flag1", 1,
bool, "flag2", 1,
uint, "", 6));
}
A a;
assert(a.flag1 == 0);
a.flag1 = 1;
assert(a.flag1 == 1);
a.flag1 = 0;
assert(a.flag1 == 0);
}
/// enums can be used too
@safe unittest
{
enum ABC { A, B, C }
struct EnumTest
{
mixin(bitfields!(
ABC, "x", 2,
bool, "y", 1,
ubyte, "z", 5));
}
}
/**
This string mixin generator allows one to create tagged pointers inside $(D_PARAM struct)s and $(D_PARAM class)es.
A tagged pointer uses the bits known to be zero in a normal pointer or class reference to store extra information.
For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero.
One can store a 2-bit integer there.
The example above creates a tagged pointer in the struct A. The pointer is of type
`uint*` as specified by the first argument, and is named x, as specified by the second
argument.
Following arguments works the same way as `bitfield`'s. The bitfield must fit into the
bits known to be zero because of the pointer alignment.
*/
template taggedPointer(T : T*, string name, Ts...) {
enum taggedPointer = createTaggedReference!(T*, T.alignof, name, Ts).result;
}
///
@safe unittest
{
struct A
{
int a;
mixin(taggedPointer!(
uint*, "x",
bool, "b1", 1,
bool, "b2", 1));
}
A obj;
obj.x = new uint;
obj.b1 = true;
obj.b2 = false;
}
/**
This string mixin generator allows one to create tagged class reference inside $(D_PARAM struct)s and $(D_PARAM class)es.
A tagged class reference uses the bits known to be zero in a normal class reference to store extra information.
For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero.
One can store a 2-bit integer there.
The example above creates a tagged reference to an Object in the struct A. This expects the same parameters
as `taggedPointer`, except the first argument which must be a class type instead of a pointer type.
*/
template taggedClassRef(T, string name, Ts...)
if (is(T == class))
{
enum taggedClassRef = createTaggedReference!(T, 8, name, Ts).result;
}
///
@safe unittest
{
struct A
{
int a;
mixin(taggedClassRef!(
Object, "o",
uint, "i", 2));
}
A obj;
obj.o = new Object();
obj.i = 3;
}
@safe pure nothrow @nogc
unittest
{
// Degenerate bitfields tests mixed with range tests
// https://issues.dlang.org/show_bug.cgi?id=8474
// https://issues.dlang.org/show_bug.cgi?id=11160
struct Test1
{
mixin(bitfields!(uint, "a", 32,
uint, "b", 4,
uint, "c", 4,
uint, "d", 8,
uint, "e", 16,));
static assert(Test1.b_min == 0);
static assert(Test1.b_max == 15);
}
struct Test2
{
mixin(bitfields!(bool, "a", 0,
ulong, "b", 64));
static assert(Test2.b_min == ulong.min);
static assert(Test2.b_max == ulong.max);
}
struct Test1b
{
mixin(bitfields!(bool, "a", 0,
int, "b", 8));
}
struct Test2b
{
mixin(bitfields!(int, "a", 32,
int, "b", 4,
int, "c", 4,
int, "d", 8,
int, "e", 16,));
static assert(Test2b.b_min == -8);
static assert(Test2b.b_max == 7);
}
struct Test3b
{
mixin(bitfields!(bool, "a", 0,
long, "b", 64));
static assert(Test3b.b_min == long.min);
static assert(Test3b.b_max == long.max);
}
struct Test4b
{
mixin(bitfields!(long, "a", 32,
int, "b", 32));
}
// Sign extension tests
Test2b t2b;
Test4b t4b;
t2b.b = -5; assert(t2b.b == -5);
t2b.d = -5; assert(t2b.d == -5);
t2b.e = -5; assert(t2b.e == -5);
t4b.a = -5; assert(t4b.a == -5L);
}
@system unittest
{
struct Test5
{
mixin(taggedPointer!(
int*, "a",
uint, "b", 2));
}
Test5 t5;
t5.a = null;
t5.b = 3;
assert(t5.a is null);
assert(t5.b == 3);
int myint = 42;
t5.a = &myint;
assert(t5.a is &myint);
assert(t5.b == 3);
struct Test6
{
mixin(taggedClassRef!(
Object, "o",
bool, "b", 1));
}
Test6 t6;
t6.o = null;
t6.b = false;
assert(t6.o is null);
assert(t6.b == false);
auto o = new Object();
t6.o = o;
t6.b = true;
assert(t6.o is o);
assert(t6.b == true);
}
@safe unittest
{
static assert(!__traits(compiles,
taggedPointer!(
int*, "a",
uint, "b", 3)));
static assert(!__traits(compiles,
taggedClassRef!(
Object, "a",
uint, "b", 4)));
struct S {
mixin(taggedClassRef!(
Object, "a",
bool, "b", 1));
}
const S s;
void bar(S s) {}
static assert(!__traits(compiles, bar(s)));
}
// https://issues.dlang.org/show_bug.cgi?id=6686
@safe unittest
{
union S {
ulong bits = ulong.max;
mixin (bitfields!(
ulong, "back", 31,
ulong, "front", 33)
);
}
S num;
num.bits = ulong.max;
num.back = 1;
assert(num.bits == 0xFFFF_FFFF_8000_0001uL);
}
// https://issues.dlang.org/show_bug.cgi?id=5942
@safe unittest
{
struct S
{
mixin(bitfields!(
int, "a" , 32,
int, "b" , 32
));
}
S data;
data.b = 42;
data.a = 1;
assert(data.b == 42);
}
@safe unittest
{
struct Test
{
mixin(bitfields!(bool, "a", 1,
uint, "b", 3,
short, "c", 4));
}
@safe void test() pure nothrow
{
Test t;
t.a = true;
t.b = 5;
t.c = 2;
assert(t.a);
assert(t.b == 5);
assert(t.c == 2);
}
test();
}
@safe unittest
{
{
static struct Integrals {
bool checkExpectations(bool eb, int ei, short es) { return b == eb && i == ei && s == es; }
mixin(bitfields!(
bool, "b", 1,
uint, "i", 3,
short, "s", 4));
}
Integrals i;
assert(i.checkExpectations(false, 0, 0));
i.b = true;
assert(i.checkExpectations(true, 0, 0));
i.i = 7;
assert(i.checkExpectations(true, 7, 0));
i.s = -8;
assert(i.checkExpectations(true, 7, -8));
i.s = 7;
assert(i.checkExpectations(true, 7, 7));
}
//https://issues.dlang.org/show_bug.cgi?id=8876
{
struct MoreIntegrals {
bool checkExpectations(uint eu, ushort es, uint ei) { return u == eu && s == es && i == ei; }
mixin(bitfields!(
uint, "u", 24,
short, "s", 16,
int, "i", 24));
}
MoreIntegrals i;
assert(i.checkExpectations(0, 0, 0));
i.s = 20;
assert(i.checkExpectations(0, 20, 0));
i.i = 72;
assert(i.checkExpectations(0, 20, 72));
i.u = 8;
assert(i.checkExpectations(8, 20, 72));
i.s = 7;
assert(i.checkExpectations(8, 7, 72));
}
enum A { True, False }
enum B { One, Two, Three, Four }
static struct Enums {
bool checkExpectations(A ea, B eb) { return a == ea && b == eb; }
mixin(bitfields!(
A, "a", 1,
B, "b", 2,
uint, "", 5));
}
Enums e;
assert(e.checkExpectations(A.True, B.One));
e.a = A.False;
assert(e.checkExpectations(A.False, B.One));
e.b = B.Three;
assert(e.checkExpectations(A.False, B.Three));
static struct SingleMember {
bool checkExpectations(bool eb) { return b == eb; }
mixin(bitfields!(
bool, "b", 1,
uint, "", 7));
}
SingleMember f;
assert(f.checkExpectations(false));
f.b = true;
assert(f.checkExpectations(true));
}
// https://issues.dlang.org/show_bug.cgi?id=12477
@system unittest
{
import core.exception : AssertError;
import std.algorithm.searching : canFind;
import std.bitmanip : bitfields;
static struct S
{
mixin(bitfields!(
uint, "a", 6,
int, "b", 2));
}
S s;
try { s.a = uint.max; assert(0); }
catch (AssertError ae)
{ assert(ae.msg.canFind("Value is greater than the maximum value of bitfield 'a'"), ae.msg); }
try { s.b = int.min; assert(0); }
catch (AssertError ae)
{ assert(ae.msg.canFind("Value is smaller than the minimum value of bitfield 'b'"), ae.msg); }
}
/**
Allows manipulating the fraction, exponent, and sign parts of a
$(D_PARAM float) separately. The definition is:
----
struct FloatRep
{
union
{
float value;
mixin(bitfields!(
uint, "fraction", 23,
ubyte, "exponent", 8,
bool, "sign", 1));
}
enum uint bias = 127, fractionBits = 23, exponentBits = 8, signBits = 1;
}
----
*/
struct FloatRep
{
union
{
float value;
mixin(bitfields!(
uint, "fraction", 23,
ubyte, "exponent", 8,
bool, "sign", 1));
}
enum uint bias = 127, fractionBits = 23, exponentBits = 8, signBits = 1;
}
///
@safe unittest
{
FloatRep rep = {value: 0};
assert(rep.fraction == 0);
assert(rep.exponent == 0);
assert(!rep.sign);
rep.value = 42;
assert(rep.fraction == 2621440);
assert(rep.exponent == 132);
assert(!rep.sign);
rep.value = 10;
assert(rep.fraction == 2097152);
assert(rep.exponent == 130);
}
///
@safe unittest
{
FloatRep rep = {value: 1};
assert(rep.fraction == 0);
assert(rep.exponent == 127);
assert(!rep.sign);
rep.exponent = 126;
assert(rep.value == 0.5);
rep.exponent = 130;
assert(rep.value == 8);
}
///
@safe unittest
{
FloatRep rep = {value: 1};
rep.value = -0.5;
assert(rep.fraction == 0);
assert(rep.exponent == 126);
assert(rep.sign);
rep.value = -1. / 3;
assert(rep.fraction == 2796203);
assert(rep.exponent == 125);
assert(rep.sign);
}
/**
Allows manipulating the fraction, exponent, and sign parts of a
$(D_PARAM double) separately. The definition is:
----
struct DoubleRep
{
union
{
double value;
mixin(bitfields!(
ulong, "fraction", 52,
ushort, "exponent", 11,
bool, "sign", 1));
}
enum uint bias = 1023, signBits = 1, fractionBits = 52, exponentBits = 11;
}
----
*/
struct DoubleRep
{
union
{
double value;
mixin(bitfields!(
ulong, "fraction", 52,
ushort, "exponent", 11,
bool, "sign", 1));
}
enum uint bias = 1023, signBits = 1, fractionBits = 52, exponentBits = 11;
}
///
@safe unittest
{
DoubleRep rep = {value: 0};
assert(rep.fraction == 0);
assert(rep.exponent == 0);
assert(!rep.sign);
rep.value = 42;
assert(rep.fraction == 1407374883553280);
assert(rep.exponent == 1028);
assert(!rep.sign);
rep.value = 10;
assert(rep.fraction == 1125899906842624);
assert(rep.exponent == 1026);
}
///
@safe unittest
{
DoubleRep rep = {value: 1};
assert(rep.fraction == 0);
assert(rep.exponent == 1023);
assert(!rep.sign);
rep.exponent = 1022;
assert(rep.value == 0.5);
rep.exponent = 1026;
assert(rep.value == 8);
}
///
@safe unittest
{
DoubleRep rep = {value: 1};
rep.value = -0.5;
assert(rep.fraction == 0);
assert(rep.exponent == 1022);
assert(rep.sign);
rep.value = -1. / 3;
assert(rep.fraction == 1501199875790165);
assert(rep.exponent == 1021);
assert(rep.sign);
}
/// Reading
@safe unittest
{
DoubleRep x;
x.value = 1.0;
assert(x.fraction == 0 && x.exponent == 1023 && !x.sign);
x.value = -0.5;
assert(x.fraction == 0 && x.exponent == 1022 && x.sign);
x.value = 0.5;
assert(x.fraction == 0 && x.exponent == 1022 && !x.sign);
}
/// Writing
@safe unittest
{
DoubleRep x;
x.fraction = 1125899906842624;
x.exponent = 1025;
x.sign = true;
assert(x.value == -5.0);
}
// https://issues.dlang.org/show_bug.cgi?id=15305
@safe unittest
{
struct S {
mixin(bitfields!(
bool, "alice", 1,
ulong, "bob", 63,
));
}
S s;
s.bob = long.max - 1;
s.alice = false;
assert(s.bob == long.max - 1);
}
/**
A dynamic array of bits. Each bit in a `BitArray` can be manipulated individually
or by the standard bitwise operators `&`, `|`, `^`, `~`, `>>`, `<<` and also by
other effective member functions; most of them work relative to the `BitArray`'s
dimension (see $(LREF dim)), instead of its $(LREF length).
*/
struct BitArray
{
private:
import core.bitop : btc, bts, btr, bsf, bt;
import std.format : FormatSpec;
size_t _len;
size_t* _ptr;
enum bitsPerSizeT = size_t.sizeof * 8;
@property size_t fullWords() const @nogc pure nothrow
{
return _len / bitsPerSizeT;
}
// Number of bits after the last full word
@property size_t endBits() const @nogc pure nothrow
{
return _len % bitsPerSizeT;
}
// Bit mask to extract the bits after the last full word
@property size_t endMask() const @nogc pure nothrow
{
return (size_t(1) << endBits) - 1;
}
static size_t lenToDim(size_t len) @nogc pure nothrow @safe
{
return (len + (bitsPerSizeT-1)) / bitsPerSizeT;
}
public:
/**
Creates a `BitArray` from a `bool` array, such that `bool` values read
from left to right correspond to subsequent bits in the `BitArray`.
Params: ba = Source array of `bool` values.
*/
this(in bool[] ba) nothrow pure
{
length = ba.length;
foreach (i, b; ba)
{
this[i] = b;
}
}
///
@system unittest
{
import std.algorithm.comparison : equal;
bool[] input = [true, false, false, true, true];
auto a = BitArray(input);
assert(a.length == 5);
assert(a.bitsSet.equal([0, 3, 4]));
// This also works because an implicit cast to bool[] occurs for this array.
auto b = BitArray([0, 0, 1]);
assert(b.length == 3);
assert(b.bitsSet.equal([2]));
}
///
@system unittest
{
import std.algorithm.comparison : equal;
import std.array : array;
import std.range : iota, repeat;
BitArray a = true.repeat(70).array;
assert(a.length == 70);
assert(a.bitsSet.equal(iota(0, 70)));
}
/**
Creates a `BitArray` from the raw contents of the source array. The
source array is not copied but simply acts as the underlying array
of bits, which stores data as `size_t` units.
That means a particular care should be taken when passing an array
of a type different than `size_t`, firstly because its length should
be a multiple of `size_t.sizeof`, and secondly because how the bits
are mapped:
---
size_t[] source = [1, 2, 3, 3424234, 724398, 230947, 389492];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
assert(ba[n] == nth_bit);
}
---
The least significant bit in any `size_t` unit is the starting bit of this
unit, and the most significant bit is the last bit of this unit. Therefore,
passing e.g. an array of `int`s may result in a different `BitArray`
depending on the processor's endianness.
This constructor is the inverse of $(LREF opCast).
Params:
v = Source array. `v.length` must be a multple of `size_t.sizeof`.
numbits = Number of bits to be mapped from the source array, i.e.
length of the created `BitArray`.
*/
this(void[] v, size_t numbits) @nogc nothrow pure