/
checkedint.d
3298 lines (2965 loc) · 98.5 KB
/
checkedint.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.
/**
$(SCRIPT inhibitQuickIndex = 1;)
This module defines facilities for efficient checking of integral operations
against overflow, casting with loss of precision, unexpected change of sign,
etc. The checking (and possibly correction) can be done at operation level, for
example $(LREF opChecked)$(D !"+"(x, y, overflow)) adds two integrals `x` and
`y` and sets `overflow` to `true` if an overflow occurred. The flag `overflow`
(a `bool` passed by reference) is not touched if the operation succeeded, so the
same flag can be reused for a sequence of operations and tested at the end.
Issuing individual checked operations is flexible and efficient but often
tedious. The $(LREF Checked) facility offers encapsulated integral wrappers that
do all checking internally and have configurable behavior upon erroneous
results. For example, `Checked!int` is a type that behaves like `int` but aborts
execution immediately whenever involved in an operation that produces the
arithmetically wrong result. The accompanying convenience function $(LREF
checked) uses type deduction to convert a value `x` of integral type `T` to
`Checked!T` by means of `checked(x)`. For example:
---
void main()
{
import std.experimental.checkedint, std.stdio;
writeln((checked(5) + 7).get); // 12
writeln((checked(10) * 1000 * 1000 * 1000).get); // Overflow
}
---
Similarly, $(D checked(-1) > uint(0)) aborts execution (even though the built-in
comparison $(D int(-1) > uint(0)) is surprisingly true due to language's
conversion rules modeled after C). Thus, `Checked!int` is a virtually drop-in
replacement for `int` useable in debug builds, to be replaced by `int` in
release mode if efficiency demands it.
`Checked` has customizable behavior with the help of a second type parameter,
`Hook`. Depending on what methods `Hook` defines, core operations on the
underlying integral may be verified for overflow or completely redefined. If
`Hook` defines no method at all and carries no state, there is no change in
behavior, i.e. $(D Checked!(int, void)) is a wrapper around `int` that adds no
customization at all.
This module provides a few predefined hooks (below) that add useful behavior to
`Checked`:
$(BOOKTABLE ,
$(TR $(TD $(LREF Abort)) $(TD
fails every incorrect operation with a message to $(REF
stderr, std, stdio) followed by a call to `assert(0)`. It is the default
second parameter, i.e. `Checked!short` is the same as
$(D Checked!(short, Abort)).
))
$(TR $(TD $(LREF Throw)) $(TD
fails every incorrect operation by throwing an exception.
))
$(TR $(TD $(LREF Warn)) $(TD
prints incorrect operations to $(REF stderr, std, stdio)
but otherwise preserves the built-in behavior.
))
$(TR $(TD $(LREF ProperCompare)) $(TD
fixes the comparison operators `==`, `!=`, `<`, `<=`, `>`, and `>=`
to return correct results in all circumstances,
at a slight cost in efficiency. For example,
$(D Checked!(uint, ProperCompare)(1) > -1) is `true`,
which is not the case for the built-in comparison. Also, comparing
numbers for equality with floating-point numbers only passes if the
integral can be converted to the floating-point number precisely,
so as to preserve transitivity of equality.
))
$(TR $(TD $(LREF WithNaN)) $(TD
reserves a special "Not a Number" (NaN) value akin to the homonym value
reserved for floating-point values. Once a $(D Checked!(X, WithNaN))
gets this special value, it preserves and propagates it until
reassigned. $(LREF isNaN) can be used to query whether the object
is not a number.
))
$(TR $(TD $(LREF Saturate)) $(TD
implements saturating arithmetic, i.e. $(D Checked!(int, Saturate))
"stops" at `int.max` for all operations that would cause an `int` to
overflow toward infinity, and at `int.min` for all operations that would
correspondingly overflow toward negative infinity.
))
)
These policies may be used alone, e.g. $(D Checked!(uint, WithNaN)) defines a
`uint`-like type that reaches a stable NaN state for all erroneous operations.
They may also be "stacked" on top of each other, owing to the property that a
checked integral emulates an actual integral, which means another checked
integral can be built on top of it. Some combinations of interest include:
$(BOOKTABLE ,
$(TR $(TD $(D Checked!(Checked!int, ProperCompare))))
$(TR $(TD
defines an `int` with fixed
comparison operators that will fail with `assert(0)` upon overflow. (Recall that
`Abort` is the default policy.) The order in which policies are combined is
important because the outermost policy (`ProperCompare` in this case) has the
first crack at intercepting an operator. The converse combination $(D
Checked!(Checked!(int, ProperCompare))) is meaningless because `Abort` will
intercept comparison and will fail without giving `ProperCompare` a chance to
intervene.
))
$(TR $(TD))
$(TR $(TDNW $(D Checked!(Checked!(int, ProperCompare), WithNaN))))
$(TR $(TD
defines an `int`-like
type that supports a NaN value. For values that are not NaN, comparison works
properly. Again the composition order is important; $(D Checked!(Checked!(int,
WithNaN), ProperCompare)) does not have good semantics because `ProperCompare`
intercepts comparisons before the numbers involved are tested for NaN.
))
)
The hook's members are looked up statically in a Design by Introspection manner
and are all optional. The table below illustrates the members that a hook type
may define and their influence over the behavior of the `Checked` type using it.
In the table, `hook` is an alias for `Hook` if the type `Hook` does not
introduce any state, or an object of type `Hook` otherwise.
$(TABLE ,
$(TR $(TH `Hook` member) $(TH Semantics in $(D Checked!(T, Hook)))
)
$(TR $(TD `defaultValue`) $(TD If defined, `Hook.defaultValue!T` is used as the
default initializer of the payload.)
)
$(TR $(TD `min`) $(TD If defined, `Hook.min!T` is used as the minimum value of
the payload.)
)
$(TR $(TD `max`) $(TD If defined, `Hook.max!T` is used as the maximum value of
the payload.)
)
$(TR $(TD `hookOpCast`) $(TD If defined, `hook.hookOpCast!U(get)` is forwarded
to unconditionally when the payload is to be cast to type `U`.)
)
$(TR $(TD `onBadCast`) $(TD If defined and `hookOpCast` is $(I not) defined,
`onBadCast!U(get)` is forwarded to when the payload is to be cast to type `U`
and the cast would lose information or force a change of sign.)
)
$(TR $(TD `hookOpEquals`) $(TD If defined, $(D hook.hookOpEquals(get, rhs)) is
forwarded to unconditionally when the payload is compared for equality against
value `rhs` of integral, floating point, or Boolean type.)
)
$(TR $(TD `hookOpCmp`) $(TD If defined, $(D hook.hookOpCmp(get, rhs)) is
forwarded to unconditionally when the payload is compared for ordering against
value `rhs` of integral, floating point, or Boolean type.)
)
$(TR $(TD `hookOpUnary`) $(TD If defined, `hook.hookOpUnary!op(get)` (where `op`
is the operator symbol) is forwarded to for unary operators `-` and `~`. In
addition, for unary operators `++` and `--`, `hook.hookOpUnary!op(payload)` is
called, where `payload` is a reference to the value wrapped by `Checked` so the
hook can change it.)
)
$(TR $(TD `hookOpBinary`) $(TD If defined, $(D hook.hookOpBinary!op(get, rhs))
(where `op` is the operator symbol and `rhs` is the right-hand side operand) is
forwarded to unconditionally for binary operators `+`, `-`, `*`, `/`, `%`,
`^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`.)
)
$(TR $(TD `hookOpBinaryRight`) $(TD If defined, $(D
hook.hookOpBinaryRight!op(lhs, get)) (where `op` is the operator symbol and
`lhs` is the left-hand side operand) is forwarded to unconditionally for binary
operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`.)
)
$(TR $(TD `onOverflow`) $(TD If defined, `hook.onOverflow!op(get)` is forwarded
to for unary operators that overflow but only if `hookOpUnary` is not defined.
Unary `~` does not overflow; unary `-` overflows only when the most negative
value of a signed type is negated, and the result of the hook call is returned.
When the increment or decrement operators overflow, the payload is assigned the
result of `hook.onOverflow!op(get)`. When a binary operator overflows, the
result of $(D hook.onOverflow!op(get, rhs)) is returned, but only if `Hook` does
not define `hookOpBinary`.)
)
$(TR $(TD `hookOpOpAssign`) $(TD If defined, $(D hook.hookOpOpAssign!op(payload,
rhs)) (where `op` is the operator symbol and `rhs` is the right-hand side
operand) is forwarded to unconditionally for binary operators `+=`, `-=`, `*=`, `/=`, `%=`,
`^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=`.)
)
$(TR $(TD `onLowerBound`) $(TD If defined, $(D hook.onLowerBound(value, bound))
(where `value` is the value being assigned) is forwarded to when the result of
binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`,
and `>>>=` is smaller than the smallest value representable by `T`.)
)
$(TR $(TD `onUpperBound`) $(TD If defined, $(D hook.onUpperBound(value, bound))
(where `value` is the value being assigned) is forwarded to when the result of
binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`,
and `>>>=` is larger than the largest value representable by `T`.)
)
$(TR $(TD `hookToHash`) $(TD If defined, $(D hook.hookToHash(payload))
(where `payload` is a reference to the value wrapped by Checked) is forwarded
to when `toHash` is called on a Checked type. Custom hashing can be implemented
in a `Hook`, otherwise the built-in hashing is used.)
)
)
Source: $(PHOBOSSRC std/experimental/checkedint.d)
*/
module std.experimental.checkedint;
import std.traits : isFloatingPoint, isIntegral, isNumeric, isUnsigned, Unqual;
///
@system unittest
{
int[] concatAndAdd(int[] a, int[] b, int offset)
{
// Aborts on overflow on size computation
auto r = new int[(checked(a.length) + b.length).get];
// Aborts on overflow on element computation
foreach (i; 0 .. a.length)
r[i] = (a[i] + checked(offset)).get;
foreach (i; 0 .. b.length)
r[i + a.length] = (b[i] + checked(offset)).get;
return r;
}
assert(concatAndAdd([1, 2, 3], [4, 5], -1) == [0, 1, 2, 3, 4]);
}
/// `Saturate` stops at an overflow
@safe unittest
{
auto x = (cast(byte) 127).checked!Saturate;
assert(x == 127);
x++;
assert(x == 127);
}
/// `WithNaN` has a special "Not a Number" (NaN) value akin to the homonym value reserved for floating-point values
@safe unittest
{
auto x = 100.checked!WithNaN;
assert(x == 100);
x /= 0;
assert(x.isNaN);
}
/// `ProperCompare` fixes the comparison operators ==, !=, <, <=, >, and >= to return correct results
@safe unittest
{
uint x = 1;
auto y = x.checked!ProperCompare;
assert(x < -1); // built-in comparison
assert(y > -1); // ProperCompare
}
/// `Throw` fails every incorrect operation by throwing an exception
@safe unittest
{
import std.exception : assertThrown;
auto x = -1.checked!Throw;
assertThrown(x / 0);
assertThrown(x + int.min);
assertThrown(x == uint.max);
}
/**
Checked integral type wraps an integral `T` and customizes its behavior with the
help of a `Hook` type. The type wrapped must be one of the predefined integrals
(unqualified), or another instance of `Checked`.
*/
struct Checked(T, Hook = Abort)
if (isIntegral!T || is(T == Checked!(U, H), U, H))
{
import std.algorithm.comparison : among;
import std.experimental.allocator.common : stateSize;
import std.traits : hasMember;
/**
The type of the integral subject to checking.
*/
alias Representation = T;
// state {
static if (hasMember!(Hook, "defaultValue"))
private T payload = Hook.defaultValue!T;
else
private T payload;
/**
`hook` is a member variable if it has state, or an alias for `Hook`
otherwise.
*/
static if (stateSize!Hook > 0) Hook hook;
else alias hook = Hook;
// } state
// get
/**
Returns a copy of the underlying value.
*/
auto get() inout { return payload; }
///
@safe unittest
{
auto x = checked(ubyte(42));
static assert(is(typeof(x.get()) == ubyte));
assert(x.get == 42);
const y = checked(ubyte(42));
static assert(is(typeof(y.get()) == const ubyte));
assert(y.get == 42);
}
/**
Defines the minimum and maximum. These values are hookable by defining
`Hook.min` and/or `Hook.max`.
*/
static if (hasMember!(Hook, "min"))
{
enum Checked!(T, Hook) min = Checked!(T, Hook)(Hook.min!T);
///
@system unittest
{
assert(Checked!short.min == -32768);
assert(Checked!(short, WithNaN).min == -32767);
assert(Checked!(uint, WithNaN).max == uint.max - 1);
}
}
else
enum Checked!(T, Hook) min = Checked(T.min);
/// ditto
static if (hasMember!(Hook, "max"))
enum Checked!(T, Hook) max = Checked(Hook.max!T);
else
enum Checked!(T, Hook) max = Checked(T.max);
/**
Constructor taking a value properly convertible to the underlying type. `U`
may be either an integral that can be converted to `T` without a loss, or
another `Checked` instance whose representation may be in turn converted to
`T` without a loss.
*/
this(U)(U rhs)
if (valueConvertible!(U, T) ||
!isIntegral!T && is(typeof(T(rhs))) ||
is(U == Checked!(V, W), V, W) &&
is(typeof(Checked!(T, Hook)(rhs.get))))
{
static if (isIntegral!U)
payload = rhs;
else
payload = rhs.payload;
}
///
@system unittest
{
auto a = checked(42L);
assert(a == 42);
auto b = Checked!long(4242); // convert 4242 to long
assert(b == 4242);
}
/**
Assignment operator. Has the same constraints as the constructor.
*/
void opAssign(U)(U rhs) if (is(typeof(Checked!(T, Hook)(rhs))))
{
static if (isIntegral!U)
payload = rhs;
else
payload = rhs.payload;
}
///
@system unittest
{
Checked!long a;
a = 42L;
assert(a == 42);
a = 4242;
assert(a == 4242);
}
// opCast
/**
Casting operator to integral, `bool`, or floating point type. If `Hook`
defines `hookOpCast`, the call immediately returns
`hook.hookOpCast!U(get)`. Otherwise, casting to `bool` yields $(D
get != 0) and casting to another integral that can represent all
values of `T` returns `get` promoted to `U`.
If a cast to a floating-point type is requested and `Hook` defines
`onBadCast`, the cast is verified by ensuring $(D get == cast(T)
U(get)). If that is not `true`, `hook.onBadCast!U(get)` is returned.
If a cast to an integral type is requested and `Hook` defines `onBadCast`,
the cast is verified by ensuring `get` and $(D cast(U)
get) are the same arithmetic number. (Note that `int(-1)` and
`uint(1)` are different values arithmetically although they have the same
bitwise representation and compare equal by language rules.) If the numbers
are not arithmetically equal, `hook.onBadCast!U(get)` is
returned.
*/
U opCast(U, this _)()
if (isIntegral!U || isFloatingPoint!U || is(U == bool))
{
static if (hasMember!(Hook, "hookOpCast"))
{
return hook.hookOpCast!U(payload);
}
else static if (is(U == bool))
{
return payload != 0;
}
else static if (valueConvertible!(T, U))
{
return payload;
}
// may lose bits or precision
else static if (!hasMember!(Hook, "onBadCast"))
{
return cast(U) payload;
}
else
{
if (isUnsigned!T || !isUnsigned!U ||
T.sizeof > U.sizeof || payload >= 0)
{
auto result = cast(U) payload;
// If signedness is different, we need additional checks
if (result == payload &&
(!isUnsigned!T || isUnsigned!U || result >= 0))
return result;
}
return hook.onBadCast!U(payload);
}
}
///
@system unittest
{
assert(cast(uint) checked(42) == 42);
assert(cast(uint) checked!WithNaN(-42) == uint.max);
}
// opEquals
/**
Compares `this` against `rhs` for equality. If `Hook` defines
`hookOpEquals`, the function forwards to $(D
hook.hookOpEquals(get, rhs)). Otherwise, the result of the
built-in operation $(D get == rhs) is returned.
If `U` is also an instance of `Checked`, both hooks (left- and right-hand
side) are introspected for the method `hookOpEquals`. If both define it,
priority is given to the left-hand side.
*/
bool opEquals(U, this _)(U rhs)
if (isIntegral!U || isFloatingPoint!U || is(U == bool) ||
is(U == Checked!(V, W), V, W) && is(typeof(this == rhs.payload)))
{
static if (is(U == Checked!(V, W), V, W))
{
alias R = typeof(payload + rhs.payload);
static if (is(Hook == W))
{
// Use the lhs hook if there
return this == rhs.payload;
}
else static if (valueConvertible!(T, R) && valueConvertible!(V, R))
{
return payload == rhs.payload;
}
else static if (hasMember!(Hook, "hookOpEquals"))
{
return hook.hookOpEquals(payload, rhs.payload);
}
else static if (hasMember!(W, "hookOpEquals"))
{
return rhs.hook.hookOpEquals(rhs.payload, payload);
}
else
{
return payload == rhs.payload;
}
}
else static if (hasMember!(Hook, "hookOpEquals"))
return hook.hookOpEquals(payload, rhs);
else static if (isIntegral!U || isFloatingPoint!U || is(U == bool))
return payload == rhs;
}
///
static if (is(T == int) && is(Hook == void)) @safe unittest
{
static struct MyHook
{
static bool thereWereErrors;
static bool hookOpEquals(L, R)(L lhs, R rhs)
{
if (lhs != rhs) return false;
static if (isUnsigned!L && !isUnsigned!R)
{
if (lhs > 0 && rhs < 0) thereWereErrors = true;
}
else static if (isUnsigned!R && !isUnsigned!L)
if (lhs < 0 && rhs > 0) thereWereErrors = true;
// Preserve built-in behavior.
return true;
}
}
auto a = checked!MyHook(-42);
assert(a == uint(-42));
assert(MyHook.thereWereErrors);
MyHook.thereWereErrors = false;
assert(checked!MyHook(uint(-42)) == -42);
assert(MyHook.thereWereErrors);
static struct MyHook2
{
static bool hookOpEquals(L, R)(L lhs, R rhs)
{
return lhs == rhs;
}
}
MyHook.thereWereErrors = false;
assert(checked!MyHook2(uint(-42)) == a);
// Hook on left hand side takes precedence, so no errors
assert(!MyHook.thereWereErrors);
}
// toHash
/**
Generates a hash for `this`. If `Hook` defines `hookToHash`, the call
immediately returns `hook.hookToHash(payload)`. If `Hook` does not
implement `hookToHash`, but it has state, a hash will be generated for
the `Hook` using the built-in function and it will be xored with the
hash of the `payload`.
*/
size_t toHash() const nothrow @safe
{
static if (hasMember!(Hook, "hookToHash"))
{
return hook.hookToHash(payload);
}
else static if (stateSize!Hook > 0)
{
static if (hasMember!(typeof(payload), "toHash"))
{
return payload.toHash() ^ hashOf(hook);
}
else
{
return hashOf(payload) ^ hashOf(hook);
}
}
else static if (hasMember!(typeof(payload), "toHash"))
{
return payload.toHash();
}
else
{
return .hashOf(payload);
}
}
// opCmp
/**
Compares `this` against `rhs` for ordering. If `Hook` defines `hookOpCmp`,
the function forwards to $(D hook.hookOpCmp(get, rhs)). Otherwise, the
result of the built-in comparison operation is returned.
If `U` is also an instance of `Checked`, both hooks (left- and right-hand
side) are introspected for the method `hookOpCmp`. If both define it,
priority is given to the left-hand side.
*/
auto opCmp(U, this _)(const U rhs) //const pure @safe nothrow @nogc
if (isIntegral!U || isFloatingPoint!U || is(U == bool))
{
static if (hasMember!(Hook, "hookOpCmp"))
{
return hook.hookOpCmp(payload, rhs);
}
else static if (valueConvertible!(T, U) || valueConvertible!(U, T))
{
return payload < rhs ? -1 : payload > rhs;
}
else static if (isFloatingPoint!U)
{
U lhs = payload;
return lhs < rhs ? U(-1.0)
: lhs > rhs ? U(1.0)
: lhs == rhs ? U(0.0) : U.init;
}
else
{
return payload < rhs ? -1 : payload > rhs;
}
}
/// ditto
auto opCmp(U, Hook1, this _)(Checked!(U, Hook1) rhs)
{
alias R = typeof(payload + rhs.payload);
static if (valueConvertible!(T, R) && valueConvertible!(U, R))
{
return payload < rhs.payload ? -1 : payload > rhs.payload;
}
else static if (is(Hook == Hook1))
{
// Use the lhs hook
return this.opCmp(rhs.payload);
}
else static if (hasMember!(Hook, "hookOpCmp"))
{
return hook.hookOpCmp(get, rhs.get);
}
else static if (hasMember!(Hook1, "hookOpCmp"))
{
return -rhs.hook.hookOpCmp(rhs.payload, get);
}
else
{
return payload < rhs.payload ? -1 : payload > rhs.payload;
}
}
///
static if (is(T == int) && is(Hook == void)) @safe unittest
{
static struct MyHook
{
static bool thereWereErrors;
static int hookOpCmp(L, R)(L lhs, R rhs)
{
static if (isUnsigned!L && !isUnsigned!R)
{
if (rhs < 0 && rhs >= lhs)
thereWereErrors = true;
}
else static if (isUnsigned!R && !isUnsigned!L)
{
if (lhs < 0 && lhs >= rhs)
thereWereErrors = true;
}
// Preserve built-in behavior.
return lhs < rhs ? -1 : lhs > rhs;
}
}
auto a = checked!MyHook(-42);
assert(a > uint(42));
assert(MyHook.thereWereErrors);
static struct MyHook2
{
static int hookOpCmp(L, R)(L lhs, R rhs)
{
// Default behavior
return lhs < rhs ? -1 : lhs > rhs;
}
}
MyHook.thereWereErrors = false;
assert(Checked!(uint, MyHook2)(uint(-42)) <= a);
//assert(Checked!(uint, MyHook2)(uint(-42)) >= a);
// Hook on left hand side takes precedence, so no errors
assert(!MyHook.thereWereErrors);
assert(a <= Checked!(uint, MyHook2)(uint(-42)));
assert(MyHook.thereWereErrors);
}
// For coverage
static if (is(T == int) && is(Hook == void)) @system unittest
{
assert(checked(42) <= checked!void(42));
assert(checked!void(42) <= checked(42u));
assert(checked!void(42) <= checked!(void*)(42u));
}
// opUnary
/**
Defines unary operators `+`, `-`, `~`, `++`, and `--`. Unary `+` is not
overridable and always has built-in behavior (returns `this`). For the
others, if `Hook` defines `hookOpUnary`, `opUnary` forwards to $(D
Checked!(typeof(hook.hookOpUnary!op(get)),
Hook)(hook.hookOpUnary!op(get))).
If `Hook` does not define `hookOpUnary` but defines `onOverflow`, `opUnary`
forwards to `hook.onOverflow!op(get)` in case an overflow occurs.
For `++` and `--`, the payload is assigned from the result of the call to
`onOverflow`.
Note that unary `-` is considered to overflow if `T` is a signed integral of
32 or 64 bits and is equal to the most negative value. This is because that
value has no positive negation.
*/
auto opUnary(string op, this _)()
if (op == "+" || op == "-" || op == "~")
{
static if (op == "+")
return Checked(this); // "+" is not hookable
else static if (hasMember!(Hook, "hookOpUnary"))
{
auto r = hook.hookOpUnary!op(payload);
return Checked!(typeof(r), Hook)(r);
}
else static if (op == "-" && isIntegral!T && T.sizeof >= 4 &&
!isUnsigned!T && hasMember!(Hook, "onOverflow"))
{
static assert(is(typeof(-payload) == typeof(payload)));
bool overflow;
import core.checkedint : negs;
auto r = negs(payload, overflow);
if (overflow) r = hook.onOverflow!op(payload);
return Checked(r);
}
else
return Checked(mixin(op ~ "payload"));
}
/// ditto
ref Checked opUnary(string op)() return
if (op == "++" || op == "--")
{
static if (hasMember!(Hook, "hookOpUnary"))
hook.hookOpUnary!op(payload);
else static if (hasMember!(Hook, "onOverflow"))
{
static if (op == "++")
{
if (payload == max.payload)
payload = hook.onOverflow!"++"(payload);
else
++payload;
}
else
{
if (payload == min.payload)
payload = hook.onOverflow!"--"(payload);
else
--payload;
}
}
else
mixin(op ~ "payload;");
return this;
}
///
static if (is(T == int) && is(Hook == void)) @safe unittest
{
static struct MyHook
{
static bool thereWereErrors;
static L hookOpUnary(string x, L)(L lhs)
{
if (x == "-" && lhs == -lhs) thereWereErrors = true;
return -lhs;
}
}
auto a = checked!MyHook(long.min);
assert(a == -a);
assert(MyHook.thereWereErrors);
auto b = checked!void(42);
assert(++b == 43);
}
// opBinary
/**
Defines binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`,
and `>>>`. If `Hook` defines `hookOpBinary`, `opBinary` forwards to $(D
Checked!(typeof(hook.hookOpBinary!op(get, rhs)),
Hook)(hook.hookOpBinary!op(get, rhs))).
If `Hook` does not define `hookOpBinary` but defines `onOverflow`,
`opBinary` forwards to `hook.onOverflow!op(get, rhs)` in case an
overflow occurs.
If two `Checked` instances are involved in a binary operation and both
define `hookOpBinary`, the left-hand side hook has priority. If both define
`onOverflow`, a compile-time error occurs.
*/
auto opBinary(string op, Rhs)(const Rhs rhs)
if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool))
{
return opBinaryImpl!(op, Rhs, typeof(this))(rhs);
}
/// ditto
auto opBinary(string op, Rhs)(const Rhs rhs) const
if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool))
{
return opBinaryImpl!(op, Rhs, typeof(this))(rhs);
}
private auto opBinaryImpl(string op, Rhs, this _)(const Rhs rhs)
{
alias R = typeof(mixin("payload" ~ op ~ "rhs"));
static assert(is(typeof(mixin("payload" ~ op ~ "rhs")) == R));
static if (isIntegral!R) alias Result = Checked!(R, Hook);
else alias Result = R;
static if (hasMember!(Hook, "hookOpBinary"))
{
auto r = hook.hookOpBinary!op(payload, rhs);
return Checked!(typeof(r), Hook)(r);
}
else static if (is(Rhs == bool))
{
return mixin("this" ~ op ~ "ubyte(rhs)");
}
else static if (isFloatingPoint!Rhs)
{
return mixin("payload" ~ op ~ "rhs");
}
else static if (hasMember!(Hook, "onOverflow"))
{
bool overflow;
auto r = opChecked!op(payload, rhs, overflow);
if (overflow) r = hook.onOverflow!op(payload, rhs);
return Result(r);
}
else
{
// Default is built-in behavior
return Result(mixin("payload" ~ op ~ "rhs"));
}
}
/// ditto
auto opBinary(string op, U, Hook1)(Checked!(U, Hook1) rhs)
{
return opBinaryImpl2!(op, U, Hook1, typeof(this))(rhs);
}
/// ditto
auto opBinary(string op, U, Hook1)(Checked!(U, Hook1) rhs) const
{
return opBinaryImpl2!(op, U, Hook1, typeof(this))(rhs);
}
private
auto opBinaryImpl2(string op, U, Hook1, this _)(Checked!(U, Hook1) rhs)
{
alias R = typeof(get + rhs.payload);
static if (valueConvertible!(T, R) && valueConvertible!(U, R) ||
is(Hook == Hook1))
{
// Delegate to lhs
return mixin("this" ~ op ~ "rhs.payload");
}
else static if (hasMember!(Hook, "hookOpBinary"))
{
return hook.hookOpBinary!op(payload, rhs);
}
else static if (hasMember!(Hook1, "hookOpBinary"))
{
// Delegate to rhs
return mixin("this.payload" ~ op ~ "rhs");
}
else static if (hasMember!(Hook, "onOverflow") &&
!hasMember!(Hook1, "onOverflow"))
{
// Delegate to lhs
return mixin("this" ~ op ~ "rhs.payload");
}
else static if (hasMember!(Hook1, "onOverflow") &&
!hasMember!(Hook, "onOverflow"))
{
// Delegate to rhs
return mixin("this.payload" ~ op ~ "rhs");
}
else
{
static assert(0, "Conflict between lhs and rhs hooks," ~
" use .get on one side to disambiguate.");
}
}
static if (is(T == int) && is(Hook == void)) @system unittest
{
const a = checked(42);
assert(a + 1 == 43);
assert(a + checked(uint(42)) == 84);
assert(checked(42) + checked!void(42u) == 84);
assert(checked!void(42) + checked(42u) == 84);
static struct MyHook
{
static uint tally;
static auto hookOpBinary(string x, L, R)(L lhs, R rhs)
{
++tally;
return mixin("lhs" ~ x ~ "rhs");
}
}
assert(checked!MyHook(42) + checked(42u) == 84);
assert(checked!void(42) + checked!MyHook(42u) == 84);
assert(MyHook.tally == 2);
}
// opBinaryRight
/**
Defines binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, `^`, `<<`,
`>>`, and `>>>` for the case when a built-in numeric or Boolean type is on
the left-hand side, and a `Checked` instance is on the right-hand side.
*/
auto opBinaryRight(string op, Lhs)(const Lhs lhs)
if (isIntegral!Lhs || isFloatingPoint!Lhs || is(Lhs == bool))
{
return opBinaryRightImpl!(op, Lhs, typeof(this))(lhs);
}
/// ditto
auto opBinaryRight(string op, Lhs)(const Lhs lhs) const
if (isIntegral!Lhs || isFloatingPoint!Lhs || is(Lhs == bool))
{
return opBinaryRightImpl!(op, Lhs, typeof(this))(lhs);
}
private auto opBinaryRightImpl(string op, Lhs, this _)(const Lhs lhs)
{
static if (hasMember!(Hook, "hookOpBinaryRight"))
{
auto r = hook.hookOpBinaryRight!op(lhs, payload);
return Checked!(typeof(r), Hook)(r);
}
else static if (hasMember!(Hook, "hookOpBinary"))
{
auto r = hook.hookOpBinary!op(lhs, payload);
return Checked!(typeof(r), Hook)(r);
}
else static if (is(Lhs == bool))
{
return mixin("ubyte(lhs)" ~ op ~ "this");
}
else static if (isFloatingPoint!Lhs)
{
return mixin("lhs" ~ op ~ "payload");
}
else static if (hasMember!(Hook, "onOverflow"))
{
bool overflow;
auto r = opChecked!op(lhs, T(payload), overflow);
if (overflow) r = hook.onOverflow!op(42);
return Checked!(typeof(r), Hook)(r);
}
else
{
// Default is built-in behavior
auto r = mixin("lhs" ~ op ~ "T(payload)");
return Checked!(typeof(r), Hook)(r);
}
}
static if (is(T == int) && is(Hook == void)) @system unittest
{
assert(1 + checked(1) == 2);
static uint tally;
static struct MyHook
{
static auto hookOpBinaryRight(string x, L, R)(L lhs, R rhs)
{
++tally;
return mixin("lhs" ~ x ~ "rhs");
}
}
assert(1 + checked!MyHook(1) == 2);
assert(tally == 1);
immutable x1 = checked(1);
assert(1 + x1 == 2);
immutable x2 = checked!MyHook(1);
assert(1 + x2 == 2);
assert(tally == 2);
}
// opOpAssign
/**
Defines operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`,
`<<=`, `>>=`, and `>>>=`.
If `Hook` defines `hookOpOpAssign`, `opOpAssign` forwards to
`hook.hookOpOpAssign!op(payload, rhs)`, where `payload` is a reference to
the internally held data so the hook can change it.
Otherwise, the operator first evaluates $(D auto result =
opBinary!op(payload, rhs).payload), which is subject to the hooks in
`opBinary`. Then, if `result` is less than $(D Checked!(T, Hook).min) and if
`Hook` defines `onLowerBound`, the payload is assigned from $(D
hook.onLowerBound(result, min)). If `result` is greater than $(D Checked!(T,
Hook).max) and if `Hook` defines `onUpperBound`, the payload is assigned
from $(D hook.onUpperBound(result, min)).
If the right-hand side is also a Checked but with a different hook or
underlying type, the hook and underlying type of this Checked takes
precedence.
In all other cases, the built-in behavior is carried out.
Params:
op = The operator involved (without the `"="`, e.g. `"+"` for `"+="` etc)
rhs = The right-hand side of the operator (left-hand side is `this`)
Returns: A reference to `this`.
*/
ref Checked opOpAssign(string op, Rhs)(const Rhs rhs) return