diff options
author | Iain Buclaw <ibuclaw@gdcproject.org> | 2022-02-13 20:17:53 +0100 |
---|---|---|
committer | Iain Buclaw <ibuclaw@gdcproject.org> | 2022-02-16 11:15:02 +0100 |
commit | d75691877c4a7521a995d2601021fcaf30f65d94 (patch) | |
tree | 36509d835d63b98ad1130ac9d4695b5033c10428 /libphobos/src | |
parent | 023327643969d5469902a9ecfa6738a315f9e362 (diff) |
d: Merge upstream dmd 52844d4b1, druntime dbd0c874, phobos 896b1d0e1.
D front-end changes:
- Parsing and compiling C code is now possible using `import'.
- `throw' statements can now be used as an expression.
- Improvements to the D template emission strategy when compiling
with `-funittest'.
D Runtime changes:
- New core.int128 module for implementing intrinsics to support
128-bit integer types.
- C bindings for the kernel and C runtime have been better separated
to allow compiling for hybrid targets, such as kFreeBSD.
Phobos changes:
- The std.experimental.checkedint module has been renamed to
std.checkedint.
gcc/d/ChangeLog:
* d-builtins.cc (d_build_builtins_module): Set purity of DECL_PURE_P
functions to PURE::const_.
* d-gimplify.cc (bit_field_ref): New function.
(d_gimplify_modify_expr): Handle implicit casting for assignments to
bit-fields.
(d_gimplify_unary_expr): New function.
(d_gimplify_binary_expr): New function.
(d_gimplify_expr): Handle UNARY_CLASS_P and BINARY_CLASS_P.
* d-target.cc (Target::_init): Initialize bitFieldStyle.
(TargetCPP::parameterType): Update signature.
(Target::supportsLinkerDirective): New function.
* dmd/MERGE: Merge upstream dmd 52844d4b1.
* expr.cc (ExprVisitor::visit (ThrowExp *)): New function.
* types.cc (d_build_bitfield_integer_type): New function.
(insert_aggregate_bitfield): New function.
(layout_aggregate_members): Handle inserting bit-fields into an
aggregate type.
libphobos/ChangeLog:
* Makefile.in: Regenerate.
* libdruntime/MERGE: Merge upstream druntime dbd0c874.
* libdruntime/Makefile.am (DRUNTIME_CSOURCES): Add core/int128.d.
(DRUNTIME_DISOURCES): Add __builtins.di.
* libdruntime/Makefile.in: Regenerate.
* src/MERGE: Merge upstream phobos 896b1d0e1.
* src/Makefile.am (PHOBOS_DSOURCES): Add std/checkedint.d.
* src/Makefile.in: Regenerate.
* testsuite/testsuite_flags.in: Add -fall-instantiations to
--gdcflags.
Diffstat (limited to 'libphobos/src')
26 files changed, 4340 insertions, 3741 deletions
diff --git a/libphobos/src/MERGE b/libphobos/src/MERGE index b60fa170c4c..2babfbe6347 100644 --- a/libphobos/src/MERGE +++ b/libphobos/src/MERGE @@ -1,4 +1,4 @@ -4687883231eba3bda7691321f2af107fdb3d0a44 +896b1d0e1e8b69bccac0e180ecd1b42a70f95d5b The first line of this file holds the git revision number of the last merge done from the dlang/phobos repository. diff --git a/libphobos/src/Makefile.am b/libphobos/src/Makefile.am index 94c6f4d4638..75f83974e99 100644 --- a/libphobos/src/Makefile.am +++ b/libphobos/src/Makefile.am @@ -89,11 +89,12 @@ PHOBOS_DSOURCES = etc/c/curl.d etc/c/zlib.d std/algorithm/comparison.d \ std/algorithm/mutation.d std/algorithm/package.d \ std/algorithm/searching.d std/algorithm/setops.d \ std/algorithm/sorting.d std/array.d std/ascii.d std/base64.d \ - std/bigint.d std/bitmanip.d std/compiler.d std/complex.d \ - std/concurrency.d std/container/array.d std/container/binaryheap.d \ - std/container/dlist.d std/container/package.d std/container/rbtree.d \ - std/container/slist.d std/container/util.d std/conv.d std/csv.d \ - std/datetime/date.d std/datetime/interval.d std/datetime/package.d \ + std/bigint.d std/bitmanip.d std/checkedint.d std/compiler.d \ + std/complex.d std/concurrency.d std/container/array.d \ + std/container/binaryheap.d std/container/dlist.d \ + std/container/package.d std/container/rbtree.d std/container/slist.d \ + std/container/util.d std/conv.d std/csv.d std/datetime/date.d \ + std/datetime/interval.d std/datetime/package.d \ std/datetime/stopwatch.d std/datetime/systime.d \ std/datetime/timezone.d std/demangle.d std/digest/crc.d \ std/digest/digest.d std/digest/hmac.d std/digest/md.d \ diff --git a/libphobos/src/Makefile.in b/libphobos/src/Makefile.in index a4101ebf028..f2395e2caf7 100644 --- a/libphobos/src/Makefile.in +++ b/libphobos/src/Makefile.in @@ -159,8 +159,9 @@ am__dirstamp = $(am__leading_dot)dirstamp @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/algorithm/sorting.lo \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/array.lo std/ascii.lo \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/base64.lo std/bigint.lo \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/bitmanip.lo std/compiler.lo \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/complex.lo \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/bitmanip.lo \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/checkedint.lo \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/compiler.lo std/complex.lo \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/concurrency.lo \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/array.lo \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/binaryheap.lo \ @@ -549,11 +550,12 @@ libgphobos_la_LINK = $(LIBTOOL) --tag=D $(libgphobos_la_LIBTOOLFLAGS) \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/algorithm/mutation.d std/algorithm/package.d \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/algorithm/searching.d std/algorithm/setops.d \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/algorithm/sorting.d std/array.d std/ascii.d std/base64.d \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/bigint.d std/bitmanip.d std/compiler.d std/complex.d \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/concurrency.d std/container/array.d std/container/binaryheap.d \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/dlist.d std/container/package.d std/container/rbtree.d \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/slist.d std/container/util.d std/conv.d std/csv.d \ -@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/datetime/date.d std/datetime/interval.d std/datetime/package.d \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/bigint.d std/bitmanip.d std/checkedint.d std/compiler.d \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/complex.d std/concurrency.d std/container/array.d \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/binaryheap.d std/container/dlist.d \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/package.d std/container/rbtree.d std/container/slist.d \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/container/util.d std/conv.d std/csv.d std/datetime/date.d \ +@ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/datetime/interval.d std/datetime/package.d \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/datetime/stopwatch.d std/datetime/systime.d \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/datetime/timezone.d std/demangle.d std/digest/crc.d \ @ENABLE_LIBDRUNTIME_ONLY_FALSE@ std/digest/digest.d std/digest/hmac.d std/digest/md.d \ @@ -717,6 +719,7 @@ std/ascii.lo: std/$(am__dirstamp) std/base64.lo: std/$(am__dirstamp) std/bigint.lo: std/$(am__dirstamp) std/bitmanip.lo: std/$(am__dirstamp) +std/checkedint.lo: std/$(am__dirstamp) std/compiler.lo: std/$(am__dirstamp) std/complex.lo: std/$(am__dirstamp) std/concurrency.lo: std/$(am__dirstamp) diff --git a/libphobos/src/index.dd b/libphobos/src/index.dd index 8613a3c2b66..cbc173d891d 100644 --- a/libphobos/src/index.dd +++ b/libphobos/src/index.dd @@ -84,7 +84,7 @@ $(BOOKTABLE , ) $(LEADINGROW Data integrity) $(TR - $(TDNW $(MREF std,experimental,checkedint)) + $(TDNW $(MREF std,checkedint)) $(TD Checked integral types.) ) $(TR diff --git a/libphobos/src/std/array.d b/libphobos/src/std/array.d index ffdda8e1d4c..b86e0f99225 100644 --- a/libphobos/src/std/array.d +++ b/libphobos/src/std/array.d @@ -117,7 +117,7 @@ if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range) alias E = ForeachType!Range; static if (hasLength!Range) { - auto length = r.length; + const length = r.length; if (length == 0) return null; @@ -126,12 +126,35 @@ if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range) auto result = (() @trusted => uninitializedArray!(Unqual!E[])(length))(); // Every element of the uninitialized array must be initialized - size_t i; - foreach (e; r) + size_t cnt; //Number of elements that have been initialized + try { - emplaceRef!E(result[i], e); - ++i; + foreach (e; r) + { + emplaceRef!E(result[cnt], e); + ++cnt; + } + } catch (Exception e) + { + //https://issues.dlang.org/show_bug.cgi?id=22185 + //Make any uninitialized elements safely destructible. + foreach (ref elem; result[cnt..$]) + { + import core.internal.lifetime : emplaceInitializer; + emplaceInitializer(elem); + } + throw e; } + /* + https://issues.dlang.org/show_bug.cgi?id=22673 + + We preallocated an array, we should ensure that enough range elements + were gathered such that every slot in the array is filled. If not, the GC + will collect the allocated array, leading to the `length - cnt` left over elements + being collected too - despite their contents having no guarantee of destructibility. + */ + assert(length == cnt, + "Range .length property was not equal to the length yielded by the range before becoming empty"); return (() @trusted => cast(E[]) result)(); } else @@ -439,6 +462,91 @@ if (isAutodecodableString!String) assert(equal(r, [S(1), S(1)])); }); } +//https://issues.dlang.org/show_bug.cgi?id=22673 +@system unittest +{ + struct LyingRange + { + enum size_t length = 100; + enum theRealLength = 50; + size_t idx = 0; + bool empty() + { + return idx <= theRealLength; + } + void popFront() + { + ++idx; + } + size_t front() + { + return idx; + } + } + static assert(hasLength!LyingRange); + LyingRange rng; + import std.exception : assertThrown; + assertThrown!Error(array(rng)); +} +//https://issues.dlang.org/show_bug.cgi?id=22185 +@system unittest +{ + import std.stdio; + static struct ThrowingCopy + { + int x = 420; + this(ref return scope ThrowingCopy rhs) + { + rhs.x = 420; + // + throw new Exception("This throws"); + } + ~this() + { + /* + Any time this destructor runs, it should be running on "valid" + data. This is is mimicked by having a .init other than 0 (the value the memory + practically will be from the GC). + */ + if (x != 420) + { + //This will only trigger during GC finalization so avoid writefln for now. + printf("Destructor failure in ThrowingCopy(%d) @ %p", x, &this); + assert(x == 420, "unittest destructor failed"); + } + } + } + static struct LyingThrowingRange + { + enum size_t length = 100; + enum size_t evilRealLength = 50; + size_t idx; + ThrowingCopy front() + { + return ThrowingCopy(12); + } + bool empty() + { + return idx == evilRealLength; + } + void popFront() + { + ++idx; + } + } + static assert(hasLength!LyingThrowingRange); + import std.exception : assertThrown; + { + assertThrown(array(LyingThrowingRange())); + } + import core.memory : GC; + /* + Force a collection early. Doesn't always actually finalize the bad objects + but trying to collect soon after the allocation is thrown away means any potential failures + will happen earlier. + */ + GC.collect(); +} /** Returns a newly allocated associative array from a range of key/value tuples @@ -939,6 +1047,11 @@ if (isDynamicArray!T && allSatisfy!(isIntegral, I)) // from rt/lifetime.d private extern(C) void[] _d_newarrayU(const TypeInfo ti, size_t length) pure nothrow; +// from rt/tracegc.d +version (D_ProfileGC) +private extern (C) void[] _d_newarrayUTrace(string file, size_t line, + string funcname, const scope TypeInfo ti, size_t length) pure nothrow; + private auto arrayAllocImpl(bool minimallyInitialized, T, I...)(I sizes) nothrow { static assert(I.length <= nDimensions!T, @@ -992,7 +1105,15 @@ private auto arrayAllocImpl(bool minimallyInitialized, T, I...)(I sizes) nothrow _d_newarrayU returns a void[], but with the length set according to E.sizeof. +/ - *(cast(void[]*)&ret) = _d_newarrayU(typeid(E[]), size); + version (D_ProfileGC) + { + // FIXME: file, line, function should be propagated from the + // caller, not here. + *(cast(void[]*)&ret) = _d_newarrayUTrace(__FILE__, __LINE__, + __FUNCTION__, typeid(E[]), size); + } + else + *(cast(void[]*)&ret) = _d_newarrayU(typeid(E[]), size); static if (minimallyInitialized && hasIndirections!E) // _d_newarrayU would have asserted if the multiplication below // had overflowed, so we don't have to check it again. diff --git a/libphobos/src/std/checkedint.d b/libphobos/src/std/checkedint.d new file mode 100644 index 00000000000..635c4207fcd --- /dev/null +++ b/libphobos/src/std/checkedint.d @@ -0,0 +1,3591 @@ +// 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.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/checkedint.d) +*/ +module std.checkedint; +import std.traits : isFloatingPoint, isIntegral, isNumeric, isUnsigned, Unqual; + +/// +@safe 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`. + +Params: + T = type that is wrapped in the `Checked` type + Hook = hook type that customizes the behavior of the `Checked` type +*/ +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.format.spec : FormatSpec; + import std.range.primitives : isInputRange, ElementType; + import std.traits : hasMember, isSomeChar; + + /** + 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); + /// + @safe unittest + { + assert(Checked!short.min == -32768); + assert(Checked!(short, WithNaN).min == -32767); + assert(Checked!(uint, WithNaN).max == uint.max - 1); + } + } + else + { + /// ditto + enum Checked!(T, Hook) min = Checked(T.min); + } + static if (hasMember!(Hook, "max")) + { + /// ditto + enum Checked!(T, Hook) max = Checked(Hook.max!T); + } + else + { + /// ditto + 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; + } + /// + @safe 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. + + Params: + rhs = The value to assign + + Returns: + A reference to `this` + */ + ref Checked opAssign(U)(U rhs) return + if (is(typeof(Checked!(T, Hook)(rhs)))) + { + static if (isIntegral!U) + payload = rhs; + else + payload = rhs.payload; + return this; + } + /// + @safe unittest + { + Checked!long a; + a = 42L; + assert(a == 42); + a = 4242; + assert(a == 4242); + } + + /// + @safe unittest + { + Checked!long a, b; + a = b = 3; + assert(a == 3 && b == 3); + } + + /** + Construct from a decimal string. The conversion follows the same rules as + $(REF to, std, conv) converting a string to the wrapped `T` type. + + Params: + str = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives) + of characters + */ + this(Range)(Range str) + if (isInputRange!Range && isSomeChar!(ElementType!Range)) + { + import std.conv : to; + + this(to!T(str)); + } + + /** + $(REF to, std, conv) can convert a string to a `Checked!T`: + */ + @system unittest + { + import std.conv : to; + + const a = to!long("1234"); + const b = to!(Checked!long)("1234"); + assert(a == b); + } + + // opCast + /** + Casting operator to integral, `bool`, or floating point type. + + 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. + + Params: + U = The type to cast to + + Returns: + 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`. + */ + 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); + } + } + /// + @safe unittest + { + assert(cast(uint) checked(42) == 42); + assert(cast(uint) checked!WithNaN(-42) == uint.max); + } + + // opEquals + /** + Compares `this` against `rhs` for equality. + + 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. + + Params: + rhs = Right-hand side to compare for equality + + Returns: + 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. + + */ + 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 + { + import std.traits : isUnsigned; + + 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`. + + Returns: + The hash of `this` instance. + + */ + 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); + } + } + + /// ditto + size_t toHash(this _)() shared const nothrow @safe + { + import core.atomic : atomicLoad, MemoryOrder; + static if (is(typeof(this.payload.atomicLoad!(MemoryOrder.acq)) P)) + { + auto payload = __ctfe ? cast(P) this.payload + : this.payload.atomicLoad!(MemoryOrder.acq); + } + else + { + alias payload = this.payload; + } + + 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); + } + } + + /** + Writes a string representation of this to a `sink`. + + Params: + sink = A `Char` accepting + $(REF_ALTTEXT output range, isOutputRange, std,range,primitives). + fmt = A $(REF FormatSpec, std, format) which controls how this + is formatted. + */ + void toString(Writer, Char)(scope ref Writer sink, scope const ref FormatSpec!Char fmt) const + { + import std.format.write : formatValue; + if (fmt.spec == 's') + return formatValue(sink, this, fmt); + else + return formatValue(sink, payload, fmt); + } + + /** + `toString` is rarely directly invoked; the usual way of using it is via + $(REF format, std, format): + */ + @system unittest + { + import std.format; + + assert(format("%04d", checked(15)) == "0015"); + assert(format("0x%02x", checked(15)) == "0x0f"); + } + + // 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. + + Params: + rhs = The right-hand side operand + U = either the type of `rhs` or the underlying type + if `rhs` is a `Checked` instance + Hook1 = If `rhs` is a `Checked` instance, `Hook1` represents + the instance's behavior hook + + Returns: + The result of `hookOpCmp` if `hook` defines `hookOpCmp`. If + `U` is an instance of `Checked` and `hook` does not define + `hookOpCmp`, result of `rhs.hook.hookOpCmp` is returned. + If none of the instances specify the behavior via `hookOpCmp`, + `-1` is returned if `lhs` is lesser than `rhs`, `1` if `lhs` + is greater than `rhs` and `0` on equality. + */ + 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 + { + import std.traits : isUnsigned; + + 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)) @safe 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. + + Params: + op = The unary operator + + Returns: + A `Checked` instance representing the result of the unary + operation + */ + 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. + + Params: + op = The binary operator + rhs = The right hand side operand + U = If `rhs` is a `Checked` instance, `U` represents + the underlying instance type + Hook1 = If `rhs` is a `Checked` instance, `Hook1` represents + the instance's behavior hook + + Returns: + A `Checked` instance representing the result of the binary + operation + */ + 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)) @safe 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. + + Params: + op = The binary operator + lhs = The left hand side operand + + Returns: + A `Checked` instance representing the result of the binary + operation + + */ + 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(lhs, payload); + 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)) @safe 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 + if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool)) + { + static assert(is(typeof(mixin("payload" ~ op ~ "=rhs")) == T)); + + static if (hasMember!(Hook, "hookOpOpAssign")) + { + hook.hookOpOpAssign!op(payload, rhs); + } + else + { + alias R = typeof(get + rhs); + auto r = opBinary!op(rhs).get; + import std.conv : unsigned; + + static if (ProperCompare.hookOpCmp(R.min, min.get) < 0 && + hasMember!(Hook, "onLowerBound")) + { + if (ProperCompare.hookOpCmp(r, min.get) < 0) + { + // Example: Checked!uint(1) += int(-3) + payload = hook.onLowerBound(r, min.get); + return this; + } + } + static if (ProperCompare.hookOpCmp(max.get, R.max) < 0 && + hasMember!(Hook, "onUpperBound")) + { + if (ProperCompare.hookOpCmp(r, max.get) > 0) + { + // Example: Checked!uint(1) += long(uint.max) + payload = hook.onUpperBound(r, max.get); + return this; + } + } + payload = cast(T) r; + } + return this; + } + + /// ditto + ref Checked opOpAssign(string op, Rhs)(const Rhs rhs) return + if (is(Rhs == Checked!(RhsT, RhsHook), RhsT, RhsHook)) + { + return opOpAssign!(op, typeof(rhs.payload))(rhs.payload); + } + + /// + static if (is(T == int) && is(Hook == void)) @safe unittest + { + static struct MyHook + { + static bool thereWereErrors; + static T onLowerBound(Rhs, T)(Rhs rhs, T bound) + { + thereWereErrors = true; + return bound; + } + static T onUpperBound(Rhs, T)(Rhs rhs, T bound) + { + thereWereErrors = true; + return bound; + } + } + auto x = checked!MyHook(byte.min); + x -= 1; + assert(MyHook.thereWereErrors); + MyHook.thereWereErrors = false; + x = byte.max; + x += 1; + assert(MyHook.thereWereErrors); + } +} + +/// +@safe @nogc pure nothrow unittest +{ + // Hook that ignores all problems. + static struct Ignore + { + @nogc nothrow pure @safe static: + Dst onBadCast(Dst, Src)(Src src) { return cast(Dst) src; } + Lhs onLowerBound(Rhs, T)(Rhs rhs, T bound) { return cast(T) rhs; } + T onUpperBound(Rhs, T)(Rhs rhs, T bound) { return cast(T) rhs; } + bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) { return lhs == rhs; } + int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) { return (lhs > rhs) - (lhs < rhs); } + typeof(~Lhs()) onOverflow(string x, Lhs)(ref Lhs lhs) { return mixin(x ~ "lhs"); } + typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + static if (x == "/") + return typeof(lhs / rhs).min; + else + return mixin("lhs" ~ x ~ "rhs"); + } + } + + auto x = Checked!(int, Ignore)(5) + 7; +} + + +/** + +Convenience function that turns an integral into the corresponding `Checked` +instance by using template argument deduction. The hook type may be specified +(by default `Abort`). + +Params: + Hook = type that customizes the behavior, by default `Abort` + T = type represetinfg the underlying represantion of the `Checked` instance + value = the actual value of the representation + +Returns: + A `Checked` instance customized by the provided `Hook` and `value` +*/ +Checked!(T, Hook) checked(Hook = Abort, T)(const T value) +if (is(typeof(Checked!(T, Hook)(value)))) +{ + return Checked!(T, Hook)(value); +} + +/// +@safe unittest +{ + static assert(is(typeof(checked(42)) == Checked!int)); + assert(checked(42) == Checked!int(42)); + static assert(is(typeof(checked!WithNaN(42)) == Checked!(int, WithNaN))); + assert(checked!WithNaN(42) == Checked!(int, WithNaN)(42)); +} + +// get +@safe unittest +{ + void test(T)() + { + assert(Checked!(T, void)(ubyte(22)).get == 22); + } + test!ubyte; + test!(const ubyte); + test!(immutable ubyte); +} + +@system unittest +{ + // https://issues.dlang.org/show_bug.cgi?id=21758 + assert(4 * checked(5L) == 20); + assert(20 / checked(5L) == 4); + assert(2 ^^ checked(3L) == 8); + assert(12 % checked(5L) == 2); + assert((0xff & checked(3L)) == 3); + assert((0xf0 | checked(3L)) == 0xf3); + assert((0xff ^ checked(3L)) == 0xfc); +} + +// Abort +/** + +Force all integral errors to fail by printing an error message to `stderr` and +then abort the program. `Abort` is the default second argument for `Checked`. + +*/ +struct Abort +{ +static: + /** + + Called automatically upon a bad cast (one that loses precision or attempts + to convert a negative value to an unsigned type). The source type is `Src` + and the destination type is `Dst`. + + Params: + src = Souce operand + + Returns: + Nominally the result is the desired value of the cast operation, + which will be forwarded as the result of the cast. For `Abort`, the + function never returns because it aborts the program. + */ + Dst onBadCast(Dst, Src)(Src src) + { + Warn.onBadCast!Dst(src); + assert(0); + } + + /** + + Called automatically upon a bounds error. + + Params: + rhs = The right-hand side value in the assignment, after the operator has + been evaluated + bound = The value of the bound being violated + + Returns: Nominally the result is the desired value of the operator, which + will be forwarded as result. For `Abort`, the function never returns because + it aborts the program. + + */ + T onLowerBound(Rhs, T)(Rhs rhs, T bound) + { + Warn.onLowerBound(rhs, bound); + assert(0); + } + /// ditto + T onUpperBound(Rhs, T)(Rhs rhs, T bound) + { + Warn.onUpperBound(rhs, bound); + assert(0); + } + + /** + + Called automatically upon a comparison for equality. In case of a erroneous + comparison (one that would make a signed negative value appear equal to an + unsigned positive value), this hook issues `assert(0)` which terminates the + application. + + Params: + lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + rhs = The right-hand side type involved in the operator + + Returns: Upon a correct comparison, returns the result of the comparison. + Otherwise, the function terminates the application so it never returns. + + */ + static bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + bool error; + auto result = opChecked!"=="(lhs, rhs, error); + if (error) + { + Warn.hookOpEquals(lhs, rhs); + assert(0); + } + return result; + } + + /** + + Called automatically upon a comparison for ordering using one of the + operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. + it would make a signed negative value appear greater than or equal to an + unsigned positive value), then application is terminated with `assert(0)`. + Otherwise, the three-state result is returned (positive if $(D lhs > rhs), + negative if $(D lhs < rhs), `0` otherwise). + + Params: + lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + rhs = The right-hand side type involved in the operator + + Returns: For correct comparisons, returns a positive integer if $(D lhs > + rhs), a negative integer if $(D lhs < rhs), `0` if the two are equal. Upon + a mistaken comparison such as $(D int(-1) < uint(0)), the function never + returns because it aborts the program. + + */ + int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + bool error; + auto result = opChecked!"cmp"(lhs, rhs, error); + if (error) + { + Warn.hookOpCmp(lhs, rhs); + assert(0); + } + return result; + } + + /** + + Called automatically upon an overflow during a unary or binary operation. + + Params: + x = The operator, e.g. `-` + lhs = The left-hand side (or sole) argument + rhs = The right-hand side type involved in the operator + + Returns: Nominally the result is the desired value of the operator, which + will be forwarded as result. For `Abort`, the function never returns because + it aborts the program. + + */ + typeof(~Lhs()) onOverflow(string x, Lhs)(Lhs lhs) + { + Warn.onOverflow!x(lhs); + assert(0); + } + /// ditto + typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + Warn.onOverflow!x(lhs, rhs); + assert(0); + } +} + +/// +@safe unittest +{ + void test(T)() + { + Checked!(int, Abort) x; + x = 42; + auto x1 = cast(T) x; + assert(x1 == 42); + //x1 += long(int.max); + } + test!short; + test!(const short); + test!(immutable short); +} + + +// Throw +/** + +Force all integral errors to fail by throwing an exception of type +`Throw.CheckFailure`. The message coming with the error is similar to the one +printed by `Warn`. + +*/ +struct Throw +{ + /** + Exception type thrown upon any failure. + */ + static class CheckFailure : Exception + { + /** + Params: + f = format specifier + vals = actual values for the format specifier + */ + this(T...)(string f, T vals) + { + import std.format : format; + super(format(f, vals)); + } + } + + /** + + Called automatically upon a bad cast (one that loses precision or attempts + to convert a negative value to an unsigned type). The source type is `Src` + and the destination type is `Dst`. + + Params: + src = source operand + + Returns: + Nominally the result is the desired value of the cast operation, + which will be forwarded as the result of the cast. For `Throw`, the + function never returns because it throws an exception. + + Throws: + `CheckFailure` on bad cast + */ + static Dst onBadCast(Dst, Src)(Src src) + { + throw new CheckFailure("Erroneous cast: cast(%s) %s(%s)", + Dst.stringof, Src.stringof, src); + } + + /** + + Called automatically upon a bounds error. + + Params: + rhs = The right-hand side value in the assignment, after the operator has + been evaluated + bound = The value of the bound being violated + + Returns: + Nominally the result is the desired value of the operator, which + will be forwarded as result. For `Throw`, the function never returns because + it throws. + + Throws: + `CheckFailure` on overflow + + */ + static T onLowerBound(Rhs, T)(Rhs rhs, T bound) + { + throw new CheckFailure("Lower bound error: %s(%s) < %s(%s)", + Rhs.stringof, rhs, T.stringof, bound); + } + /// ditto + static T onUpperBound(Rhs, T)(Rhs rhs, T bound) + { + throw new CheckFailure("Upper bound error: %s(%s) > %s(%s)", + Rhs.stringof, rhs, T.stringof, bound); + } + + /** + + Called automatically upon a comparison for equality. Throws upon an + erroneous comparison (one that would make a signed negative value appear + equal to an unsigned positive value). + + Params: + lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + rhs = The right-hand side type involved in the operator + + Returns: The result of the comparison. + + Throws: `CheckFailure` if the comparison is mathematically erroneous. + + */ + static bool hookOpEquals(L, R)(L lhs, R rhs) + { + bool error; + auto result = opChecked!"=="(lhs, rhs, error); + if (error) + { + throw new CheckFailure("Erroneous comparison: %s(%s) == %s(%s)", + L.stringof, lhs, R.stringof, rhs); + } + return result; + } + + /** + + Called automatically upon a comparison for ordering using one of the + operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. + it would make a signed negative value appear greater than or equal to an + unsigned positive value), throws a `Throw.CheckFailure` exception. + Otherwise, the three-state result is returned (positive if $(D lhs > rhs), + negative if $(D lhs < rhs), `0` otherwise). + + Params: + lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + rhs = The right-hand side type involved in the operator + + Returns: For correct comparisons, returns a positive integer if $(D lhs > + rhs), a negative integer if $(D lhs < rhs), `0` if the two are equal. + + Throws: Upon a mistaken comparison such as $(D int(-1) < uint(0)), the + function never returns because it throws a `Throw.CheckedFailure` exception. + + */ + static int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + bool error; + auto result = opChecked!"cmp"(lhs, rhs, error); + if (error) + { + throw new CheckFailure("Erroneous ordering comparison: %s(%s) and %s(%s)", + Lhs.stringof, lhs, Rhs.stringof, rhs); + } + return result; + } + + /** + + Called automatically upon an overflow during a unary or binary operation. + + Params: + x = The operator, e.g. `-` + lhs = The left-hand side (or sole) argument + rhs = The right-hand side type involved in the operator + + Returns: + Nominally the result is the desired value of the operator, which + will be forwarded as result. For `Throw`, the function never returns because + it throws an exception. + + Throws: + `CheckFailure` on overflow + + */ + static typeof(~Lhs()) onOverflow(string x, Lhs)(Lhs lhs) + { + throw new CheckFailure("Overflow on unary operator: %s%s(%s)", + x, Lhs.stringof, lhs); + } + /// ditto + static typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + throw new CheckFailure("Overflow on binary operator: %s(%s) %s %s(%s)", + Lhs.stringof, lhs, x, Rhs.stringof, rhs); + } +} + +/// +@safe unittest +{ + void test(T)() + { + Checked!(int, Throw) x; + x = 42; + auto x1 = cast(T) x; + assert(x1 == 42); + x = T.max + 1; + import std.exception : assertThrown, assertNotThrown; + assertThrown(cast(T) x); + x = x.max; + assertThrown(x += 42); + assertThrown(x += 42L); + x = x.min; + assertThrown(-x); + assertThrown(x -= 42); + assertThrown(x -= 42L); + x = -1; + assertNotThrown(x == -1); + assertThrown(x == uint(-1)); + assertNotThrown(x <= -1); + assertThrown(x <= uint(-1)); + } + test!short; + test!(const short); + test!(immutable short); +} + +// Warn +/** +Hook that prints to `stderr` a trace of all integral errors, without affecting +default behavior. +*/ +struct Warn +{ + import std.stdio : writefln; +static: + /** + + Called automatically upon a bad cast from `src` to type `Dst` (one that + loses precision or attempts to convert a negative value to an unsigned + type). + + Params: + src = The source of the cast + Dst = The target type of the cast + + Returns: `cast(Dst) src` + + */ + Dst onBadCast(Dst, Src)(Src src) + { + trustedStderr.writefln("Erroneous cast: cast(%s) %s(%s)", + Dst.stringof, Src.stringof, src); + return cast(Dst) src; + } + + /** + + Called automatically upon a bad `opOpAssign` call (one that loses precision + or attempts to convert a negative value to an unsigned type). + + Params: + rhs = The right-hand side value in the assignment, after the operator has + been evaluated + bound = The bound being violated + + Returns: `cast(T) rhs` + */ + T onLowerBound(Rhs, T)(Rhs rhs, T bound) + { + trustedStderr.writefln("Lower bound error: %s(%s) < %s(%s)", + Rhs.stringof, rhs, T.stringof, bound); + return cast(T) rhs; + } + /// ditto + T onUpperBound(Rhs, T)(Rhs rhs, T bound) + { + trustedStderr.writefln("Upper bound error: %s(%s) > %s(%s)", + Rhs.stringof, rhs, T.stringof, bound); + return cast(T) rhs; + } + + /** + + Called automatically upon a comparison for equality. In case of an Erroneous + comparison (one that would make a signed negative value appear equal to an + unsigned positive value), writes a warning message to `stderr` as a side + effect. + + Params: + lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + rhs = The right-hand side type involved in the operator + + Returns: In all cases the function returns the built-in result of $(D lhs == + rhs). + + */ + bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + bool error; + auto result = opChecked!"=="(lhs, rhs, error); + if (error) + { + trustedStderr.writefln("Erroneous comparison: %s(%s) == %s(%s)", + Lhs.stringof, lhs, Rhs.stringof, rhs); + return lhs == rhs; + } + return result; + } + + /// + @safe unittest + { + auto x = checked!Warn(-42); + // Passes + assert(x == -42); + // Passes but prints a warning + // assert(x == uint(-42)); + } + + /** + + Called automatically upon a comparison for ordering using one of the + operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. + it would make a signed negative value appear greater than or equal to an + unsigned positive value), then a warning message is printed to `stderr`. + + Params: + lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + rhs = The right-hand side type involved in the operator + + Returns: In all cases, returns $(D lhs < rhs ? -1 : lhs > rhs). The result + is not autocorrected in case of an erroneous comparison. + + */ + int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + bool error; + auto result = opChecked!"cmp"(lhs, rhs, error); + if (error) + { + trustedStderr.writefln("Erroneous ordering comparison: %s(%s) and %s(%s)", + Lhs.stringof, lhs, Rhs.stringof, rhs); + return lhs < rhs ? -1 : lhs > rhs; + } + return result; + } + + /// + @safe unittest + { + auto x = checked!Warn(-42); + // Passes + assert(x <= -42); + // Passes but prints a warning + // assert(x <= uint(-42)); + } + + /** + + Called automatically upon an overflow during a unary or binary operation. + + Params: + x = The operator involved + Lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of + the operator is `Checked!int` + Rhs = The right-hand side type involved in the operator + + Returns: + $(D mixin(x ~ "lhs")) for unary, $(D mixin("lhs" ~ x ~ "rhs")) for + binary + + */ + typeof(~Lhs()) onOverflow(string x, Lhs)(ref Lhs lhs) + { + trustedStderr.writefln("Overflow on unary operator: %s%s(%s)", + x, Lhs.stringof, lhs); + return mixin(x ~ "lhs"); + } + /// ditto + typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + trustedStderr.writefln("Overflow on binary operator: %s(%s) %s %s(%s)", + Lhs.stringof, lhs, x, Rhs.stringof, rhs); + static if (x == "/") // Issue 20743: mixin below would cause SIGFPE on POSIX + return typeof(lhs / rhs).min; // or EXCEPTION_INT_OVERFLOW on Windows + else + return mixin("lhs" ~ x ~ "rhs"); + } + + // This is safe because we do not assign to the reference returned by + // `stderr`. The ability for the caller to do that is why `stderr` is not + // safe in the general case. + private @property auto ref trustedStderr() @trusted + { + import std.stdio : stderr; + + return stderr; + } +} + +/// +@safe unittest +{ + auto x = checked!Warn(42); + short x1 = cast(short) x; + //x += long(int.max); + auto y = checked!Warn(cast(const int) 42); + short y1 = cast(const byte) y; +} + +@system unittest +{ + auto a = checked!Warn(int.min); + auto b = checked!Warn(-1); + auto x = checked!Abort(int.min); + auto y = checked!Abort(-1); + + // Temporarily redirect output to stderr to make sure we get the right output. + import std.file : exists, remove; + import std.process : uniqueTempPath; + import std.stdio : stderr; + auto tmpname = uniqueTempPath; + scope(exit) if (exists(tmpname)) remove(tmpname); + auto t = stderr; + stderr.open(tmpname, "w"); + // Open a new scope to minimize code ran with stderr redirected. + { + scope(exit) stderr = t; + assert(a / b == a * b); + import std.exception : assertThrown; + import core.exception : AssertError; + assertThrown!AssertError(x / y); + } + import std.file : readText; + import std.ascii : newline; + auto witness = readText(tmpname); + auto expected = +"Overflow on binary operator: int(-2147483648) / const(int)(-1)" ~ newline ~ +"Overflow on binary operator: int(-2147483648) * const(int)(-1)" ~ newline ~ +"Overflow on binary operator: int(-2147483648) / const(int)(-1)" ~ newline; + assert(witness == expected, "'" ~ witness ~ "'"); +} + +// https://issues.dlang.org/show_bug.cgi?id=22249 +@safe unittest +{ + alias _ = Warn.onLowerBound!(int, int); +} + +// ProperCompare +/** + +Hook that provides arithmetically correct comparisons for equality and ordering. +Comparing an object of type $(D Checked!(X, ProperCompare)) against another +integral (for equality or ordering) ensures that no surprising conversions from +signed to unsigned integral occur before the comparison. Using $(D Checked!(X, +ProperCompare)) on either side of a comparison for equality against a +floating-point number makes sure the integral can be properly converted to the +floating point type, thus making sure equality is transitive. + +*/ +struct ProperCompare +{ + /** + Hook for `==` and `!=` that ensures comparison against integral values has + the behavior expected by the usual arithmetic rules. The built-in semantics + yield surprising behavior when comparing signed values against unsigned + values for equality, for example $(D uint.max == -1) or $(D -1_294_967_296 == + 3_000_000_000u). The call $(D hookOpEquals(x, y)) returns `true` if and only + if `x` and `y` represent the same arithmetic number. + + If one of the numbers is an integral and the other is a floating-point + number, $(D hookOpEquals(x, y)) returns `true` if and only if the integral + can be converted exactly (without approximation) to the floating-point + number. This is in order to preserve transitivity of equality: if $(D + hookOpEquals(x, y)) and $(D hookOpEquals(y, z)) then $(D hookOpEquals(y, + z)), in case `x`, `y`, and `z` are a mix of integral and floating-point + numbers. + + Params: + lhs = The left-hand side of the comparison for equality + rhs = The right-hand side of the comparison for equality + + Returns: + The result of the comparison, `true` if the values are equal + */ + static bool hookOpEquals(L, R)(L lhs, R rhs) + { + alias C = typeof(lhs + rhs); + static if (isFloatingPoint!C) + { + static if (!isFloatingPoint!L) + { + return hookOpEquals(rhs, lhs); + } + else static if (!isFloatingPoint!R) + { + static assert(isFloatingPoint!L && !isFloatingPoint!R); + auto rhs1 = C(rhs); + return lhs == rhs1 && cast(R) rhs1 == rhs; + } + else + return lhs == rhs; + } + else + { + bool error; + auto result = opChecked!"=="(lhs, rhs, error); + if (error) + { + // Only possible error is a wrong "true" + return false; + } + return result; + } + } + + /** + Hook for `<`, `<=`, `>`, and `>=` that ensures comparison against integral + values has the behavior expected by the usual arithmetic rules. The built-in + semantics yield surprising behavior when comparing signed values against + unsigned values, for example $(D 0u < -1). The call $(D hookOpCmp(x, y)) + returns `-1` if and only if `x` is smaller than `y` in abstract arithmetic + sense. + + If one of the numbers is an integral and the other is a floating-point + number, $(D hookOpEquals(x, y)) returns a floating-point number that is `-1` + if `x < y`, `0` if `x == y`, `1` if `x > y`, and `NaN` if the floating-point + number is `NaN`. + + Params: + lhs = The left-hand side of the comparison for ordering + rhs = The right-hand side of the comparison for ordering + + Returns: + The result of the comparison (negative if $(D lhs < rhs), positive if $(D + lhs > rhs), `0` if the values are equal) + */ + static auto hookOpCmp(L, R)(L lhs, R rhs) + { + alias C = typeof(lhs + rhs); + static if (isFloatingPoint!C) + { + return lhs < rhs + ? C(-1) + : lhs > rhs ? C(1) : lhs == rhs ? C(0) : C.init; + } + else + { + static if (!valueConvertible!(L, C) || !valueConvertible!(R, C)) + { + static assert(isUnsigned!C); + static assert(isUnsigned!L != isUnsigned!R); + if (!isUnsigned!L && lhs < 0) + return -1; + if (!isUnsigned!R && rhs < 0) + return 1; + } + return lhs < rhs ? -1 : lhs > rhs; + } + } +} + +/// +@safe unittest +{ + alias opEqualsProper = ProperCompare.hookOpEquals; + assert(opEqualsProper(42, 42)); + assert(opEqualsProper(42.0, 42.0)); + assert(opEqualsProper(42u, 42)); + assert(opEqualsProper(42, 42u)); + assert(-1 == 4294967295u); + assert(!opEqualsProper(-1, 4294967295u)); + assert(!opEqualsProper(const uint(-1), -1)); + assert(!opEqualsProper(uint(-1), -1.0)); + assert(3_000_000_000U == -1_294_967_296); + assert(!opEqualsProper(3_000_000_000U, -1_294_967_296)); +} + +@safe unittest +{ + alias opCmpProper = ProperCompare.hookOpCmp; + assert(opCmpProper(42, 42) == 0); + assert(opCmpProper(42, 42.0) == 0); + assert(opCmpProper(41, 42.0) < 0); + assert(opCmpProper(42, 41.0) > 0); + import std.math.traits : isNaN; + assert(isNaN(opCmpProper(41, double.init))); + assert(opCmpProper(42u, 42) == 0); + assert(opCmpProper(42, 42u) == 0); + assert(opCmpProper(-1, uint(-1)) < 0); + assert(opCmpProper(uint(-1), -1) > 0); + assert(opCmpProper(-1.0, -1) == 0); +} + +@safe unittest +{ + auto x1 = Checked!(uint, ProperCompare)(42u); + assert(x1.get < -1); + assert(x1 > -1); +} + +// WithNaN +/** + +Hook that reserves a special value as a "Not a Number" representative. For +signed integrals, the reserved value is `T.min`. For signed integrals, the +reserved value is `T.max`. + +The default value of a $(D Checked!(X, WithNaN)) is its NaN value, so care must +be taken that all variables are explicitly initialized. Any arithmetic and logic +operation involving at least on NaN becomes NaN itself. All of $(D a == b), $(D +a < b), $(D a > b), $(D a <= b), $(D a >= b) yield `false` if at least one of +`a` and `b` is NaN. + +*/ +struct WithNaN +{ +static: + /** + The default value used for values not explicitly initialized. It is the NaN + value, i.e. `T.min` for signed integrals and `T.max` for unsigned integrals. + */ + enum T defaultValue(T) = T.min == 0 ? T.max : T.min; + /** + The maximum value representable is `T.max` for signed integrals, $(D + T.max - 1) for unsigned integrals. The minimum value representable is $(D + T.min + 1) for signed integrals, `0` for unsigned integrals. + */ + enum T max(T) = cast(T) (T.min == 0 ? T.max - 1 : T.max); + /// ditto + enum T min(T) = cast(T) (T.min == 0 ? T(0) : T.min + 1); + + /** + If `rhs` is `WithNaN.defaultValue!Rhs`, returns + `WithNaN.defaultValue!Lhs`. Otherwise, returns $(D cast(Lhs) rhs). + + Params: + rhs = the value being cast (`Rhs` is the first argument to `Checked`) + Lhs = the target type of the cast + + Returns: The result of the cast operation. + */ + Lhs hookOpCast(Lhs, Rhs)(Rhs rhs) + { + static if (is(Lhs == bool)) + { + return rhs != defaultValue!Rhs && rhs != 0; + } + else static if (valueConvertible!(Rhs, Lhs)) + { + return rhs != defaultValue!Rhs ? Lhs(rhs) : defaultValue!Lhs; + } + else + { + // Not value convertible, only viable option is rhs fits within the + // bounds of Lhs + static if (ProperCompare.hookOpCmp(Rhs.min, Lhs.min) < 0) + { + // Example: hookOpCast!short(int(42)), hookOpCast!uint(int(42)) + if (ProperCompare.hookOpCmp(rhs, Lhs.min) < 0) + return defaultValue!Lhs; + } + static if (ProperCompare.hookOpCmp(Rhs.max, Lhs.max) > 0) + { + // Example: hookOpCast!int(uint(42)) + if (ProperCompare.hookOpCmp(rhs, Lhs.max) > 0) + return defaultValue!Lhs; + } + return cast(Lhs) rhs; + } + } + + /// + @safe unittest + { + auto x = checked!WithNaN(422); + assert((cast(ubyte) x) == 255); + x = checked!WithNaN(-422); + assert((cast(byte) x) == -128); + assert(cast(short) x == -422); + assert(cast(bool) x); + x = x.init; // set back to NaN + assert(x != true); + assert(x != false); + } + + /** + + Returns `false` if $(D lhs == WithNaN.defaultValue!Lhs), $(D lhs == rhs) + otherwise. + + Params: + lhs = The left-hand side of the comparison (`Lhs` is the first argument to + `Checked`) + rhs = The right-hand side of the comparison + + Returns: `lhs != WithNaN.defaultValue!Lhs && lhs == rhs` + */ + bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + return lhs != defaultValue!Lhs && lhs == rhs; + } + + /** + + If $(D lhs == WithNaN.defaultValue!Lhs), returns `double.init`. Otherwise, + has the same semantics as the default comparison. + + Params: + lhs = The left-hand side of the comparison (`Lhs` is the first argument to + `Checked`) + rhs = The right-hand side of the comparison + + Returns: `double.init` if `lhs == WitnNaN.defaultValue!Lhs`, `-1.0` if $(D + lhs < rhs), `0.0` if $(D lhs == rhs), `1.0` if $(D lhs > rhs). + + */ + double hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + if (lhs == defaultValue!Lhs) return double.init; + return lhs < rhs + ? -1.0 + : lhs > rhs ? 1.0 : lhs == rhs ? 0.0 : double.init; + } + + /// + @safe unittest + { + Checked!(int, WithNaN) x; + assert(!(x < 0) && !(x > 0) && !(x == 0)); + x = 1; + assert(x > 0 && !(x < 0) && !(x == 0)); + } + + /** + Defines hooks for unary operators `-`, `~`, `++`, and `--`. + + For `-` and `~`, if $(D v == WithNaN.defaultValue!T), returns + `WithNaN.defaultValue!T`. Otherwise, the semantics is the same as for the + built-in operator. + + For `++` and `--`, if $(D v == WithNaN.defaultValue!Lhs) or the operation + would result in an overflow, sets `v` to `WithNaN.defaultValue!T`. + Otherwise, the semantics is the same as for the built-in operator. + + Params: + x = The operator symbol + v = The left-hand side of the comparison (`T` is the first argument to + `Checked`) + + Returns: $(UL $(LI For $(D x == "-" || x == "~"): If $(D v == + WithNaN.defaultValue!T), the function returns `WithNaN.defaultValue!T`. + Otherwise it returns the normal result of the operator.) $(LI For $(D x == + "++" || x == "--"): The function returns `void`.)) + + */ + auto hookOpUnary(string x, T)(ref T v) + { + static if (x == "-" || x == "~") + { + return v != defaultValue!T ? mixin(x ~ "v") : v; + } + else static if (x == "++") + { + static if (defaultValue!T == T.min) + { + if (v != defaultValue!T) + { + if (v == T.max) v = defaultValue!T; + else ++v; + } + } + else + { + static assert(defaultValue!T == T.max); + if (v != defaultValue!T) ++v; + } + } + else static if (x == "--") + { + if (v != defaultValue!T) --v; + } + } + + /// + @safe unittest + { + Checked!(int, WithNaN) x; + ++x; + assert(x.isNaN); + x = 1; + assert(!x.isNaN); + x = -x; + ++x; + assert(!x.isNaN); + } + + @safe unittest // for coverage + { + Checked!(uint, WithNaN) y; + ++y; + assert(y.isNaN); + } + + /** + Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, + `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the + left-hand side operand. If $(D lhs == WithNaN.defaultValue!Lhs), returns + $(D WithNaN.defaultValue!(typeof(lhs + rhs))) without evaluating the + operand. Otherwise, evaluates the operand. If evaluation does not overflow, + returns the result. Otherwise, returns $(D WithNaN.defaultValue!(typeof(lhs + + rhs))). + + Params: + x = The operator symbol + lhs = The left-hand side operand (`Lhs` is the first argument to `Checked`) + rhs = The right-hand side operand + + Returns: If $(D lhs != WithNaN.defaultValue!Lhs) and the operator does not + overflow, the function returns the same result as the built-in operator. In + all other cases, returns $(D WithNaN.defaultValue!(typeof(lhs + rhs))). + */ + auto hookOpBinary(string x, L, R)(L lhs, R rhs) + { + alias Result = typeof(lhs + rhs); + if (lhs != defaultValue!L) + { + bool error; + auto result = opChecked!x(lhs, rhs, error); + if (!error) return result; + } + return defaultValue!Result; + } + + /// + @safe unittest + { + Checked!(int, WithNaN) x; + assert((x + 1).isNaN); + x = 100; + assert(!(x + 1).isNaN); + } + + /** + Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, + `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the + right-hand side operand. If $(D rhs == WithNaN.defaultValue!Rhs), returns + $(D WithNaN.defaultValue!(typeof(lhs + rhs))) without evaluating the + operand. Otherwise, evaluates the operand. If evaluation does not overflow, + returns the result. Otherwise, returns $(D WithNaN.defaultValue!(typeof(lhs + + rhs))). + + Params: + x = The operator symbol + lhs = The left-hand side operand + rhs = The right-hand side operand (`Rhs` is the first argument to `Checked`) + + Returns: If $(D rhs != WithNaN.defaultValue!Rhs) and the operator does not + overflow, the function returns the same result as the built-in operator. In + all other cases, returns $(D WithNaN.defaultValue!(typeof(lhs + rhs))). + */ + auto hookOpBinaryRight(string x, L, R)(L lhs, R rhs) + { + alias Result = typeof(lhs + rhs); + if (rhs != defaultValue!R) + { + bool error; + auto result = opChecked!x(lhs, rhs, error); + if (!error) return result; + } + return defaultValue!Result; + } + /// + @safe unittest + { + Checked!(int, WithNaN) x; + assert((1 + x).isNaN); + x = 100; + assert(!(1 + x).isNaN); + } + + /** + + Defines hooks for binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, + `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` for cases where a `Checked` + object is the left-hand side operand. If $(D lhs == + WithNaN.defaultValue!Lhs), no action is carried. Otherwise, evaluates the + operand. If evaluation does not overflow and fits in `Lhs` without loss of + information or change of sign, sets `lhs` to the result. Otherwise, sets + `lhs` to `WithNaN.defaultValue!Lhs`. + + Params: + x = The operator symbol (without the `=`) + lhs = The left-hand side operand (`Lhs` is the first argument to `Checked`) + rhs = The right-hand side operand + + Returns: `void` + */ + void hookOpOpAssign(string x, L, R)(ref L lhs, R rhs) + { + if (lhs == defaultValue!L) + return; + bool error; + auto temp = opChecked!x(lhs, rhs, error); + lhs = error + ? defaultValue!L + : hookOpCast!L(temp); + } + + /// + @safe unittest + { + Checked!(int, WithNaN) x; + x += 4; + assert(x.isNaN); + x = 0; + x += 4; + assert(!x.isNaN); + x += int.max; + assert(x.isNaN); + } +} + +/// +@safe unittest +{ + auto x1 = Checked!(int, WithNaN)(); + assert(x1.isNaN); + assert(x1.get == int.min); + assert(x1 != x1); + assert(!(x1 < x1)); + assert(!(x1 > x1)); + assert(!(x1 == x1)); + ++x1; + assert(x1.isNaN); + assert(x1.get == int.min); + --x1; + assert(x1.isNaN); + assert(x1.get == int.min); + x1 = 42; + assert(!x1.isNaN); + assert(x1 == x1); + assert(x1 <= x1); + assert(x1 >= x1); + static assert(x1.min == int.min + 1); + x1 += long(int.max); +} + +/** +Queries whether a $(D Checked!(T, WithNaN)) object is not a number (NaN). + +Params: + x = the `Checked` instance queried + +Returns: + `true` if `x` is a NaN, `false` otherwise +*/ +bool isNaN(T)(const Checked!(T, WithNaN) x) +{ + return x.get == x.init.get; +} + +/// +@safe unittest +{ + auto x1 = Checked!(int, WithNaN)(); + assert(x1.isNaN); + x1 = 1; + assert(!x1.isNaN); + x1 = x1.init; + assert(x1.isNaN); +} + +@safe unittest +{ + void test1(T)() + { + auto x1 = Checked!(T, WithNaN)(); + assert(x1.isNaN); + assert(x1.get == int.min); + assert(x1 != x1); + assert(!(x1 < x1)); + assert(!(x1 > x1)); + assert(!(x1 == x1)); + assert(x1.get == int.min); + auto x2 = Checked!(T, WithNaN)(42); + assert(!x2.isNaN); + assert(x2 == x2); + assert(x2 <= x2); + assert(x2 >= x2); + static assert(x2.min == T.min + 1); + } + test1!int; + test1!(const int); + test1!(immutable int); + + void test2(T)() + { + auto x1 = Checked!(T, WithNaN)(); + assert(x1.get == T.min); + assert(x1 != x1); + assert(!(x1 < x1)); + assert(!(x1 > x1)); + assert(!(x1 == x1)); + ++x1; + assert(x1.get == T.min); + --x1; + assert(x1.get == T.min); + x1 = 42; + assert(x1 == x1); + assert(x1 <= x1); + assert(x1 >= x1); + static assert(x1.min == T.min + 1); + x1 += long(T.max); + } + test2!int; +} + +@safe unittest +{ + alias Smart(T) = Checked!(Checked!(T, ProperCompare), WithNaN); + Smart!int x1; + assert(x1 != x1); + x1 = -1; + assert(x1 < 1u); + auto x2 = Smart!(const int)(42); +} + +// Saturate +/** + +Hook that implements $(I saturation), i.e. any arithmetic operation that would +overflow leaves the result at its extreme value (`min` or `max` depending on the +direction of the overflow). + +Saturation is not sticky; if a value reaches its saturation value, another +operation may take it back to normal range. + +*/ +struct Saturate +{ +static: + /** + + Implements saturation for operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, + and `>>>=`. This hook is called if the result of the binary operation does + not fit in `Lhs` without loss of information or a change in sign. + + Params: + Rhs = The right-hand side type in the assignment, after the operation has + been computed + bound = The bound being violated + + Returns: `Lhs.max` if $(D rhs >= 0), `Lhs.min` otherwise. + + */ + T onLowerBound(Rhs, T)(Rhs, T bound) + { + return bound; + } + /// ditto + T onUpperBound(Rhs, T)(Rhs, T bound) + { + return bound; + } + /// + @safe unittest + { + auto x = checked!Saturate(short(100)); + x += 33000; + assert(x == short.max); + x -= 70000; + assert(x == short.min); + } + + /** + + Implements saturation for operators `+`, `-` (unary and binary), `*`, `/`, + `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. + + For unary `-`, `onOverflow` is called if $(D lhs == Lhs.min) and `Lhs` is a + signed type. The function returns `Lhs.max`. + + For binary operators, the result is as follows: $(UL $(LI `Lhs.max` if the + result overflows in the positive direction, on division by `0`, or on + shifting right by a negative value) $(LI `Lhs.min` if the result overflows + in the negative direction) $(LI `0` if `lhs` is being shifted left by a + negative value, or shifted right by a large positive value)) + + Params: + x = The operator involved in the `opAssign` operation + Lhs = The left-hand side type of the operator (`Lhs` is the first argument to + `Checked`) + Rhs = The right-hand side type in the operator + + Returns: The saturated result of the operator. + + */ + auto onOverflow(string x, Lhs)(Lhs) + { + static assert(x == "-" || x == "++" || x == "--"); + return x == "--" ? Lhs.min : Lhs.max; + } + /// ditto + typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + static if (x == "+") + return rhs >= 0 ? Lhs.max : Lhs.min; + else static if (x == "*") + return (lhs >= 0) == (rhs >= 0) ? Lhs.max : Lhs.min; + else static if (x == "^^") + return lhs > 0 || !(rhs & 1) ? Lhs.max : Lhs.min; + else static if (x == "-") + return rhs >= 0 ? Lhs.min : Lhs.max; + else static if (x == "/" || x == "%") + return Lhs.max; + else static if (x == "<<") + return rhs >= 0 ? Lhs.max : 0; + else static if (x == ">>" || x == ">>>") + return rhs >= 0 ? 0 : Lhs.max; + else + static assert(false); + } + /// + @safe unittest + { + assert(checked!Saturate(int.max) + 1 == int.max); + assert(checked!Saturate(100) ^^ 10 == int.max); + assert(checked!Saturate(-100) ^^ 10 == int.max); + assert(checked!Saturate(100) / 0 == int.max); + assert(checked!Saturate(100) << -1 == 0); + assert(checked!Saturate(100) << 33 == int.max); + assert(checked!Saturate(100) >> -1 == int.max); + assert(checked!Saturate(100) >> 33 == 0); + } +} + +/// +@safe unittest +{ + auto x = checked!Saturate(int.max); + ++x; + assert(x == int.max); + --x; + assert(x == int.max - 1); + x = int.min; + assert(-x == int.max); + x -= 42; + assert(x == int.min); + assert(x * -2 == int.max); +} + +/* +Yields `true` if `T1` is "value convertible" (by C's "value preserving" rule, +see $(HTTP c-faq.com/expr/preservingrules.html)) to `T2`, where the two are +integral types. That is, all of values in `T1` are also in `T2`. For example +`int` is value convertible to `long` but not to `uint` or `ulong`. +*/ +private enum valueConvertible(T1, T2) = isIntegral!T1 && isIntegral!T2 && + is(T1 : T2) && ( + isUnsigned!T1 == isUnsigned!T2 || // same signedness + !isUnsigned!T2 && T2.sizeof > T1.sizeof // safely convertible + ); + +/** + +Defines binary operations with overflow checking for any two integral types. +The result type obeys the language rules (even when they may be +counterintuitive), and `overflow` is set if an overflow occurs (including +inadvertent change of signedness, e.g. `-1` is converted to `uint`). +Conceptually the behavior is: + +$(OL $(LI Perform the operation in infinite precision) +$(LI If the infinite-precision result fits in the result type, return it and +do not touch `overflow`) +$(LI Otherwise, set `overflow` to `true` and return an unspecified value) +) + +The implementation exploits properties of types and operations to minimize +additional work. + +Params: +x = The binary operator involved, e.g. `/` +lhs = The left-hand side of the operator +rhs = The right-hand side of the operator +overflow = The overflow indicator (assigned `true` in case there's an error) + +Returns: +The result of the operation, which is the same as the built-in operator +*/ +typeof(mixin(x == "cmp" ? "0" : ("L() " ~ x ~ " R()"))) +opChecked(string x, L, R)(const L lhs, const R rhs, ref bool overflow) +if (isIntegral!L && isIntegral!R) +{ + static if (x == "cmp") + alias Result = int; + else + alias Result = typeof(mixin("L() " ~ x ~ " R()")); + + import core.checkedint : addu, adds, subs, muls, subu, mulu; + import std.algorithm.comparison : among; + static if (x == "==") + { + alias C = typeof(lhs + rhs); + static if (valueConvertible!(L, C) && valueConvertible!(R, C)) + { + // Values are converted to R before comparison, cool. + return lhs == rhs; + } + else + { + static assert(isUnsigned!C); + static assert(isUnsigned!L != isUnsigned!R); + if (lhs != rhs) return false; + // R(lhs) and R(rhs) have the same bit pattern, yet may be + // different due to signedness change. + static if (!isUnsigned!R) + { + if (rhs >= 0) + return true; + } + else + { + if (lhs >= 0) + return true; + } + overflow = true; + return true; + } + } + else static if (x == "cmp") + { + alias C = typeof(lhs + rhs); + static if (!valueConvertible!(L, C) || !valueConvertible!(R, C)) + { + static assert(isUnsigned!C); + static assert(isUnsigned!L != isUnsigned!R); + if (!isUnsigned!L && lhs < 0) + { + overflow = true; + return -1; + } + if (!isUnsigned!R && rhs < 0) + { + overflow = true; + return 1; + } + } + return lhs < rhs ? -1 : lhs > rhs; + } + else static if (x.among("<<", ">>", ">>>")) + { + // Handle shift separately from all others. The test below covers + // negative rhs as well. + import std.conv : unsigned; + if (unsigned(rhs) > 8 * Result.sizeof) goto fail; + return mixin("lhs" ~ x ~ "rhs"); + } + else static if (x.among("&", "|", "^")) + { + // Nothing to check + return mixin("lhs" ~ x ~ "rhs"); + } + else static if (x == "^^") + { + // Exponentiation is weird, handle separately + return pow(lhs, rhs, overflow); + } + else static if (valueConvertible!(L, Result) && + valueConvertible!(R, Result)) + { + static if (L.sizeof < Result.sizeof && R.sizeof < Result.sizeof && + x.among("+", "-", "*")) + { + // No checks - both are value converted and result is in range + return mixin("lhs" ~ x ~ "rhs"); + } + else static if (x == "+") + { + static if (isUnsigned!Result) alias impl = addu; + else alias impl = adds; + return impl(Result(lhs), Result(rhs), overflow); + } + else static if (x == "-") + { + static if (isUnsigned!Result) alias impl = subu; + else alias impl = subs; + return impl(Result(lhs), Result(rhs), overflow); + } + else static if (x == "*") + { + static if (!isUnsigned!L && !isUnsigned!R && + is(L == Result)) + { + if (lhs == Result.min && rhs == -1) goto fail; + } + static if (isUnsigned!Result) alias impl = mulu; + else alias impl = muls; + return impl(Result(lhs), Result(rhs), overflow); + } + else static if (x == "/" || x == "%") + { + static if (!isUnsigned!L && !isUnsigned!R && + is(L == Result) && x == "/") + { + if (lhs == Result.min && rhs == -1) goto fail; + } + if (rhs == 0) goto fail; + return mixin("lhs" ~ x ~ "rhs"); + } + else static assert(0, x); + } + else // Mixed signs + { + static assert(isUnsigned!Result); + static assert(isUnsigned!L != isUnsigned!R); + static if (x == "+") + { + static if (!isUnsigned!L) + { + if (lhs < 0) + return subu(Result(rhs), Result(-lhs), overflow); + } + else static if (!isUnsigned!R) + { + if (rhs < 0) + return subu(Result(lhs), Result(-rhs), overflow); + } + return addu(Result(lhs), Result(rhs), overflow); + } + else static if (x == "-") + { + static if (!isUnsigned!L) + { + if (lhs < 0) goto fail; + } + else static if (!isUnsigned!R) + { + if (rhs < 0) + return addu(Result(lhs), Result(-rhs), overflow); + } + return subu(Result(lhs), Result(rhs), overflow); + } + else static if (x == "*") + { + static if (!isUnsigned!L) + { + if (lhs < 0) goto fail; + } + else static if (!isUnsigned!R) + { + if (rhs < 0) goto fail; + } + return mulu(Result(lhs), Result(rhs), overflow); + } + else static if (x == "/" || x == "%") + { + static if (!isUnsigned!L) + { + if (lhs < 0 || rhs == 0) goto fail; + } + else static if (!isUnsigned!R) + { + if (rhs <= 0) goto fail; + } + return mixin("Result(lhs)" ~ x ~ "Result(rhs)"); + } + else static assert(0, x); + } + debug assert(false); +fail: + overflow = true; + return Result(0); +} + +/// +@safe unittest +{ + bool overflow; + assert(opChecked!"+"(const short(1), short(1), overflow) == 2 && !overflow); + assert(opChecked!"+"(1, 1, overflow) == 2 && !overflow); + assert(opChecked!"+"(1, 1u, overflow) == 2 && !overflow); + assert(opChecked!"+"(-1, 1u, overflow) == 0 && !overflow); + assert(opChecked!"+"(1u, -1, overflow) == 0 && !overflow); +} + +/// +@safe unittest +{ + bool overflow; + assert(opChecked!"-"(1, 1, overflow) == 0 && !overflow); + assert(opChecked!"-"(1, 1u, overflow) == 0 && !overflow); + assert(opChecked!"-"(1u, -1, overflow) == 2 && !overflow); + assert(opChecked!"-"(-1, 1u, overflow) == 0 && overflow); +} + +@safe unittest +{ + bool overflow; + assert(opChecked!"*"(2, 3, overflow) == 6 && !overflow); + assert(opChecked!"*"(2, 3u, overflow) == 6 && !overflow); + assert(opChecked!"*"(1u, -1, overflow) == 0 && overflow); + //assert(mul(-1, 1u, overflow) == uint.max - 1 && overflow); +} + +@safe unittest +{ + bool overflow; + assert(opChecked!"/"(6, 3, overflow) == 2 && !overflow); + assert(opChecked!"/"(6, 3, overflow) == 2 && !overflow); + assert(opChecked!"/"(6u, 3, overflow) == 2 && !overflow); + assert(opChecked!"/"(6, 3u, overflow) == 2 && !overflow); + assert(opChecked!"/"(11, 0, overflow) == 0 && overflow); + overflow = false; + assert(opChecked!"/"(6u, 0, overflow) == 0 && overflow); + overflow = false; + assert(opChecked!"/"(-6, 2u, overflow) == 0 && overflow); + overflow = false; + assert(opChecked!"/"(-6, 0u, overflow) == 0 && overflow); + overflow = false; + assert(opChecked!"cmp"(0u, -6, overflow) == 1 && overflow); + overflow = false; + assert(opChecked!"|"(1, 2, overflow) == 3 && !overflow); +} + +/* +Exponentiation function used by the implementation of operator `^^`. +*/ +private pure @safe nothrow @nogc +auto pow(L, R)(const L lhs, const R rhs, ref bool overflow) +if (isIntegral!L && isIntegral!R) +{ + if (rhs <= 1) + { + if (rhs == 0) return 1; + static if (!isUnsigned!R) + return rhs == 1 + ? lhs + : (rhs == -1 && (lhs == 1 || lhs == -1)) ? lhs : 0; + else + return lhs; + } + + typeof(lhs ^^ rhs) b = void; + static if (!isUnsigned!L && isUnsigned!(typeof(b))) + { + // Need to worry about mixed-sign stuff + if (lhs < 0) + { + if (rhs & 1) + { + if (lhs < 0) overflow = true; + return 0; + } + b = -lhs; + } + else + { + b = lhs; + } + } + else + { + b = lhs; + } + if (b == 1) return 1; + if (b == -1) return (rhs & 1) ? -1 : 1; + if (rhs > 63) + { + overflow = true; + return 0; + } + + assert((b > 1 || b < -1) && rhs > 1); + return powImpl(b, cast(uint) rhs, overflow); +} + +// Inspiration: http://www.stepanovpapers.com/PAM.pdf +pure @safe nothrow @nogc +private T powImpl(T)(T b, uint e, ref bool overflow) +if (isIntegral!T && T.sizeof >= 4) +{ + assert(e > 1); + + import core.checkedint : muls, mulu; + static if (isUnsigned!T) alias mul = mulu; + else alias mul = muls; + + T r = b; + --e; + // Loop invariant: r * (b ^^ e) is the actual result + for (;; e /= 2) + { + if (e % 2) + { + r = mul(r, b, overflow); + if (e == 1) break; + } + b = mul(b, b, overflow); + } + return r; +} + +@safe unittest +{ + static void testPow(T)(T x, uint e) + { + bool overflow; + assert(opChecked!"^^"(T(0), 0, overflow) == 1); + assert(opChecked!"^^"(-2, T(0), overflow) == 1); + assert(opChecked!"^^"(-2, T(1), overflow) == -2); + assert(opChecked!"^^"(-1, -1, overflow) == -1); + assert(opChecked!"^^"(-2, 1, overflow) == -2); + assert(opChecked!"^^"(-2, -1, overflow) == 0); + assert(opChecked!"^^"(-2, 4u, overflow) == 16); + assert(!overflow); + assert(opChecked!"^^"(-2, 3u, overflow) == 0); + assert(overflow); + overflow = false; + assert(opChecked!"^^"(3, 64u, overflow) == 0); + assert(overflow); + overflow = false; + foreach (uint i; 0 .. e) + { + assert(opChecked!"^^"(x, i, overflow) == x ^^ i); + assert(!overflow); + } + assert(opChecked!"^^"(x, e, overflow) == x ^^ e); + assert(overflow); + } + + testPow!int(3, 21); + testPow!uint(3, 21); + testPow!long(3, 40); + testPow!ulong(3, 41); +} + +version (StdUnittest) private struct CountOverflows +{ + uint calls; + auto onOverflow(string op, Lhs)(Lhs lhs) + { + ++calls; + return mixin(op ~ "lhs"); + } + auto onOverflow(string op, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + ++calls; + return mixin("lhs" ~ op ~ "rhs"); + } + T onLowerBound(Rhs, T)(Rhs rhs, T) + { + ++calls; + return cast(T) rhs; + } + T onUpperBound(Rhs, T)(Rhs rhs, T) + { + ++calls; + return cast(T) rhs; + } +} + +// opBinary +@nogc nothrow pure @safe unittest +{ + static struct CountOpBinary + { + uint calls; + auto hookOpBinary(string op, Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + ++calls; + return mixin("lhs" ~ op ~ "rhs"); + } + } + auto x = Checked!(const int, void)(42), y = Checked!(immutable int, void)(142); + assert(x + y == 184); + assert(x + 100 == 142); + assert(y - x == 100); + assert(200 - x == 158); + assert(y * x == 142 * 42); + assert(x / 1 == 42); + assert(x % 20 == 2); + + auto x1 = Checked!(int, CountOverflows)(42); + assert(x1 + 0 == 42); + assert(x1 + false == 42); + assert(is(typeof(x1 + 0.5) == double)); + assert(x1 + 0.5 == 42.5); + assert(x1.hook.calls == 0); + assert(x1 + int.max == int.max + 42); + assert(x1.hook.calls == 1); + assert(x1 * 2 == 84); + assert(x1.hook.calls == 1); + assert(x1 / 2 == 21); + assert(x1.hook.calls == 1); + assert(x1 % 20 == 2); + assert(x1.hook.calls == 1); + assert(x1 << 2 == 42 << 2); + assert(x1.hook.calls == 1); + assert(x1 << 42 == x1.get << x1.get); + assert(x1.hook.calls == 2); + x1 = int.min; + assert(x1 - 1 == int.max); + assert(x1.hook.calls == 3); + + auto x2 = Checked!(int, CountOpBinary)(42); + assert(x2 + 1 == 43); + assert(x2.hook.calls == 1); + + auto x3 = Checked!(uint, CountOverflows)(42u); + assert(x3 + 1 == 43); + assert(x3.hook.calls == 0); + assert(x3 - 1 == 41); + assert(x3.hook.calls == 0); + assert(x3 + (-42) == 0); + assert(x3.hook.calls == 0); + assert(x3 - (-42) == 84); + assert(x3.hook.calls == 0); + assert(x3 * 2 == 84); + assert(x3.hook.calls == 0); + assert(x3 * -2 == -84); + assert(x3.hook.calls == 1); + assert(x3 / 2 == 21); + assert(x3.hook.calls == 1); + assert(x3 / -2 == 0); + assert(x3.hook.calls == 2); + assert(x3 ^^ 2 == 42 * 42); + assert(x3.hook.calls == 2); + + auto x4 = Checked!(int, CountOverflows)(42); + assert(x4 + 1 == 43); + assert(x4.hook.calls == 0); + assert(x4 + 1u == 43); + assert(x4.hook.calls == 0); + assert(x4 - 1 == 41); + assert(x4.hook.calls == 0); + assert(x4 * 2 == 84); + assert(x4.hook.calls == 0); + x4 = -2; + assert(x4 + 2u == 0); + assert(x4.hook.calls == 0); + assert(x4 * 2u == -4); + assert(x4.hook.calls == 1); + + auto x5 = Checked!(int, CountOverflows)(3); + assert(x5 ^^ 0 == 1); + assert(x5 ^^ 1 == 3); + assert(x5 ^^ 2 == 9); + assert(x5 ^^ 3 == 27); + assert(x5 ^^ 4 == 81); + assert(x5 ^^ 5 == 81 * 3); + assert(x5 ^^ 6 == 81 * 9); +} + +// opBinaryRight +@nogc nothrow pure @safe unittest +{ + auto x1 = Checked!(int, CountOverflows)(42); + assert(1 + x1 == 43); + assert(true + x1 == 43); + assert(0.5 + x1 == 42.5); + auto x2 = Checked!(int, void)(42); + assert(x1 + x2 == 84); + assert(x2 + x1 == 84); +} + +// opOpAssign +@safe unittest +{ + auto x1 = Checked!(int, CountOverflows)(3); + assert((x1 += 2) == 5); + x1 *= 2_000_000_000L; + assert(x1.hook.calls == 1); + x1 *= -2_000_000_000L; + assert(x1.hook.calls == 2); + + auto x2 = Checked!(ushort, CountOverflows)(ushort(3)); + assert((x2 += 2) == 5); + assert(x2.hook.calls == 0); + assert((x2 += ushort.max) == cast(ushort) (ushort(5) + ushort.max)); + assert(x2.hook.calls == 1); + + auto x3 = Checked!(uint, CountOverflows)(3u); + x3 *= ulong(2_000_000_000); + assert(x3.hook.calls == 1); +} + +// opAssign +@safe unittest +{ + Checked!(int, void) x; + x = 42; + assert(x.get == 42); + x = x; + assert(x.get == 42); + x = short(43); + assert(x.get == 43); + x = ushort(44); + assert(x.get == 44); +} + +@safe unittest +{ + static assert(!is(typeof(Checked!(short, void)(ushort(42))))); + static assert(!is(typeof(Checked!(int, void)(long(42))))); + static assert(!is(typeof(Checked!(int, void)(ulong(42))))); + assert(Checked!(short, void)(short(42)).get == 42); + assert(Checked!(int, void)(ushort(42)).get == 42); +} + +// opCast +@nogc nothrow pure @safe unittest +{ + static assert(is(typeof(cast(float) Checked!(int, void)(42)) == float)); + assert(cast(float) Checked!(int, void)(42) == 42); + + assert(is(typeof(cast(long) Checked!(int, void)(42)) == long)); + assert(cast(long) Checked!(int, void)(42) == 42); + static assert(is(typeof(cast(long) Checked!(uint, void)(42u)) == long)); + assert(cast(long) Checked!(uint, void)(42u) == 42); + + auto x = Checked!(int, void)(42); + if (x) {} else assert(0); + x = 0; + if (x) assert(0); + + static struct Hook1 + { + uint calls; + Dst hookOpCast(Dst, Src)(Src value) + { + ++calls; + return 42; + } + } + auto y = Checked!(long, Hook1)(long.max); + assert(cast(int) y == 42); + assert(cast(uint) y == 42); + assert(y.hook.calls == 2); + + static struct Hook2 + { + uint calls; + Dst onBadCast(Dst, Src)(Src value) + { + ++calls; + return 42; + } + } + auto x1 = Checked!(uint, Hook2)(100u); + assert(cast(ushort) x1 == 100); + assert(cast(short) x1 == 100); + assert(cast(float) x1 == 100); + assert(cast(double) x1 == 100); + assert(cast(real) x1 == 100); + assert(x1.hook.calls == 0); + assert(cast(int) x1 == 100); + assert(x1.hook.calls == 0); + x1 = uint.max; + assert(cast(int) x1 == 42); + assert(x1.hook.calls == 1); + + auto x2 = Checked!(int, Hook2)(-100); + assert(cast(short) x2 == -100); + assert(cast(ushort) x2 == 42); + assert(cast(uint) x2 == 42); + assert(cast(ulong) x2 == 42); + assert(x2.hook.calls == 3); +} + +// opEquals +@nogc nothrow pure @safe unittest +{ + assert(Checked!(int, void)(42) == 42L); + assert(42UL == Checked!(int, void)(42)); + + static struct Hook1 + { + uint calls; + bool hookOpEquals(Lhs, Rhs)(const Lhs lhs, const Rhs rhs) + { + ++calls; + return lhs != rhs; + } + } + auto x1 = Checked!(int, Hook1)(100); + assert(x1 != Checked!(long, Hook1)(100)); + assert(x1.hook.calls == 1); + assert(x1 != 100u); + assert(x1.hook.calls == 2); + + static struct Hook2 + { + uint calls; + bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + ++calls; + return false; + } + } + auto x2 = Checked!(int, Hook2)(-100); + assert(x2 != x1); + // For coverage: lhs has no hookOpEquals, rhs does + assert(Checked!(uint, void)(100u) != x2); + // For coverage: different types, neither has a hookOpEquals + assert(Checked!(uint, void)(100u) == Checked!(int, void*)(100)); + assert(x2.hook.calls == 0); + assert(x2 != -100); + assert(x2.hook.calls == 1); + assert(x2 != cast(uint) -100); + assert(x2.hook.calls == 2); + x2 = 100; + assert(x2 != cast(uint) 100); + assert(x2.hook.calls == 3); + x2 = -100; + + auto x3 = Checked!(uint, Hook2)(100u); + assert(x3 != 100); + x3 = uint.max; + assert(x3 != -1); + + assert(x2 != x3); +} + +// opCmp +@nogc nothrow pure @safe unittest +{ + Checked!(int, void) x; + assert(x <= x); + assert(x < 45); + assert(x < 45u); + assert(x > -45); + assert(x < 44.2); + assert(x > -44.2); + assert(!(x < double.init)); + assert(!(x > double.init)); + assert(!(x <= double.init)); + assert(!(x >= double.init)); + + static struct Hook1 + { + uint calls; + int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + ++calls; + return 0; + } + } + auto x1 = Checked!(int, Hook1)(42); + assert(!(x1 < 43u)); + assert(!(43u < x1)); + assert(x1.hook.calls == 2); + + static struct Hook2 + { + uint calls; + int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) + { + ++calls; + return ProperCompare.hookOpCmp(lhs, rhs); + } + } + auto x2 = Checked!(int, Hook2)(-42); + assert(x2 < 43u); + assert(43u > x2); + assert(x2.hook.calls == 2); + x2 = 42; + assert(x2 > 41u); + + auto x3 = Checked!(uint, Hook2)(42u); + assert(x3 > 41); + assert(x3 > -41); +} + +// opUnary +@nogc nothrow pure @safe unittest +{ + auto x = Checked!(int, void)(42); + assert(x == +x); + static assert(is(typeof(-x) == typeof(x))); + assert(-x == Checked!(int, void)(-42)); + static assert(is(typeof(~x) == typeof(x))); + assert(~x == Checked!(int, void)(~42)); + assert(++x == 43); + assert(--x == 42); + + static struct Hook1 + { + uint calls; + auto hookOpUnary(string op, T)(T value) if (op == "-") + { + ++calls; + return T(42); + } + auto hookOpUnary(string op, T)(T value) if (op == "~") + { + ++calls; + return T(43); + } + } + auto x1 = Checked!(int, Hook1)(100); + assert(is(typeof(-x1) == typeof(x1))); + assert(-x1 == Checked!(int, Hook1)(42)); + assert(is(typeof(~x1) == typeof(x1))); + assert(~x1 == Checked!(int, Hook1)(43)); + assert(x1.hook.calls == 2); + + static struct Hook2 + { + uint calls; + void hookOpUnary(string op, T)(ref T value) if (op == "++") + { + ++calls; + --value; + } + void hookOpUnary(string op, T)(ref T value) if (op == "--") + { + ++calls; + ++value; + } + } + auto x2 = Checked!(int, Hook2)(100); + assert(++x2 == 99); + assert(x2 == 99); + assert(--x2 == 100); + assert(x2 == 100); + + auto x3 = Checked!(int, CountOverflows)(int.max - 1); + assert(++x3 == int.max); + assert(x3.hook.calls == 0); + assert(++x3 == int.min); + assert(x3.hook.calls == 1); + assert(-x3 == int.min); + assert(x3.hook.calls == 2); + + x3 = int.min + 1; + assert(--x3 == int.min); + assert(x3.hook.calls == 2); + assert(--x3 == int.max); + assert(x3.hook.calls == 3); +} + +// +@nogc nothrow pure @safe unittest +{ + Checked!(int, void) x; + assert(x == x); + assert(x == +x); + assert(x == -x); + ++x; + assert(x == 1); + x++; + assert(x == 2); + + x = 42; + assert(x == 42); + const short _short = 43; + x = _short; + assert(x == _short); + ushort _ushort = 44; + x = _ushort; + assert(x == _ushort); + assert(x == 44.0); + assert(x != 44.1); + assert(x < 45); + assert(x < 44.2); + assert(x > -45); + assert(x > -44.2); + + assert(cast(long) x == 44); + assert(cast(short) x == 44); + + const Checked!(uint, void) y; + assert(y <= y); + assert(y == 0); + assert(y < x); + x = -1; + assert(x > y); +} + +@nogc nothrow pure @safe unittest +{ + alias cint = Checked!(int, void); + cint a = 1, b = 2; + a += b; + assert(a == cint(3)); + + alias ccint = Checked!(cint, Saturate); + ccint c = 14; + a += c; + assert(a == cint(17)); +} + +// toHash +@safe unittest +{ + assert(checked(42).toHash() == checked(42).toHash()); + assert(checked(12).toHash() != checked(19).toHash()); + + static struct Hook1 + { + static size_t hookToHash(T)(T payload) nothrow @trusted + { + static if (size_t.sizeof == 4) + { + return typeid(payload).getHash(&payload) ^ 0xFFFF_FFFF; + } + else + { + return typeid(payload).getHash(&payload) ^ 0xFFFF_FFFF_FFFF_FFFF; + } + + } + } + + auto a = checked!Hook1(78); + auto b = checked!Hook1(78); + assert(a.toHash() == b.toHash()); + + assert(checked!Hook1(12).toHash() != checked!Hook1(13).toHash()); + + static struct Hook2 + { + static if (size_t.sizeof == 4) + { + static size_t hashMask = 0xFFFF_0000; + } + else + { + static size_t hashMask = 0xFFFF_0000_FFFF_0000; + } + + static size_t hookToHash(T)(T payload) nothrow @trusted + { + return typeid(payload).getHash(&payload) ^ hashMask; + } + } + + auto x = checked!Hook2(1901); + auto y = checked!Hook2(1989); + + assert((() nothrow @safe => x.toHash() == x.toHash())()); + + assert(x.toHash() == x.toHash()); + assert(x.toHash() != y.toHash()); + assert(checked!Hook1(1901).toHash() != x.toHash()); + + immutable z = checked!Hook1(1901); + immutable t = checked!Hook1(1901); + immutable w = checked!Hook2(1901); + + assert(z.toHash() == t.toHash()); + assert(z.toHash() != x.toHash()); + assert(z.toHash() != w.toHash()); + + const long c = 0xF0F0F0F0; + const long d = 0xF0F0F0F0; + + assert(checked!Hook1(c).toHash() != checked!Hook2(c)); + assert(checked!Hook1(c).toHash() != checked!Hook1(d)); + + // Hook with state, does not implement hookToHash + static struct Hook3 + { + ulong var1 = ulong.max; + uint var2 = uint.max; + } + + assert(checked!Hook3(12).toHash() != checked!Hook3(13).toHash()); + assert(checked!Hook3(13).toHash() == checked!Hook3(13).toHash()); + + // Hook with no state and no hookToHash, payload has its own hashing function + auto x1 = Checked!(Checked!int, ProperCompare)(123); + auto x2 = Checked!(Checked!int, ProperCompare)(123); + auto x3 = Checked!(Checked!int, ProperCompare)(144); + + assert(x1.toHash() == x2.toHash()); + assert(x1.toHash() != x3.toHash()); + assert(x2.toHash() != x3.toHash()); + + // Check shared. + { + shared shared0 = checked(12345678); + shared shared1 = checked!Hook1(123456789); + shared shared2 = checked!Hook2(234567891); + shared shared3 = checked!Hook3(345678912); + assert(shared0.toHash() == hashOf(shared0)); + assert(shared1.toHash() == hashOf(shared1)); + assert(shared2.toHash() == hashOf(shared2)); + assert(shared3.toHash() == hashOf(shared3)); + } +} + +/// +@safe unittest +{ + struct MyHook + { + static size_t hookToHash(T)(const T payload) nothrow @trusted + { + return .hashOf(payload); + } + } + + int[Checked!(int, MyHook)] aa; + Checked!(int, MyHook) var = 42; + aa[var] = 100; + + assert(aa[var] == 100); + + int[Checked!(int, Abort)] bb; + Checked!(int, Abort) var2 = 42; + bb[var2] = 100; + + assert(bb[var2] == 100); +} diff --git a/libphobos/src/std/complex.d b/libphobos/src/std/complex.d index 756d1ca94bb..485b548b049 100644 --- a/libphobos/src/std/complex.d +++ b/libphobos/src/std/complex.d @@ -1015,6 +1015,14 @@ Complex!T tan(T)(Complex!T z) @safe pure nothrow @nogc @safe pure nothrow @nogc unittest { static import std.math; + + int ceqrel(T)(const Complex!T x, const Complex!T y) @safe pure nothrow @nogc + { + import std.math.operations : feqrel; + const r = feqrel(x.re, y.re); + const i = feqrel(x.im, y.im); + return r < i ? r : i; + } assert(ceqrel(tan(complex(1.0, 0.0)), complex(std.math.tan(1.0), 0.0)) >= double.mant_dig - 2); assert(ceqrel(tan(complex(0.0, 1.0)), complex(0.0, std.math.tanh(1.0))) >= double.mant_dig - 2); } @@ -1705,14 +1713,11 @@ Complex!T log10(T)(Complex!T x) @safe pure nothrow @nogc auto b = log10(complex(0.0, 1.0)) * 2.0; auto c = log10(complex(sqrt(2.0) / 2, sqrt(2.0) / 2)) * 4.0; assert(isClose(b, c, 0.0, 1e-15)); - - assert(ceqrel(log10(complex(-100.0L, 0.0L)), complex(2.0L, PI / LN10)) >= real.mant_dig - 1); - assert(ceqrel(log10(complex(-100.0L, -0.0L)), complex(2.0L, -PI / LN10)) >= real.mant_dig - 1); } @safe pure nothrow @nogc unittest { - import std.math.constants : PI; + import std.math.constants : LN10, PI; import std.math.operations : isClose; auto a = log10(fromPolar(1.0, PI / 6.0)); @@ -1732,6 +1737,9 @@ Complex!T log10(T)(Complex!T x) @safe pure nothrow @nogc auto f = log10(complex(-1.0L, 0.0L)); assert(isClose(f, complex(0.0L, 1.36437635384184134748L), 0.0, 1e-15)); + + assert(ceqrel(log10(complex(-100.0L, 0.0L)), complex(2.0L, PI / LN10)) >= real.mant_dig - 1); + assert(ceqrel(log10(complex(-100.0L, -0.0L)), complex(2.0L, -PI / LN10)) >= real.mant_dig - 1); } /** @@ -1771,9 +1779,6 @@ if (isIntegral!Int) assert(pow(a, 3) == a * a * a); assert(pow(a, -2) == 1.0 / (a * a)); assert(isClose(pow(a, -3), 1.0 / (a * a * a))); - - auto b = complex(2.0); - assert(ceqrel(pow(b, 3), exp(3 * log(b))) >= double.mant_dig - 1); } /// ditto @@ -1865,6 +1870,9 @@ Complex!T pow(T)(const T x, Complex!T n) @trusted pure nothrow @nogc auto d = pow(PI, complex(2.0, -1.0)); assert(ceqrel(d, complex(4.0790296880118296, -8.9872469554541869)) >= double.mant_dig - 1); + + auto e = complex(2.0); + assert(ceqrel(pow(e, 3), exp(3 * log(e))) >= double.mant_dig - 1); } @safe pure nothrow @nogc unittest diff --git a/libphobos/src/std/conv.d b/libphobos/src/std/conv.d index 98df7fd1ccf..a10f4da7f9c 100644 --- a/libphobos/src/std/conv.d +++ b/libphobos/src/std/conv.d @@ -50,9 +50,9 @@ module std.conv; public import std.ascii : LetterCase; import std.meta; -import std.range.primitives; +import std.range; import std.traits; -import std.typecons : Flag, Yes, No, tuple; +import std.typecons : Flag, Yes, No, tuple, isTuple; // Same as std.string.format, but "self-importing". // Helps reduce code and imports, particularly in static asserts. @@ -653,6 +653,32 @@ if (isImplicitlyConvertible!(S, T) && }} } +// https://issues.dlang.org/show_bug.cgi?id=13551 +private T toImpl(T, S)(S value) +if (isTuple!T) +{ + T t; + static foreach (i; 0 .. T.length) + { + t[i] = value[i].to!(typeof(T[i])); + } + return t; +} + +@safe unittest +{ + import std.typecons : Tuple; + + auto test = ["10", "20", "30"]; + assert(test.to!(Tuple!(int, int, int)) == Tuple!(int, int, int)(10, 20, 30)); + + auto test1 = [1, 2]; + assert(test1.to!(Tuple!(int, int)) == Tuple!(int, int)(1, 2)); + + auto test2 = [1.0, 2.0, 3.0]; + assert(test2.to!(Tuple!(int, int, int)) == Tuple!(int, int, int)(1, 2, 3)); +} + /* Converting static arrays forwards to their dynamic counterparts. */ @@ -1970,7 +1996,7 @@ if (isInputRange!S && isSomeChar!(ElementEncodingType!S) && /// ditto private T toImpl(T, S)(S value, uint radix) -if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S) && +if (isSomeFiniteCharInputRange!S && isIntegral!T && is(typeof(parse!T(value, radix)))) { scope(success) diff --git a/libphobos/src/std/experimental/allocator/package.d b/libphobos/src/std/experimental/allocator/package.d index 2804829abe4..62f848f11fc 100644 --- a/libphobos/src/std/experimental/allocator/package.d +++ b/libphobos/src/std/experimental/allocator/package.d @@ -3735,7 +3735,13 @@ unittest Ternary r = (() @nogc => a.resolveInternalPointer(&b[0], p))(); assert(&p[0] == &b[0] && p.length >= b.length); r = a.resolveInternalPointer((() @trusted => &b[0] + b.length)(), p); - assert(&p[0] == &b[0] && p.length >= b.length); + + /* This line randomly fails on MacOS 12.x x64 + * https://issues.dlang.org/show_bug.cgi?id=22660 + * Commenting it out until someone can fix it. + */ + //assert(&p[0] == &b[0] && p.length >= b.length); + r = a.resolveInternalPointer((() @trusted => &b[0] + b.length / 2)(), p); assert(&p[0] == &b[0] && p.length >= b.length); auto bogus = new void[b.length]; diff --git a/libphobos/src/std/experimental/checkedint.d b/libphobos/src/std/experimental/checkedint.d index 354851bfc84..9237341d418 100644 --- a/libphobos/src/std/experimental/checkedint.d +++ b/libphobos/src/std/experimental/checkedint.d @@ -1,3467 +1,14 @@ -// 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; - -/// -@safe 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.format.spec : FormatSpec; - import std.range.primitives : isInputRange, ElementType; - import std.traits : hasMember, isSomeChar; - - /** - 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); - /// - @safe 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; - } - /// - @safe 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. - */ - ref Checked opAssign(U)(U rhs) return - if (is(typeof(Checked!(T, Hook)(rhs)))) - { - static if (isIntegral!U) - payload = rhs; - else - payload = rhs.payload; - return this; - } - /// - @safe unittest - { - Checked!long a; - a = 42L; - assert(a == 42); - a = 4242; - assert(a == 4242); - } - - /// - @safe unittest - { - Checked!long a, b; - a = b = 3; - assert(a == 3 && b == 3); - } - - /** - Construct from a decimal string. The conversion follows the same rules as - $(REF to, std, conv) converting a string to the wrapped `T` type. - - Params: - str = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives) - of characters - */ - this(Range)(Range str) - if (isInputRange!Range && isSomeChar!(ElementType!Range)) - { - import std.conv : to; - - this(to!T(str)); - } - - /** - $(REF to, std, conv) can convert a string to a `Checked!T`: - */ - @system unittest - { - import std.conv : to; - - const a = to!long("1234"); - const b = to!(Checked!long)("1234"); - assert(a == b); - } - - // 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); - } - } - /// - @safe 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 - { - import std.traits : isUnsigned; - - 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); - } - } - - /// ditto - size_t toHash(this _)() shared const nothrow @safe - { - import core.atomic : atomicLoad, MemoryOrder; - static if (is(typeof(this.payload.atomicLoad!(MemoryOrder.acq)) P)) - { - auto payload = __ctfe ? cast(P) this.payload - : this.payload.atomicLoad!(MemoryOrder.acq); - } - else - { - alias payload = this.payload; - } - - 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); - } - } - - /** - Writes a string representation of this to a `sink`. - - Params: - sink = A `Char` accepting - $(REF_ALTTEXT output range, isOutputRange, std,range,primitives). - fmt = A $(REF FormatSpec, std, format) which controls how this - is formatted. - */ - void toString(Writer, Char)(scope ref Writer sink, scope const ref FormatSpec!Char fmt) const - { - import std.format.write : formatValue; - if (fmt.spec == 's') - return formatValue(sink, this, fmt); - else - return formatValue(sink, payload, fmt); - } - - /** - `toString` is rarely directly invoked; the usual way of using it is via - $(REF format, std, format): - */ - @system unittest - { - import std.format; - - assert(format("%04d", checked(15)) == "0015"); - assert(format("0x%02x", checked(15)) == "0x0f"); - } - - // 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 - { - import std.traits : isUnsigned; - - 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)) @safe 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)) @safe 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(lhs, payload); - 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)) @safe 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 - if (isIntegral!Rhs || isFloatingPoint!Rhs || is(Rhs == bool)) - { - static assert(is(typeof(mixin("payload" ~ op ~ "=rhs")) == T)); - - static if (hasMember!(Hook, "hookOpOpAssign")) - { - hook.hookOpOpAssign!op(payload, rhs); - } - else - { - alias R = typeof(get + rhs); - auto r = opBinary!op(rhs).get; - import std.conv : unsigned; - - static if (ProperCompare.hookOpCmp(R.min, min.get) < 0 && - hasMember!(Hook, "onLowerBound")) - { - if (ProperCompare.hookOpCmp(r, min.get) < 0) - { - // Example: Checked!uint(1) += int(-3) - payload = hook.onLowerBound(r, min.get); - return this; - } - } - static if (ProperCompare.hookOpCmp(max.get, R.max) < 0 && - hasMember!(Hook, "onUpperBound")) - { - if (ProperCompare.hookOpCmp(r, max.get) > 0) - { - // Example: Checked!uint(1) += long(uint.max) - payload = hook.onUpperBound(r, max.get); - return this; - } - } - payload = cast(T) r; - } - return this; - } - - /// ditto - ref Checked opOpAssign(string op, Rhs)(const Rhs rhs) return - if (is(Rhs == Checked!(RhsT, RhsHook), RhsT, RhsHook)) - { - return opOpAssign!(op, typeof(rhs.payload))(rhs.payload); - } - - /// - static if (is(T == int) && is(Hook == void)) @safe unittest - { - static struct MyHook - { - static bool thereWereErrors; - static T onLowerBound(Rhs, T)(Rhs rhs, T bound) - { - thereWereErrors = true; - return bound; - } - static T onUpperBound(Rhs, T)(Rhs rhs, T bound) - { - thereWereErrors = true; - return bound; - } - } - auto x = checked!MyHook(byte.min); - x -= 1; - assert(MyHook.thereWereErrors); - MyHook.thereWereErrors = false; - x = byte.max; - x += 1; - assert(MyHook.thereWereErrors); - } -} - -/** - -Convenience function that turns an integral into the corresponding `Checked` -instance by using template argument deduction. The hook type may be specified -(by default `Abort`). - -*/ -Checked!(T, Hook) checked(Hook = Abort, T)(const T value) -if (is(typeof(Checked!(T, Hook)(value)))) -{ - return Checked!(T, Hook)(value); -} - -/// -@safe unittest -{ - static assert(is(typeof(checked(42)) == Checked!int)); - assert(checked(42) == Checked!int(42)); - static assert(is(typeof(checked!WithNaN(42)) == Checked!(int, WithNaN))); - assert(checked!WithNaN(42) == Checked!(int, WithNaN)(42)); -} - -// get -@safe unittest -{ - void test(T)() - { - assert(Checked!(T, void)(ubyte(22)).get == 22); - } - test!ubyte; - test!(const ubyte); - test!(immutable ubyte); -} - -@system unittest -{ - // https://issues.dlang.org/show_bug.cgi?id=21758 - assert(4 * checked(5L) == 20); - assert(20 / checked(5L) == 4); - assert(2 ^^ checked(3L) == 8); - assert(12 % checked(5L) == 2); - assert((0xff & checked(3L)) == 3); - assert((0xf0 | checked(3L)) == 0xf3); - assert((0xff ^ checked(3L)) == 0xfc); -} - -// Abort -/** - -Force all integral errors to fail by printing an error message to `stderr` and -then abort the program. `Abort` is the default second argument for `Checked`. - -*/ -struct Abort -{ -static: - /** - - Called automatically upon a bad cast (one that loses precision or attempts - to convert a negative value to an unsigned type). The source type is `Src` - and the destination type is `Dst`. - - Params: - src = The source of the cast - - Returns: Nominally the result is the desired value of the cast operation, - which will be forwarded as the result of the cast. For `Abort`, the - function never returns because it aborts the program. - - */ - Dst onBadCast(Dst, Src)(Src src) - { - Warn.onBadCast!Dst(src); - assert(0); - } - - /** - - Called automatically upon a bounds error. - - Params: - rhs = The right-hand side value in the assignment, after the operator has - been evaluated - bound = The value of the bound being violated - - Returns: Nominally the result is the desired value of the operator, which - will be forwarded as result. For `Abort`, the function never returns because - it aborts the program. - - */ - T onLowerBound(Rhs, T)(Rhs rhs, T bound) - { - Warn.onLowerBound(rhs, bound); - assert(0); - } - /// ditto - T onUpperBound(Rhs, T)(Rhs rhs, T bound) - { - Warn.onUpperBound(rhs, bound); - assert(0); - } - - /** - - Called automatically upon a comparison for equality. In case of a erroneous - comparison (one that would make a signed negative value appear equal to an - unsigned positive value), this hook issues `assert(0)` which terminates the - application. - - Params: - lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - rhs = The right-hand side type involved in the operator - - Returns: Upon a correct comparison, returns the result of the comparison. - Otherwise, the function terminates the application so it never returns. - - */ - static bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - bool error; - auto result = opChecked!"=="(lhs, rhs, error); - if (error) - { - Warn.hookOpEquals(lhs, rhs); - assert(0); - } - return result; - } - - /** - - Called automatically upon a comparison for ordering using one of the - operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. - it would make a signed negative value appear greater than or equal to an - unsigned positive value), then application is terminated with `assert(0)`. - Otherwise, the three-state result is returned (positive if $(D lhs > rhs), - negative if $(D lhs < rhs), `0` otherwise). - - Params: - lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - rhs = The right-hand side type involved in the operator - - Returns: For correct comparisons, returns a positive integer if $(D lhs > - rhs), a negative integer if $(D lhs < rhs), `0` if the two are equal. Upon - a mistaken comparison such as $(D int(-1) < uint(0)), the function never - returns because it aborts the program. - - */ - int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - bool error; - auto result = opChecked!"cmp"(lhs, rhs, error); - if (error) - { - Warn.hookOpCmp(lhs, rhs); - assert(0); - } - return result; - } - - /** - - Called automatically upon an overflow during a unary or binary operation. - - Params: - x = The operator, e.g. `-` - lhs = The left-hand side (or sole) argument - rhs = The right-hand side type involved in the operator - - Returns: Nominally the result is the desired value of the operator, which - will be forwarded as result. For `Abort`, the function never returns because - it aborts the program. - - */ - typeof(~Lhs()) onOverflow(string x, Lhs)(Lhs lhs) - { - Warn.onOverflow!x(lhs); - assert(0); - } - /// ditto - typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - Warn.onOverflow!x(lhs, rhs); - assert(0); - } -} - -@safe unittest -{ - void test(T)() - { - Checked!(int, Abort) x; - x = 42; - auto x1 = cast(T) x; - assert(x1 == 42); - //x1 += long(int.max); - } - test!short; - test!(const short); - test!(immutable short); -} - - -// Throw -/** - -Force all integral errors to fail by throwing an exception of type -`Throw.CheckFailure`. The message coming with the error is similar to the one -printed by `Warn`. - -*/ -struct Throw -{ - /** - Exception type thrown upon any failure. - */ - static class CheckFailure : Exception - { - this(T...)(string f, T vals) - { - import std.format : format; - super(format(f, vals)); - } - } - - /** - - Called automatically upon a bad cast (one that loses precision or attempts - to convert a negative value to an unsigned type). The source type is `Src` - and the destination type is `Dst`. - - Params: - src = The source of the cast - - Returns: Nominally the result is the desired value of the cast operation, - which will be forwarded as the result of the cast. For `Throw`, the - function never returns because it throws an exception. - - */ - static Dst onBadCast(Dst, Src)(Src src) - { - throw new CheckFailure("Erroneous cast: cast(%s) %s(%s)", - Dst.stringof, Src.stringof, src); - } - - /** - - Called automatically upon a bounds error. - - Params: - rhs = The right-hand side value in the assignment, after the operator has - been evaluated - bound = The value of the bound being violated - - Returns: Nominally the result is the desired value of the operator, which - will be forwarded as result. For `Throw`, the function never returns because - it throws. - - */ - static T onLowerBound(Rhs, T)(Rhs rhs, T bound) - { - throw new CheckFailure("Lower bound error: %s(%s) < %s(%s)", - Rhs.stringof, rhs, T.stringof, bound); - } - /// ditto - static T onUpperBound(Rhs, T)(Rhs rhs, T bound) - { - throw new CheckFailure("Upper bound error: %s(%s) > %s(%s)", - Rhs.stringof, rhs, T.stringof, bound); - } - - /** - - Called automatically upon a comparison for equality. Throws upon an - erroneous comparison (one that would make a signed negative value appear - equal to an unsigned positive value). - - Params: - lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - rhs = The right-hand side type involved in the operator - - Returns: The result of the comparison. - - Throws: `CheckFailure` if the comparison is mathematically erroneous. - - */ - static bool hookOpEquals(L, R)(L lhs, R rhs) - { - bool error; - auto result = opChecked!"=="(lhs, rhs, error); - if (error) - { - throw new CheckFailure("Erroneous comparison: %s(%s) == %s(%s)", - L.stringof, lhs, R.stringof, rhs); - } - return result; - } - - /** - - Called automatically upon a comparison for ordering using one of the - operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. - it would make a signed negative value appear greater than or equal to an - unsigned positive value), throws a `Throw.CheckFailure` exception. - Otherwise, the three-state result is returned (positive if $(D lhs > rhs), - negative if $(D lhs < rhs), `0` otherwise). - - Params: - lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - rhs = The right-hand side type involved in the operator - - Returns: For correct comparisons, returns a positive integer if $(D lhs > - rhs), a negative integer if $(D lhs < rhs), `0` if the two are equal. - - Throws: Upon a mistaken comparison such as $(D int(-1) < uint(0)), the - function never returns because it throws a `Throw.CheckedFailure` exception. - - */ - static int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - bool error; - auto result = opChecked!"cmp"(lhs, rhs, error); - if (error) - { - throw new CheckFailure("Erroneous ordering comparison: %s(%s) and %s(%s)", - Lhs.stringof, lhs, Rhs.stringof, rhs); - } - return result; - } - - /** - - Called automatically upon an overflow during a unary or binary operation. - - Params: - x = The operator, e.g. `-` - lhs = The left-hand side (or sole) argument - rhs = The right-hand side type involved in the operator - - Returns: Nominally the result is the desired value of the operator, which - will be forwarded as result. For `Throw`, the function never returns because - it throws an exception. - - */ - static typeof(~Lhs()) onOverflow(string x, Lhs)(Lhs lhs) - { - throw new CheckFailure("Overflow on unary operator: %s%s(%s)", - x, Lhs.stringof, lhs); - } - /// ditto - static typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - throw new CheckFailure("Overflow on binary operator: %s(%s) %s %s(%s)", - Lhs.stringof, lhs, x, Rhs.stringof, rhs); - } -} - -/// -@safe unittest -{ - void test(T)() - { - Checked!(int, Throw) x; - x = 42; - auto x1 = cast(T) x; - assert(x1 == 42); - x = T.max + 1; - import std.exception : assertThrown, assertNotThrown; - assertThrown(cast(T) x); - x = x.max; - assertThrown(x += 42); - assertThrown(x += 42L); - x = x.min; - assertThrown(-x); - assertThrown(x -= 42); - assertThrown(x -= 42L); - x = -1; - assertNotThrown(x == -1); - assertThrown(x == uint(-1)); - assertNotThrown(x <= -1); - assertThrown(x <= uint(-1)); - } - test!short; - test!(const short); - test!(immutable short); -} - -// Warn -/** -Hook that prints to `stderr` a trace of all integral errors, without affecting -default behavior. -*/ -struct Warn -{ - import std.stdio : writefln; -static: - /** - - Called automatically upon a bad cast from `src` to type `Dst` (one that - loses precision or attempts to convert a negative value to an unsigned - type). - - Params: - src = The source of the cast - Dst = The target type of the cast - - Returns: `cast(Dst) src` - - */ - Dst onBadCast(Dst, Src)(Src src) - { - trustedStderr.writefln("Erroneous cast: cast(%s) %s(%s)", - Dst.stringof, Src.stringof, src); - return cast(Dst) src; - } - - /** - - Called automatically upon a bad `opOpAssign` call (one that loses precision - or attempts to convert a negative value to an unsigned type). - - Params: - rhs = The right-hand side value in the assignment, after the operator has - been evaluated - bound = The bound being violated - - Returns: `cast(T) rhs` - */ - T onLowerBound(Rhs, T)(Rhs rhs, T bound) - { - trustedStderr.writefln("Lower bound error: %s(%s) < %s(%s)", - Rhs.stringof, rhs, T.stringof, bound); - return cast(T) rhs; - } - /// ditto - T onUpperBound(Rhs, T)(Rhs rhs, T bound) - { - trustedStderr.writefln("Upper bound error: %s(%s) > %s(%s)", - Rhs.stringof, rhs, T.stringof, bound); - return cast(T) rhs; - } - - /** - - Called automatically upon a comparison for equality. In case of an Erroneous - comparison (one that would make a signed negative value appear equal to an - unsigned positive value), writes a warning message to `stderr` as a side - effect. - - Params: - lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - rhs = The right-hand side type involved in the operator - - Returns: In all cases the function returns the built-in result of $(D lhs == - rhs). - - */ - bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - bool error; - auto result = opChecked!"=="(lhs, rhs, error); - if (error) - { - trustedStderr.writefln("Erroneous comparison: %s(%s) == %s(%s)", - Lhs.stringof, lhs, Rhs.stringof, rhs); - return lhs == rhs; - } - return result; - } - - /// - @safe unittest - { - auto x = checked!Warn(-42); - // Passes - assert(x == -42); - // Passes but prints a warning - // assert(x == uint(-42)); - } - - /** - - Called automatically upon a comparison for ordering using one of the - operators `<`, `<=`, `>`, or `>=`. In case the comparison is erroneous (i.e. - it would make a signed negative value appear greater than or equal to an - unsigned positive value), then a warning message is printed to `stderr`. - - Params: - lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - rhs = The right-hand side type involved in the operator - - Returns: In all cases, returns $(D lhs < rhs ? -1 : lhs > rhs). The result - is not autocorrected in case of an erroneous comparison. - - */ - int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - bool error; - auto result = opChecked!"cmp"(lhs, rhs, error); - if (error) - { - trustedStderr.writefln("Erroneous ordering comparison: %s(%s) and %s(%s)", - Lhs.stringof, lhs, Rhs.stringof, rhs); - return lhs < rhs ? -1 : lhs > rhs; - } - return result; - } - - /// - @safe unittest - { - auto x = checked!Warn(-42); - // Passes - assert(x <= -42); - // Passes but prints a warning - // assert(x <= uint(-42)); - } - - /** - - Called automatically upon an overflow during a unary or binary operation. - - Params: - x = The operator involved - Lhs = The first argument of `Checked`, e.g. `int` if the left-hand side of - the operator is `Checked!int` - Rhs = The right-hand side type involved in the operator - - Returns: $(D mixin(x ~ "lhs")) for unary, $(D mixin("lhs" ~ x ~ "rhs")) for - binary - - */ - typeof(~Lhs()) onOverflow(string x, Lhs)(ref Lhs lhs) - { - trustedStderr.writefln("Overflow on unary operator: %s%s(%s)", - x, Lhs.stringof, lhs); - return mixin(x ~ "lhs"); - } - /// ditto - typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - trustedStderr.writefln("Overflow on binary operator: %s(%s) %s %s(%s)", - Lhs.stringof, lhs, x, Rhs.stringof, rhs); - static if (x == "/") // Issue 20743: mixin below would cause SIGFPE on POSIX - return typeof(lhs / rhs).min; // or EXCEPTION_INT_OVERFLOW on Windows - else - return mixin("lhs" ~ x ~ "rhs"); - } - - // This is safe because we do not assign to the reference returned by - // `stderr`. The ability for the caller to do that is why `stderr` is not - // safe in the general case. - private @property auto ref trustedStderr() @trusted - { - import std.stdio : stderr; - - return stderr; - } -} - -/// -@safe unittest -{ - auto x = checked!Warn(42); - short x1 = cast(short) x; - //x += long(int.max); - auto y = checked!Warn(cast(const int) 42); - short y1 = cast(const byte) y; -} - -@system unittest -{ - auto a = checked!Warn(int.min); - auto b = checked!Warn(-1); - auto x = checked!Abort(int.min); - auto y = checked!Abort(-1); - - // Temporarily redirect output to stderr to make sure we get the right output. - import std.file : exists, remove; - import std.process : uniqueTempPath; - import std.stdio : stderr; - auto tmpname = uniqueTempPath; - scope(exit) if (exists(tmpname)) remove(tmpname); - auto t = stderr; - stderr.open(tmpname, "w"); - // Open a new scope to minimize code ran with stderr redirected. - { - scope(exit) stderr = t; - assert(a / b == a * b); - import std.exception : assertThrown; - import core.exception : AssertError; - assertThrown!AssertError(x / y); - } - import std.file : readText; - import std.ascii : newline; - auto witness = readText(tmpname); - auto expected = -"Overflow on binary operator: int(-2147483648) / const(int)(-1)" ~ newline ~ -"Overflow on binary operator: int(-2147483648) * const(int)(-1)" ~ newline ~ -"Overflow on binary operator: int(-2147483648) / const(int)(-1)" ~ newline; - assert(witness == expected, "'" ~ witness ~ "'"); -} - -// https://issues.dlang.org/show_bug.cgi?id=22249 -@safe unittest -{ - alias _ = Warn.onLowerBound!(int, int); -} - -// ProperCompare -/** - -Hook that provides arithmetically correct comparisons for equality and ordering. -Comparing an object of type $(D Checked!(X, ProperCompare)) against another -integral (for equality or ordering) ensures that no surprising conversions from -signed to unsigned integral occur before the comparison. Using $(D Checked!(X, -ProperCompare)) on either side of a comparison for equality against a -floating-point number makes sure the integral can be properly converted to the -floating point type, thus making sure equality is transitive. - -*/ -struct ProperCompare -{ - /** - Hook for `==` and `!=` that ensures comparison against integral values has - the behavior expected by the usual arithmetic rules. The built-in semantics - yield surprising behavior when comparing signed values against unsigned - values for equality, for example $(D uint.max == -1) or $(D -1_294_967_296 == - 3_000_000_000u). The call $(D hookOpEquals(x, y)) returns `true` if and only - if `x` and `y` represent the same arithmetic number. - - If one of the numbers is an integral and the other is a floating-point - number, $(D hookOpEquals(x, y)) returns `true` if and only if the integral - can be converted exactly (without approximation) to the floating-point - number. This is in order to preserve transitivity of equality: if $(D - hookOpEquals(x, y)) and $(D hookOpEquals(y, z)) then $(D hookOpEquals(y, - z)), in case `x`, `y`, and `z` are a mix of integral and floating-point - numbers. - - Params: - lhs = The left-hand side of the comparison for equality - rhs = The right-hand side of the comparison for equality - - Returns: - The result of the comparison, `true` if the values are equal - */ - static bool hookOpEquals(L, R)(L lhs, R rhs) - { - alias C = typeof(lhs + rhs); - static if (isFloatingPoint!C) - { - static if (!isFloatingPoint!L) - { - return hookOpEquals(rhs, lhs); - } - else static if (!isFloatingPoint!R) - { - static assert(isFloatingPoint!L && !isFloatingPoint!R); - auto rhs1 = C(rhs); - return lhs == rhs1 && cast(R) rhs1 == rhs; - } - else - return lhs == rhs; - } - else - { - bool error; - auto result = opChecked!"=="(lhs, rhs, error); - if (error) - { - // Only possible error is a wrong "true" - return false; - } - return result; - } - } - - /** - Hook for `<`, `<=`, `>`, and `>=` that ensures comparison against integral - values has the behavior expected by the usual arithmetic rules. The built-in - semantics yield surprising behavior when comparing signed values against - unsigned values, for example $(D 0u < -1). The call $(D hookOpCmp(x, y)) - returns `-1` if and only if `x` is smaller than `y` in abstract arithmetic - sense. - - If one of the numbers is an integral and the other is a floating-point - number, $(D hookOpEquals(x, y)) returns a floating-point number that is `-1` - if `x < y`, `0` if `x == y`, `1` if `x > y`, and `NaN` if the floating-point - number is `NaN`. - - Params: - lhs = The left-hand side of the comparison for ordering - rhs = The right-hand side of the comparison for ordering - - Returns: - The result of the comparison (negative if $(D lhs < rhs), positive if $(D - lhs > rhs), `0` if the values are equal) - */ - static auto hookOpCmp(L, R)(L lhs, R rhs) - { - alias C = typeof(lhs + rhs); - static if (isFloatingPoint!C) - { - return lhs < rhs - ? C(-1) - : lhs > rhs ? C(1) : lhs == rhs ? C(0) : C.init; - } - else - { - static if (!valueConvertible!(L, C) || !valueConvertible!(R, C)) - { - static assert(isUnsigned!C); - static assert(isUnsigned!L != isUnsigned!R); - if (!isUnsigned!L && lhs < 0) - return -1; - if (!isUnsigned!R && rhs < 0) - return 1; - } - return lhs < rhs ? -1 : lhs > rhs; - } - } -} - -/// -@safe unittest -{ - alias opEqualsProper = ProperCompare.hookOpEquals; - assert(opEqualsProper(42, 42)); - assert(opEqualsProper(42.0, 42.0)); - assert(opEqualsProper(42u, 42)); - assert(opEqualsProper(42, 42u)); - assert(-1 == 4294967295u); - assert(!opEqualsProper(-1, 4294967295u)); - assert(!opEqualsProper(const uint(-1), -1)); - assert(!opEqualsProper(uint(-1), -1.0)); - assert(3_000_000_000U == -1_294_967_296); - assert(!opEqualsProper(3_000_000_000U, -1_294_967_296)); -} - -@safe unittest -{ - alias opCmpProper = ProperCompare.hookOpCmp; - assert(opCmpProper(42, 42) == 0); - assert(opCmpProper(42, 42.0) == 0); - assert(opCmpProper(41, 42.0) < 0); - assert(opCmpProper(42, 41.0) > 0); - import std.math.traits : isNaN; - assert(isNaN(opCmpProper(41, double.init))); - assert(opCmpProper(42u, 42) == 0); - assert(opCmpProper(42, 42u) == 0); - assert(opCmpProper(-1, uint(-1)) < 0); - assert(opCmpProper(uint(-1), -1) > 0); - assert(opCmpProper(-1.0, -1) == 0); -} - -@safe unittest -{ - auto x1 = Checked!(uint, ProperCompare)(42u); - assert(x1.get < -1); - assert(x1 > -1); -} - -// WithNaN -/** - -Hook that reserves a special value as a "Not a Number" representative. For -signed integrals, the reserved value is `T.min`. For signed integrals, the -reserved value is `T.max`. - -The default value of a $(D Checked!(X, WithNaN)) is its NaN value, so care must -be taken that all variables are explicitly initialized. Any arithmetic and logic -operation involving at least on NaN becomes NaN itself. All of $(D a == b), $(D -a < b), $(D a > b), $(D a <= b), $(D a >= b) yield `false` if at least one of -`a` and `b` is NaN. - -*/ -struct WithNaN -{ -static: - /** - The default value used for values not explicitly initialized. It is the NaN - value, i.e. `T.min` for signed integrals and `T.max` for unsigned integrals. - */ - enum T defaultValue(T) = T.min == 0 ? T.max : T.min; - /** - The maximum value representable is `T.max` for signed integrals, $(D - T.max - 1) for unsigned integrals. The minimum value representable is $(D - T.min + 1) for signed integrals, `0` for unsigned integrals. - */ - enum T max(T) = cast(T) (T.min == 0 ? T.max - 1 : T.max); - /// ditto - enum T min(T) = cast(T) (T.min == 0 ? T(0) : T.min + 1); - - /** - If `rhs` is `WithNaN.defaultValue!Rhs`, returns - `WithNaN.defaultValue!Lhs`. Otherwise, returns $(D cast(Lhs) rhs). - - Params: - rhs = the value being cast (`Rhs` is the first argument to `Checked`) - Lhs = the target type of the cast - - Returns: The result of the cast operation. - */ - Lhs hookOpCast(Lhs, Rhs)(Rhs rhs) - { - static if (is(Lhs == bool)) - { - return rhs != defaultValue!Rhs && rhs != 0; - } - else static if (valueConvertible!(Rhs, Lhs)) - { - return rhs != defaultValue!Rhs ? Lhs(rhs) : defaultValue!Lhs; - } - else - { - // Not value convertible, only viable option is rhs fits within the - // bounds of Lhs - static if (ProperCompare.hookOpCmp(Rhs.min, Lhs.min) < 0) - { - // Example: hookOpCast!short(int(42)), hookOpCast!uint(int(42)) - if (ProperCompare.hookOpCmp(rhs, Lhs.min) < 0) - return defaultValue!Lhs; - } - static if (ProperCompare.hookOpCmp(Rhs.max, Lhs.max) > 0) - { - // Example: hookOpCast!int(uint(42)) - if (ProperCompare.hookOpCmp(rhs, Lhs.max) > 0) - return defaultValue!Lhs; - } - return cast(Lhs) rhs; - } - } - - /// - @safe unittest - { - auto x = checked!WithNaN(422); - assert((cast(ubyte) x) == 255); - x = checked!WithNaN(-422); - assert((cast(byte) x) == -128); - assert(cast(short) x == -422); - assert(cast(bool) x); - x = x.init; // set back to NaN - assert(x != true); - assert(x != false); - } - - /** - - Returns `false` if $(D lhs == WithNaN.defaultValue!Lhs), $(D lhs == rhs) - otherwise. - - Params: - lhs = The left-hand side of the comparison (`Lhs` is the first argument to - `Checked`) - rhs = The right-hand side of the comparison - - Returns: `lhs != WithNaN.defaultValue!Lhs && lhs == rhs` - */ - bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - return lhs != defaultValue!Lhs && lhs == rhs; - } - - /** - - If $(D lhs == WithNaN.defaultValue!Lhs), returns `double.init`. Otherwise, - has the same semantics as the default comparison. - - Params: - lhs = The left-hand side of the comparison (`Lhs` is the first argument to - `Checked`) - rhs = The right-hand side of the comparison - - Returns: `double.init` if `lhs == WitnNaN.defaultValue!Lhs`, `-1.0` if $(D - lhs < rhs), `0.0` if $(D lhs == rhs), `1.0` if $(D lhs > rhs). - - */ - double hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - if (lhs == defaultValue!Lhs) return double.init; - return lhs < rhs - ? -1.0 - : lhs > rhs ? 1.0 : lhs == rhs ? 0.0 : double.init; - } - - /// - @safe unittest - { - Checked!(int, WithNaN) x; - assert(!(x < 0) && !(x > 0) && !(x == 0)); - x = 1; - assert(x > 0 && !(x < 0) && !(x == 0)); - } - - /** - Defines hooks for unary operators `-`, `~`, `++`, and `--`. - - For `-` and `~`, if $(D v == WithNaN.defaultValue!T), returns - `WithNaN.defaultValue!T`. Otherwise, the semantics is the same as for the - built-in operator. - - For `++` and `--`, if $(D v == WithNaN.defaultValue!Lhs) or the operation - would result in an overflow, sets `v` to `WithNaN.defaultValue!T`. - Otherwise, the semantics is the same as for the built-in operator. - - Params: - x = The operator symbol - v = The left-hand side of the comparison (`T` is the first argument to - `Checked`) - - Returns: $(UL $(LI For $(D x == "-" || x == "~"): If $(D v == - WithNaN.defaultValue!T), the function returns `WithNaN.defaultValue!T`. - Otherwise it returns the normal result of the operator.) $(LI For $(D x == - "++" || x == "--"): The function returns `void`.)) - - */ - auto hookOpUnary(string x, T)(ref T v) - { - static if (x == "-" || x == "~") - { - return v != defaultValue!T ? mixin(x ~ "v") : v; - } - else static if (x == "++") - { - static if (defaultValue!T == T.min) - { - if (v != defaultValue!T) - { - if (v == T.max) v = defaultValue!T; - else ++v; - } - } - else - { - static assert(defaultValue!T == T.max); - if (v != defaultValue!T) ++v; - } - } - else static if (x == "--") - { - if (v != defaultValue!T) --v; - } - } - - /// - @safe unittest - { - Checked!(int, WithNaN) x; - ++x; - assert(x.isNaN); - x = 1; - assert(!x.isNaN); - x = -x; - ++x; - assert(!x.isNaN); - } - - @safe unittest // for coverage - { - Checked!(uint, WithNaN) y; - ++y; - assert(y.isNaN); - } - - /** - Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, - `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the - left-hand side operand. If $(D lhs == WithNaN.defaultValue!Lhs), returns - $(D WithNaN.defaultValue!(typeof(lhs + rhs))) without evaluating the - operand. Otherwise, evaluates the operand. If evaluation does not overflow, - returns the result. Otherwise, returns $(D WithNaN.defaultValue!(typeof(lhs + - rhs))). - - Params: - x = The operator symbol - lhs = The left-hand side operand (`Lhs` is the first argument to `Checked`) - rhs = The right-hand side operand - - Returns: If $(D lhs != WithNaN.defaultValue!Lhs) and the operator does not - overflow, the function returns the same result as the built-in operator. In - all other cases, returns $(D WithNaN.defaultValue!(typeof(lhs + rhs))). - */ - auto hookOpBinary(string x, L, R)(L lhs, R rhs) - { - alias Result = typeof(lhs + rhs); - if (lhs != defaultValue!L) - { - bool error; - auto result = opChecked!x(lhs, rhs, error); - if (!error) return result; - } - return defaultValue!Result; - } - - /// - @safe unittest - { - Checked!(int, WithNaN) x; - assert((x + 1).isNaN); - x = 100; - assert(!(x + 1).isNaN); - } - - /** - Defines hooks for binary operators `+`, `-`, `*`, `/`, `%`, `^^`, `&`, `|`, - `^`, `<<`, `>>`, and `>>>` for cases where a `Checked` object is the - right-hand side operand. If $(D rhs == WithNaN.defaultValue!Rhs), returns - $(D WithNaN.defaultValue!(typeof(lhs + rhs))) without evaluating the - operand. Otherwise, evaluates the operand. If evaluation does not overflow, - returns the result. Otherwise, returns $(D WithNaN.defaultValue!(typeof(lhs + - rhs))). - - Params: - x = The operator symbol - lhs = The left-hand side operand - rhs = The right-hand side operand (`Rhs` is the first argument to `Checked`) - - Returns: If $(D rhs != WithNaN.defaultValue!Rhs) and the operator does not - overflow, the function returns the same result as the built-in operator. In - all other cases, returns $(D WithNaN.defaultValue!(typeof(lhs + rhs))). - */ - auto hookOpBinaryRight(string x, L, R)(L lhs, R rhs) - { - alias Result = typeof(lhs + rhs); - if (rhs != defaultValue!R) - { - bool error; - auto result = opChecked!x(lhs, rhs, error); - if (!error) return result; - } - return defaultValue!Result; - } - /// - @safe unittest - { - Checked!(int, WithNaN) x; - assert((1 + x).isNaN); - x = 100; - assert(!(1 + x).isNaN); - } - - /** - - Defines hooks for binary operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, - `&=`, `|=`, `^=`, `<<=`, `>>=`, and `>>>=` for cases where a `Checked` - object is the left-hand side operand. If $(D lhs == - WithNaN.defaultValue!Lhs), no action is carried. Otherwise, evaluates the - operand. If evaluation does not overflow and fits in `Lhs` without loss of - information or change of sign, sets `lhs` to the result. Otherwise, sets - `lhs` to `WithNaN.defaultValue!Lhs`. - - Params: - x = The operator symbol (without the `=`) - lhs = The left-hand side operand (`Lhs` is the first argument to `Checked`) - rhs = The right-hand side operand - - Returns: `void` - */ - void hookOpOpAssign(string x, L, R)(ref L lhs, R rhs) - { - if (lhs == defaultValue!L) - return; - bool error; - auto temp = opChecked!x(lhs, rhs, error); - lhs = error - ? defaultValue!L - : hookOpCast!L(temp); - } - - /// - @safe unittest - { - Checked!(int, WithNaN) x; - x += 4; - assert(x.isNaN); - x = 0; - x += 4; - assert(!x.isNaN); - x += int.max; - assert(x.isNaN); - } -} - -/// -@safe unittest -{ - auto x1 = Checked!(int, WithNaN)(); - assert(x1.isNaN); - assert(x1.get == int.min); - assert(x1 != x1); - assert(!(x1 < x1)); - assert(!(x1 > x1)); - assert(!(x1 == x1)); - ++x1; - assert(x1.isNaN); - assert(x1.get == int.min); - --x1; - assert(x1.isNaN); - assert(x1.get == int.min); - x1 = 42; - assert(!x1.isNaN); - assert(x1 == x1); - assert(x1 <= x1); - assert(x1 >= x1); - static assert(x1.min == int.min + 1); - x1 += long(int.max); -} - -/** -Queries whether a $(D Checked!(T, WithNaN)) object is not a number (NaN). - -Params: x = the `Checked` instance queried - -Returns: `true` if `x` is a NaN, `false` otherwise -*/ -bool isNaN(T)(const Checked!(T, WithNaN) x) -{ - return x.get == x.init.get; -} - -/// -@safe unittest -{ - auto x1 = Checked!(int, WithNaN)(); - assert(x1.isNaN); - x1 = 1; - assert(!x1.isNaN); - x1 = x1.init; - assert(x1.isNaN); -} - -@safe unittest -{ - void test1(T)() - { - auto x1 = Checked!(T, WithNaN)(); - assert(x1.isNaN); - assert(x1.get == int.min); - assert(x1 != x1); - assert(!(x1 < x1)); - assert(!(x1 > x1)); - assert(!(x1 == x1)); - assert(x1.get == int.min); - auto x2 = Checked!(T, WithNaN)(42); - assert(!x2.isNaN); - assert(x2 == x2); - assert(x2 <= x2); - assert(x2 >= x2); - static assert(x2.min == T.min + 1); - } - test1!int; - test1!(const int); - test1!(immutable int); - - void test2(T)() - { - auto x1 = Checked!(T, WithNaN)(); - assert(x1.get == T.min); - assert(x1 != x1); - assert(!(x1 < x1)); - assert(!(x1 > x1)); - assert(!(x1 == x1)); - ++x1; - assert(x1.get == T.min); - --x1; - assert(x1.get == T.min); - x1 = 42; - assert(x1 == x1); - assert(x1 <= x1); - assert(x1 >= x1); - static assert(x1.min == T.min + 1); - x1 += long(T.max); - } - test2!int; -} - -@safe unittest -{ - alias Smart(T) = Checked!(Checked!(T, ProperCompare), WithNaN); - Smart!int x1; - assert(x1 != x1); - x1 = -1; - assert(x1 < 1u); - auto x2 = Smart!(const int)(42); -} - -// Saturate -/** - -Hook that implements $(I saturation), i.e. any arithmetic operation that would -overflow leaves the result at its extreme value (`min` or `max` depending on the -direction of the overflow). - -Saturation is not sticky; if a value reaches its saturation value, another -operation may take it back to normal range. - -*/ -struct Saturate -{ -static: - /** - - Implements saturation for operators `+=`, `-=`, `*=`, `/=`, `%=`, `^^=`, `&=`, `|=`, `^=`, `<<=`, `>>=`, - and `>>>=`. This hook is called if the result of the binary operation does - not fit in `Lhs` without loss of information or a change in sign. - - Params: - Rhs = The right-hand side type in the assignment, after the operation has - been computed - bound = The bound being violated - - Returns: `Lhs.max` if $(D rhs >= 0), `Lhs.min` otherwise. - - */ - T onLowerBound(Rhs, T)(Rhs rhs, T bound) - { - return bound; - } - /// ditto - T onUpperBound(Rhs, T)(Rhs rhs, T bound) - { - return bound; - } - /// - @safe unittest - { - auto x = checked!Saturate(short(100)); - x += 33000; - assert(x == short.max); - x -= 70000; - assert(x == short.min); - } - - /** - - Implements saturation for operators `+`, `-` (unary and binary), `*`, `/`, - `%`, `^^`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`. - - For unary `-`, `onOverflow` is called if $(D lhs == Lhs.min) and `Lhs` is a - signed type. The function returns `Lhs.max`. - - For binary operators, the result is as follows: $(UL $(LI `Lhs.max` if the - result overflows in the positive direction, on division by `0`, or on - shifting right by a negative value) $(LI `Lhs.min` if the result overflows - in the negative direction) $(LI `0` if `lhs` is being shifted left by a - negative value, or shifted right by a large positive value)) - - Params: - x = The operator involved in the `opAssign` operation - Lhs = The left-hand side of the operator (`Lhs` is the first argument to - `Checked`) - Rhs = The right-hand side type in the operator - - Returns: The saturated result of the operator. - - */ - auto onOverflow(string x, Lhs)(Lhs lhs) - { - static assert(x == "-" || x == "++" || x == "--"); - return x == "--" ? Lhs.min : Lhs.max; - } - /// ditto - typeof(Lhs() + Rhs()) onOverflow(string x, Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - static if (x == "+") - return rhs >= 0 ? Lhs.max : Lhs.min; - else static if (x == "*") - return (lhs >= 0) == (rhs >= 0) ? Lhs.max : Lhs.min; - else static if (x == "^^") - return lhs > 0 || !(rhs & 1) ? Lhs.max : Lhs.min; - else static if (x == "-") - return rhs >= 0 ? Lhs.min : Lhs.max; - else static if (x == "/" || x == "%") - return Lhs.max; - else static if (x == "<<") - return rhs >= 0 ? Lhs.max : 0; - else static if (x == ">>" || x == ">>>") - return rhs >= 0 ? 0 : Lhs.max; - else - static assert(false); - } - /// - @safe unittest - { - assert(checked!Saturate(int.max) + 1 == int.max); - assert(checked!Saturate(100) ^^ 10 == int.max); - assert(checked!Saturate(-100) ^^ 10 == int.max); - assert(checked!Saturate(100) / 0 == int.max); - assert(checked!Saturate(100) << -1 == 0); - assert(checked!Saturate(100) << 33 == int.max); - assert(checked!Saturate(100) >> -1 == int.max); - assert(checked!Saturate(100) >> 33 == 0); - } -} - -/// -@safe unittest -{ - auto x = checked!Saturate(int.max); - ++x; - assert(x == int.max); - --x; - assert(x == int.max - 1); - x = int.min; - assert(-x == int.max); - x -= 42; - assert(x == int.min); - assert(x * -2 == int.max); -} - -/* -Yields `true` if `T1` is "value convertible" (by C's "value preserving" rule, -see $(HTTP c-faq.com/expr/preservingrules.html)) to `T2`, where the two are -integral types. That is, all of values in `T1` are also in `T2`. For example -`int` is value convertible to `long` but not to `uint` or `ulong`. -*/ -private enum valueConvertible(T1, T2) = isIntegral!T1 && isIntegral!T2 && - is(T1 : T2) && ( - isUnsigned!T1 == isUnsigned!T2 || // same signedness - !isUnsigned!T2 && T2.sizeof > T1.sizeof // safely convertible - ); /** - -Defines binary operations with overflow checking for any two integral types. -The result type obeys the language rules (even when they may be -counterintuitive), and `overflow` is set if an overflow occurs (including -inadvertent change of signedness, e.g. `-1` is converted to `uint`). -Conceptually the behavior is: - -$(OL $(LI Perform the operation in infinite precision) -$(LI If the infinite-precision result fits in the result type, return it and -do not touch `overflow`) -$(LI Otherwise, set `overflow` to `true` and return an unspecified value) -) - -The implementation exploits properties of types and operations to minimize -additional work. - -Params: -x = The binary operator involved, e.g. `/` -lhs = The left-hand side of the operator -rhs = The right-hand side of the operator -overflow = The overflow indicator (assigned `true` in case there's an error) - -Returns: -The result of the operation, which is the same as the built-in operator -*/ -typeof(mixin(x == "cmp" ? "0" : ("L() " ~ x ~ " R()"))) -opChecked(string x, L, R)(const L lhs, const R rhs, ref bool overflow) -if (isIntegral!L && isIntegral!R) -{ - static if (x == "cmp") - alias Result = int; - else - alias Result = typeof(mixin("L() " ~ x ~ " R()")); - - import core.checkedint : addu, adds, subs, muls, subu, mulu; - import std.algorithm.comparison : among; - static if (x == "==") - { - alias C = typeof(lhs + rhs); - static if (valueConvertible!(L, C) && valueConvertible!(R, C)) - { - // Values are converted to R before comparison, cool. - return lhs == rhs; - } - else - { - static assert(isUnsigned!C); - static assert(isUnsigned!L != isUnsigned!R); - if (lhs != rhs) return false; - // R(lhs) and R(rhs) have the same bit pattern, yet may be - // different due to signedness change. - static if (!isUnsigned!R) - { - if (rhs >= 0) - return true; - } - else - { - if (lhs >= 0) - return true; - } - overflow = true; - return true; - } - } - else static if (x == "cmp") - { - alias C = typeof(lhs + rhs); - static if (!valueConvertible!(L, C) || !valueConvertible!(R, C)) - { - static assert(isUnsigned!C); - static assert(isUnsigned!L != isUnsigned!R); - if (!isUnsigned!L && lhs < 0) - { - overflow = true; - return -1; - } - if (!isUnsigned!R && rhs < 0) - { - overflow = true; - return 1; - } - } - return lhs < rhs ? -1 : lhs > rhs; - } - else static if (x.among("<<", ">>", ">>>")) - { - // Handle shift separately from all others. The test below covers - // negative rhs as well. - import std.conv : unsigned; - if (unsigned(rhs) > 8 * Result.sizeof) goto fail; - return mixin("lhs" ~ x ~ "rhs"); - } - else static if (x.among("&", "|", "^")) - { - // Nothing to check - return mixin("lhs" ~ x ~ "rhs"); - } - else static if (x == "^^") - { - // Exponentiation is weird, handle separately - return pow(lhs, rhs, overflow); - } - else static if (valueConvertible!(L, Result) && - valueConvertible!(R, Result)) - { - static if (L.sizeof < Result.sizeof && R.sizeof < Result.sizeof && - x.among("+", "-", "*")) - { - // No checks - both are value converted and result is in range - return mixin("lhs" ~ x ~ "rhs"); - } - else static if (x == "+") - { - static if (isUnsigned!Result) alias impl = addu; - else alias impl = adds; - return impl(Result(lhs), Result(rhs), overflow); - } - else static if (x == "-") - { - static if (isUnsigned!Result) alias impl = subu; - else alias impl = subs; - return impl(Result(lhs), Result(rhs), overflow); - } - else static if (x == "*") - { - static if (!isUnsigned!L && !isUnsigned!R && - is(L == Result)) - { - if (lhs == Result.min && rhs == -1) goto fail; - } - static if (isUnsigned!Result) alias impl = mulu; - else alias impl = muls; - return impl(Result(lhs), Result(rhs), overflow); - } - else static if (x == "/" || x == "%") - { - static if (!isUnsigned!L && !isUnsigned!R && - is(L == Result) && x == "/") - { - if (lhs == Result.min && rhs == -1) goto fail; - } - if (rhs == 0) goto fail; - return mixin("lhs" ~ x ~ "rhs"); - } - else static assert(0, x); - } - else // Mixed signs - { - static assert(isUnsigned!Result); - static assert(isUnsigned!L != isUnsigned!R); - static if (x == "+") - { - static if (!isUnsigned!L) - { - if (lhs < 0) - return subu(Result(rhs), Result(-lhs), overflow); - } - else static if (!isUnsigned!R) - { - if (rhs < 0) - return subu(Result(lhs), Result(-rhs), overflow); - } - return addu(Result(lhs), Result(rhs), overflow); - } - else static if (x == "-") - { - static if (!isUnsigned!L) - { - if (lhs < 0) goto fail; - } - else static if (!isUnsigned!R) - { - if (rhs < 0) - return addu(Result(lhs), Result(-rhs), overflow); - } - return subu(Result(lhs), Result(rhs), overflow); - } - else static if (x == "*") - { - static if (!isUnsigned!L) - { - if (lhs < 0) goto fail; - } - else static if (!isUnsigned!R) - { - if (rhs < 0) goto fail; - } - return mulu(Result(lhs), Result(rhs), overflow); - } - else static if (x == "/" || x == "%") - { - static if (!isUnsigned!L) - { - if (lhs < 0 || rhs == 0) goto fail; - } - else static if (!isUnsigned!R) - { - if (rhs <= 0) goto fail; - } - return mixin("Result(lhs)" ~ x ~ "Result(rhs)"); - } - else static assert(0, x); - } - debug assert(false); -fail: - overflow = true; - return Result(0); -} - -/// -@safe unittest -{ - bool overflow; - assert(opChecked!"+"(const short(1), short(1), overflow) == 2 && !overflow); - assert(opChecked!"+"(1, 1, overflow) == 2 && !overflow); - assert(opChecked!"+"(1, 1u, overflow) == 2 && !overflow); - assert(opChecked!"+"(-1, 1u, overflow) == 0 && !overflow); - assert(opChecked!"+"(1u, -1, overflow) == 0 && !overflow); -} - -/// -@safe unittest -{ - bool overflow; - assert(opChecked!"-"(1, 1, overflow) == 0 && !overflow); - assert(opChecked!"-"(1, 1u, overflow) == 0 && !overflow); - assert(opChecked!"-"(1u, -1, overflow) == 2 && !overflow); - assert(opChecked!"-"(-1, 1u, overflow) == 0 && overflow); -} - -@safe unittest -{ - bool overflow; - assert(opChecked!"*"(2, 3, overflow) == 6 && !overflow); - assert(opChecked!"*"(2, 3u, overflow) == 6 && !overflow); - assert(opChecked!"*"(1u, -1, overflow) == 0 && overflow); - //assert(mul(-1, 1u, overflow) == uint.max - 1 && overflow); -} - -@safe unittest -{ - bool overflow; - assert(opChecked!"/"(6, 3, overflow) == 2 && !overflow); - assert(opChecked!"/"(6, 3, overflow) == 2 && !overflow); - assert(opChecked!"/"(6u, 3, overflow) == 2 && !overflow); - assert(opChecked!"/"(6, 3u, overflow) == 2 && !overflow); - assert(opChecked!"/"(11, 0, overflow) == 0 && overflow); - overflow = false; - assert(opChecked!"/"(6u, 0, overflow) == 0 && overflow); - overflow = false; - assert(opChecked!"/"(-6, 2u, overflow) == 0 && overflow); - overflow = false; - assert(opChecked!"/"(-6, 0u, overflow) == 0 && overflow); - overflow = false; - assert(opChecked!"cmp"(0u, -6, overflow) == 1 && overflow); - overflow = false; - assert(opChecked!"|"(1, 2, overflow) == 3 && !overflow); -} - -/* -Exponentiation function used by the implementation of operator `^^`. -*/ -private pure @safe nothrow @nogc -auto pow(L, R)(const L lhs, const R rhs, ref bool overflow) -if (isIntegral!L && isIntegral!R) -{ - if (rhs <= 1) - { - if (rhs == 0) return 1; - static if (!isUnsigned!R) - return rhs == 1 - ? lhs - : (rhs == -1 && (lhs == 1 || lhs == -1)) ? lhs : 0; - else - return lhs; - } - - typeof(lhs ^^ rhs) b = void; - static if (!isUnsigned!L && isUnsigned!(typeof(b))) - { - // Need to worry about mixed-sign stuff - if (lhs < 0) - { - if (rhs & 1) - { - if (lhs < 0) overflow = true; - return 0; - } - b = -lhs; - } - else - { - b = lhs; - } - } - else - { - b = lhs; - } - if (b == 1) return 1; - if (b == -1) return (rhs & 1) ? -1 : 1; - if (rhs > 63) - { - overflow = true; - return 0; - } - - assert((b > 1 || b < -1) && rhs > 1); - return powImpl(b, cast(uint) rhs, overflow); -} - -// Inspiration: http://www.stepanovpapers.com/PAM.pdf -pure @safe nothrow @nogc -private T powImpl(T)(T b, uint e, ref bool overflow) -if (isIntegral!T && T.sizeof >= 4) -{ - assert(e > 1); - - import core.checkedint : muls, mulu; - static if (isUnsigned!T) alias mul = mulu; - else alias mul = muls; - - T r = b; - --e; - // Loop invariant: r * (b ^^ e) is the actual result - for (;; e /= 2) - { - if (e % 2) - { - r = mul(r, b, overflow); - if (e == 1) break; - } - b = mul(b, b, overflow); - } - return r; -} - -@safe unittest -{ - static void testPow(T)(T x, uint e) - { - bool overflow; - assert(opChecked!"^^"(T(0), 0, overflow) == 1); - assert(opChecked!"^^"(-2, T(0), overflow) == 1); - assert(opChecked!"^^"(-2, T(1), overflow) == -2); - assert(opChecked!"^^"(-1, -1, overflow) == -1); - assert(opChecked!"^^"(-2, 1, overflow) == -2); - assert(opChecked!"^^"(-2, -1, overflow) == 0); - assert(opChecked!"^^"(-2, 4u, overflow) == 16); - assert(!overflow); - assert(opChecked!"^^"(-2, 3u, overflow) == 0); - assert(overflow); - overflow = false; - assert(opChecked!"^^"(3, 64u, overflow) == 0); - assert(overflow); - overflow = false; - foreach (uint i; 0 .. e) - { - assert(opChecked!"^^"(x, i, overflow) == x ^^ i); - assert(!overflow); - } - assert(opChecked!"^^"(x, e, overflow) == x ^^ e); - assert(overflow); - } - - testPow!int(3, 21); - testPow!uint(3, 21); - testPow!long(3, 40); - testPow!ulong(3, 41); -} - -version (StdUnittest) private struct CountOverflows -{ - uint calls; - auto onOverflow(string op, Lhs)(Lhs lhs) - { - ++calls; - return mixin(op ~ "lhs"); - } - auto onOverflow(string op, Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - ++calls; - return mixin("lhs" ~ op ~ "rhs"); - } - T onLowerBound(Rhs, T)(Rhs rhs, T bound) - { - ++calls; - return cast(T) rhs; - } - T onUpperBound(Rhs, T)(Rhs rhs, T bound) - { - ++calls; - return cast(T) rhs; - } -} - -// opBinary -@nogc nothrow pure @safe unittest -{ - static struct CountOpBinary - { - uint calls; - auto hookOpBinary(string op, Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - ++calls; - return mixin("lhs" ~ op ~ "rhs"); - } - } - auto x = Checked!(const int, void)(42), y = Checked!(immutable int, void)(142); - assert(x + y == 184); - assert(x + 100 == 142); - assert(y - x == 100); - assert(200 - x == 158); - assert(y * x == 142 * 42); - assert(x / 1 == 42); - assert(x % 20 == 2); - - auto x1 = Checked!(int, CountOverflows)(42); - assert(x1 + 0 == 42); - assert(x1 + false == 42); - assert(is(typeof(x1 + 0.5) == double)); - assert(x1 + 0.5 == 42.5); - assert(x1.hook.calls == 0); - assert(x1 + int.max == int.max + 42); - assert(x1.hook.calls == 1); - assert(x1 * 2 == 84); - assert(x1.hook.calls == 1); - assert(x1 / 2 == 21); - assert(x1.hook.calls == 1); - assert(x1 % 20 == 2); - assert(x1.hook.calls == 1); - assert(x1 << 2 == 42 << 2); - assert(x1.hook.calls == 1); - assert(x1 << 42 == x1.get << x1.get); - assert(x1.hook.calls == 2); - x1 = int.min; - assert(x1 - 1 == int.max); - assert(x1.hook.calls == 3); - - auto x2 = Checked!(int, CountOpBinary)(42); - assert(x2 + 1 == 43); - assert(x2.hook.calls == 1); - - auto x3 = Checked!(uint, CountOverflows)(42u); - assert(x3 + 1 == 43); - assert(x3.hook.calls == 0); - assert(x3 - 1 == 41); - assert(x3.hook.calls == 0); - assert(x3 + (-42) == 0); - assert(x3.hook.calls == 0); - assert(x3 - (-42) == 84); - assert(x3.hook.calls == 0); - assert(x3 * 2 == 84); - assert(x3.hook.calls == 0); - assert(x3 * -2 == -84); - assert(x3.hook.calls == 1); - assert(x3 / 2 == 21); - assert(x3.hook.calls == 1); - assert(x3 / -2 == 0); - assert(x3.hook.calls == 2); - assert(x3 ^^ 2 == 42 * 42); - assert(x3.hook.calls == 2); - - auto x4 = Checked!(int, CountOverflows)(42); - assert(x4 + 1 == 43); - assert(x4.hook.calls == 0); - assert(x4 + 1u == 43); - assert(x4.hook.calls == 0); - assert(x4 - 1 == 41); - assert(x4.hook.calls == 0); - assert(x4 * 2 == 84); - assert(x4.hook.calls == 0); - x4 = -2; - assert(x4 + 2u == 0); - assert(x4.hook.calls == 0); - assert(x4 * 2u == -4); - assert(x4.hook.calls == 1); - - auto x5 = Checked!(int, CountOverflows)(3); - assert(x5 ^^ 0 == 1); - assert(x5 ^^ 1 == 3); - assert(x5 ^^ 2 == 9); - assert(x5 ^^ 3 == 27); - assert(x5 ^^ 4 == 81); - assert(x5 ^^ 5 == 81 * 3); - assert(x5 ^^ 6 == 81 * 9); -} - -// opBinaryRight -@nogc nothrow pure @safe unittest -{ - auto x1 = Checked!(int, CountOverflows)(42); - assert(1 + x1 == 43); - assert(true + x1 == 43); - assert(0.5 + x1 == 42.5); - auto x2 = Checked!(int, void)(42); - assert(x1 + x2 == 84); - assert(x2 + x1 == 84); -} - -// opOpAssign -@safe unittest -{ - auto x1 = Checked!(int, CountOverflows)(3); - assert((x1 += 2) == 5); - x1 *= 2_000_000_000L; - assert(x1.hook.calls == 1); - x1 *= -2_000_000_000L; - assert(x1.hook.calls == 2); - - auto x2 = Checked!(ushort, CountOverflows)(ushort(3)); - assert((x2 += 2) == 5); - assert(x2.hook.calls == 0); - assert((x2 += ushort.max) == cast(ushort) (ushort(5) + ushort.max)); - assert(x2.hook.calls == 1); - - auto x3 = Checked!(uint, CountOverflows)(3u); - x3 *= ulong(2_000_000_000); - assert(x3.hook.calls == 1); -} - -// opAssign -@safe unittest -{ - Checked!(int, void) x; - x = 42; - assert(x.get == 42); - x = x; - assert(x.get == 42); - x = short(43); - assert(x.get == 43); - x = ushort(44); - assert(x.get == 44); -} - -@safe unittest -{ - static assert(!is(typeof(Checked!(short, void)(ushort(42))))); - static assert(!is(typeof(Checked!(int, void)(long(42))))); - static assert(!is(typeof(Checked!(int, void)(ulong(42))))); - assert(Checked!(short, void)(short(42)).get == 42); - assert(Checked!(int, void)(ushort(42)).get == 42); -} - -// opCast -@nogc nothrow pure @safe unittest -{ - static assert(is(typeof(cast(float) Checked!(int, void)(42)) == float)); - assert(cast(float) Checked!(int, void)(42) == 42); - - assert(is(typeof(cast(long) Checked!(int, void)(42)) == long)); - assert(cast(long) Checked!(int, void)(42) == 42); - static assert(is(typeof(cast(long) Checked!(uint, void)(42u)) == long)); - assert(cast(long) Checked!(uint, void)(42u) == 42); - - auto x = Checked!(int, void)(42); - if (x) {} else assert(0); - x = 0; - if (x) assert(0); - - static struct Hook1 - { - uint calls; - Dst hookOpCast(Dst, Src)(Src value) - { - ++calls; - return 42; - } - } - auto y = Checked!(long, Hook1)(long.max); - assert(cast(int) y == 42); - assert(cast(uint) y == 42); - assert(y.hook.calls == 2); - - static struct Hook2 - { - uint calls; - Dst onBadCast(Dst, Src)(Src value) - { - ++calls; - return 42; - } - } - auto x1 = Checked!(uint, Hook2)(100u); - assert(cast(ushort) x1 == 100); - assert(cast(short) x1 == 100); - assert(cast(float) x1 == 100); - assert(cast(double) x1 == 100); - assert(cast(real) x1 == 100); - assert(x1.hook.calls == 0); - assert(cast(int) x1 == 100); - assert(x1.hook.calls == 0); - x1 = uint.max; - assert(cast(int) x1 == 42); - assert(x1.hook.calls == 1); - - auto x2 = Checked!(int, Hook2)(-100); - assert(cast(short) x2 == -100); - assert(cast(ushort) x2 == 42); - assert(cast(uint) x2 == 42); - assert(cast(ulong) x2 == 42); - assert(x2.hook.calls == 3); -} - -// opEquals -@nogc nothrow pure @safe unittest -{ - assert(Checked!(int, void)(42) == 42L); - assert(42UL == Checked!(int, void)(42)); - - static struct Hook1 - { - uint calls; - bool hookOpEquals(Lhs, Rhs)(const Lhs lhs, const Rhs rhs) - { - ++calls; - return lhs != rhs; - } - } - auto x1 = Checked!(int, Hook1)(100); - assert(x1 != Checked!(long, Hook1)(100)); - assert(x1.hook.calls == 1); - assert(x1 != 100u); - assert(x1.hook.calls == 2); - - static struct Hook2 - { - uint calls; - bool hookOpEquals(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - ++calls; - return false; - } - } - auto x2 = Checked!(int, Hook2)(-100); - assert(x2 != x1); - // For coverage: lhs has no hookOpEquals, rhs does - assert(Checked!(uint, void)(100u) != x2); - // For coverage: different types, neither has a hookOpEquals - assert(Checked!(uint, void)(100u) == Checked!(int, void*)(100)); - assert(x2.hook.calls == 0); - assert(x2 != -100); - assert(x2.hook.calls == 1); - assert(x2 != cast(uint) -100); - assert(x2.hook.calls == 2); - x2 = 100; - assert(x2 != cast(uint) 100); - assert(x2.hook.calls == 3); - x2 = -100; - - auto x3 = Checked!(uint, Hook2)(100u); - assert(x3 != 100); - x3 = uint.max; - assert(x3 != -1); - - assert(x2 != x3); -} - -// opCmp -@nogc nothrow pure @safe unittest -{ - Checked!(int, void) x; - assert(x <= x); - assert(x < 45); - assert(x < 45u); - assert(x > -45); - assert(x < 44.2); - assert(x > -44.2); - assert(!(x < double.init)); - assert(!(x > double.init)); - assert(!(x <= double.init)); - assert(!(x >= double.init)); - - static struct Hook1 - { - uint calls; - int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - ++calls; - return 0; - } - } - auto x1 = Checked!(int, Hook1)(42); - assert(!(x1 < 43u)); - assert(!(43u < x1)); - assert(x1.hook.calls == 2); - - static struct Hook2 - { - uint calls; - int hookOpCmp(Lhs, Rhs)(Lhs lhs, Rhs rhs) - { - ++calls; - return ProperCompare.hookOpCmp(lhs, rhs); - } - } - auto x2 = Checked!(int, Hook2)(-42); - assert(x2 < 43u); - assert(43u > x2); - assert(x2.hook.calls == 2); - x2 = 42; - assert(x2 > 41u); - - auto x3 = Checked!(uint, Hook2)(42u); - assert(x3 > 41); - assert(x3 > -41); -} - -// opUnary -@nogc nothrow pure @safe unittest -{ - auto x = Checked!(int, void)(42); - assert(x == +x); - static assert(is(typeof(-x) == typeof(x))); - assert(-x == Checked!(int, void)(-42)); - static assert(is(typeof(~x) == typeof(x))); - assert(~x == Checked!(int, void)(~42)); - assert(++x == 43); - assert(--x == 42); - - static struct Hook1 - { - uint calls; - auto hookOpUnary(string op, T)(T value) if (op == "-") - { - ++calls; - return T(42); - } - auto hookOpUnary(string op, T)(T value) if (op == "~") - { - ++calls; - return T(43); - } - } - auto x1 = Checked!(int, Hook1)(100); - assert(is(typeof(-x1) == typeof(x1))); - assert(-x1 == Checked!(int, Hook1)(42)); - assert(is(typeof(~x1) == typeof(x1))); - assert(~x1 == Checked!(int, Hook1)(43)); - assert(x1.hook.calls == 2); - - static struct Hook2 - { - uint calls; - void hookOpUnary(string op, T)(ref T value) if (op == "++") - { - ++calls; - --value; - } - void hookOpUnary(string op, T)(ref T value) if (op == "--") - { - ++calls; - ++value; - } - } - auto x2 = Checked!(int, Hook2)(100); - assert(++x2 == 99); - assert(x2 == 99); - assert(--x2 == 100); - assert(x2 == 100); - - auto x3 = Checked!(int, CountOverflows)(int.max - 1); - assert(++x3 == int.max); - assert(x3.hook.calls == 0); - assert(++x3 == int.min); - assert(x3.hook.calls == 1); - assert(-x3 == int.min); - assert(x3.hook.calls == 2); - - x3 = int.min + 1; - assert(--x3 == int.min); - assert(x3.hook.calls == 2); - assert(--x3 == int.max); - assert(x3.hook.calls == 3); -} - -// -@nogc nothrow pure @safe unittest -{ - Checked!(int, void) x; - assert(x == x); - assert(x == +x); - assert(x == -x); - ++x; - assert(x == 1); - x++; - assert(x == 2); - - x = 42; - assert(x == 42); - const short _short = 43; - x = _short; - assert(x == _short); - ushort _ushort = 44; - x = _ushort; - assert(x == _ushort); - assert(x == 44.0); - assert(x != 44.1); - assert(x < 45); - assert(x < 44.2); - assert(x > -45); - assert(x > -44.2); - - assert(cast(long) x == 44); - assert(cast(short) x == 44); - - const Checked!(uint, void) y; - assert(y <= y); - assert(y == 0); - assert(y < x); - x = -1; - assert(x > y); -} - -@nogc nothrow pure @safe unittest -{ - alias cint = Checked!(int, void); - cint a = 1, b = 2; - a += b; - assert(a == cint(3)); - - alias ccint = Checked!(cint, Saturate); - ccint c = 14; - a += c; - assert(a == cint(17)); -} - -// toHash -@safe unittest -{ - assert(checked(42).toHash() == checked(42).toHash()); - assert(checked(12).toHash() != checked(19).toHash()); - - static struct Hook1 - { - static size_t hookToHash(T)(T payload) nothrow @trusted - { - static if (size_t.sizeof == 4) - { - return typeid(payload).getHash(&payload) ^ 0xFFFF_FFFF; - } - else - { - return typeid(payload).getHash(&payload) ^ 0xFFFF_FFFF_FFFF_FFFF; - } - - } - } - - auto a = checked!Hook1(78); - auto b = checked!Hook1(78); - assert(a.toHash() == b.toHash()); - - assert(checked!Hook1(12).toHash() != checked!Hook1(13).toHash()); - - static struct Hook2 - { - static if (size_t.sizeof == 4) - { - static size_t hashMask = 0xFFFF_0000; - } - else - { - static size_t hashMask = 0xFFFF_0000_FFFF_0000; - } - - static size_t hookToHash(T)(T payload) nothrow @trusted - { - return typeid(payload).getHash(&payload) ^ hashMask; - } - } - - auto x = checked!Hook2(1901); - auto y = checked!Hook2(1989); - - assert((() nothrow @safe => x.toHash() == x.toHash())()); - - assert(x.toHash() == x.toHash()); - assert(x.toHash() != y.toHash()); - assert(checked!Hook1(1901).toHash() != x.toHash()); - - immutable z = checked!Hook1(1901); - immutable t = checked!Hook1(1901); - immutable w = checked!Hook2(1901); - - assert(z.toHash() == t.toHash()); - assert(z.toHash() != x.toHash()); - assert(z.toHash() != w.toHash()); - - const long c = 0xF0F0F0F0; - const long d = 0xF0F0F0F0; - - assert(checked!Hook1(c).toHash() != checked!Hook2(c)); - assert(checked!Hook1(c).toHash() != checked!Hook1(d)); - - // Hook with state, does not implement hookToHash - static struct Hook3 - { - ulong var1 = ulong.max; - uint var2 = uint.max; - } - - assert(checked!Hook3(12).toHash() != checked!Hook3(13).toHash()); - assert(checked!Hook3(13).toHash() == checked!Hook3(13).toHash()); - - // Hook with no state and no hookToHash, payload has its own hashing function - auto x1 = Checked!(Checked!int, ProperCompare)(123); - auto x2 = Checked!(Checked!int, ProperCompare)(123); - auto x3 = Checked!(Checked!int, ProperCompare)(144); - - assert(x1.toHash() == x2.toHash()); - assert(x1.toHash() != x3.toHash()); - assert(x2.toHash() != x3.toHash()); - - // Check shared. - { - shared shared0 = checked(12345678); - shared shared1 = checked!Hook1(123456789); - shared shared2 = checked!Hook2(234567891); - shared shared3 = checked!Hook3(345678912); - assert(shared0.toHash() == hashOf(shared0)); - assert(shared1.toHash() == hashOf(shared1)); - assert(shared2.toHash() == hashOf(shared2)); - assert(shared3.toHash() == hashOf(shared3)); - } -} - -/// -@safe unittest -{ - struct MyHook - { - static size_t hookToHash(T)(const T payload) nothrow @trusted - { - return .hashOf(payload); - } - } - - int[Checked!(int, MyHook)] aa; - Checked!(int, MyHook) var = 42; - aa[var] = 100; - - assert(aa[var] == 100); - - int[Checked!(int, Abort)] bb; - Checked!(int, Abort) var2 = 42; - bb[var2] = 100; - - assert(bb[var2] == 100); -} + * This module is now deprecated, use $(MREF std, experimental) + * instead. + * + * Copyright: Copyright The D Language Foundation 2005 - 2015. + * License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0). + * Authors: + * Source: $(PHOBOSSRC std/experimental/checkedint.d) + * + * $(SCRIPT inhibitQuickIndex = 1;) + */ +deprecated module std.experimental.checkedint; +public import std.checkedint; diff --git a/libphobos/src/std/experimental/logger/core.d b/libphobos/src/std/experimental/logger/core.d index 08d6cbede2d..afd98add6ba 100644 --- a/libphobos/src/std/experimental/logger/core.d +++ b/libphobos/src/std/experimental/logger/core.d @@ -1633,13 +1633,14 @@ private @property Logger defaultSharedLoggerImpl() @trusted import std.concurrency : initOnce; initOnce!stdSharedDefaultLogger({ auto buffer = cast(ubyte[]) _buffer; - return emplace!FileLogger(buffer, stderr, LogLevel.all); + return emplace!FileLogger(buffer, stderr, LogLevel.warning); }()); return stdSharedDefaultLogger; } -/** This property sets and gets the default `Logger`. +/** This property sets and gets the default `Logger`. Unless set to another +logger by the user, the default logger's log level is LogLevel.warning. Example: ------------- @@ -2007,7 +2008,7 @@ version (StdUnittest) private void testFuncNames(Logger logger) @safe auto oldunspecificLogger = sharedLog; - assert(oldunspecificLogger.logLevel == LogLevel.all, + assert(oldunspecificLogger.logLevel == LogLevel.warning, to!string(oldunspecificLogger.logLevel)); assert(l.logLevel == LogLevel.all); @@ -3063,7 +3064,7 @@ private void trustedStore(T)(ref shared T dst, ref T src) @trusted { auto dl = cast(FileLogger) sharedLog; assert(dl !is null); - assert(dl.logLevel == LogLevel.all); + assert(dl.logLevel == LogLevel.warning); assert(globalLogLevel == LogLevel.all); auto tl = cast(StdForwardLogger) stdThreadLocalLog; diff --git a/libphobos/src/std/experimental/logger/filelogger.d b/libphobos/src/std/experimental/logger/filelogger.d index 6fd7e5ff66b..a0bea7733cf 100644 --- a/libphobos/src/std/experimental/logger/filelogger.d +++ b/libphobos/src/std/experimental/logger/filelogger.d @@ -263,7 +263,7 @@ class FileLogger : Logger { auto dl = cast(FileLogger) sharedLog; assert(dl !is null); - assert(dl.logLevel == LogLevel.all); + assert(dl.logLevel == LogLevel.warning); assert(globalLogLevel == LogLevel.all); auto tl = cast(StdForwardLogger) stdThreadLocalLog; diff --git a/libphobos/src/std/experimental/logger/multilogger.d b/libphobos/src/std/experimental/logger/multilogger.d index 0751cb86357..90bfb5820ab 100644 --- a/libphobos/src/std/experimental/logger/multilogger.d +++ b/libphobos/src/std/experimental/logger/multilogger.d @@ -191,7 +191,7 @@ class MultiLogger : Logger { auto dl = cast(FileLogger) sharedLog; assert(dl !is null); - assert(dl.logLevel == LogLevel.all); + assert(dl.logLevel == LogLevel.warning); assert(globalLogLevel == LogLevel.all); auto tl = cast(StdForwardLogger) stdThreadLocalLog; diff --git a/libphobos/src/std/file.d b/libphobos/src/std/file.d index 315e054cbab..c974ada2ae8 100644 --- a/libphobos/src/std/file.d +++ b/libphobos/src/std/file.d @@ -89,7 +89,7 @@ import std.datetime.date : DateTime; import std.datetime.systime : Clock, SysTime, unixTimeToStdTime; import std.internal.cstring; import std.meta; -import std.range.primitives; +import std.range; import std.traits; import std.typecons; @@ -313,8 +313,7 @@ Throws: $(LREF FileException) on error. */ void[] read(R)(R name, size_t upTo = size_t.max) -if (isInputRange!R && isSomeChar!(ElementEncodingType!R) && !isInfinite!R && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { static if (isNarrowString!R && is(immutable ElementEncodingType!R == immutable char)) return readImpl(name, name.tempCString!FSChar(), upTo); @@ -356,7 +355,7 @@ version (Posix) private void[] readImpl(scope const(char)[] name, scope const(FS import core.memory : GC; import std.algorithm.comparison : min; import std.conv : to; - import std.experimental.checkedint : checked; + import std.checkedint : checked; // A few internal configuration parameters { enum size_t @@ -500,7 +499,7 @@ version (linux) @safe unittest $(REF UTFException, std, utf) on UTF decoding error. +/ S readText(S = string, R)(auto ref R name) -if (isSomeString!S && (isInputRange!R && !isInfinite!R && isSomeChar!(ElementType!R) || is(StringTypeOf!R))) +if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R))) { import std.algorithm.searching : startsWith; import std.encoding : getBOM, BOM; @@ -736,8 +735,7 @@ Throws: $(LREF FileException) on error. See_also: $(REF toFile, std,stdio) */ void write(R)(R name, const void[] buffer) -if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && - !isConvertibleToString!R) +if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R) { static if (isNarrowString!R && is(immutable ElementEncodingType!R == immutable char)) writeImpl(name, name.tempCString!FSChar(), buffer, false); @@ -785,8 +783,7 @@ Params: Throws: $(LREF FileException) on error. */ void append(R)(R name, const void[] buffer) -if ((isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || isSomeString!R) && - !isConvertibleToString!R) +if ((isSomeFiniteCharInputRange!R || isSomeString!R) && !isConvertibleToString!R) { static if (isNarrowString!R && is(immutable ElementEncodingType!R == immutable char)) writeImpl(name, name.tempCString!FSChar(), buffer, true); @@ -915,10 +912,8 @@ version (Windows) private void writeImpl(scope const(char)[] name, scope const(F * Throws: $(LREF FileException) on error. */ void rename(RF, RT)(RF from, RT to) -if ((isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) || isSomeString!RF) - && !isConvertibleToString!RF && - (isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) || isSomeString!RT) - && !isConvertibleToString!RT) +if ((isSomeFiniteCharInputRange!RF || isSomeString!RF) && !isConvertibleToString!RF && + (isSomeFiniteCharInputRange!RT || isSomeString!RT) && !isConvertibleToString!RT) { // Place outside of @trusted block auto fromz = from.tempCString!FSChar(); @@ -1027,8 +1022,7 @@ Params: Throws: $(LREF FileException) on error. */ void remove(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { static if (isNarrowString!R && is(immutable ElementEncodingType!R == immutable char)) removeImpl(name, name.tempCString!FSChar()); @@ -1082,7 +1076,7 @@ private void removeImpl(scope const(char)[] name, scope const(FSChar)* namez) @t } version (Windows) private WIN32_FILE_ATTRIBUTE_DATA getFileAttributesWin(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R)) +if (isSomeFiniteCharInputRange!R) { auto namez = name.tempCString!FSChar(); @@ -1137,8 +1131,7 @@ Throws: $(LREF FileException) on error (e.g., file not found). */ ulong getSize(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -1233,8 +1226,7 @@ private SysTime statTimeToStdTime(char which)(ref const stat_t statbuf) void getTimes(R)(R name, out SysTime accessTime, out SysTime modificationTime) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -1378,8 +1370,9 @@ version (StdDdoc) out SysTime fileCreationTime, out SysTime fileAccessTime, out SysTime fileModificationTime) - if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R); + if (isSomeFiniteCharInputRange!R || isConvertibleToString!R); + // above line contains both constraints for docs + // (so users know how it can be called) } else version (Windows) { @@ -1387,8 +1380,7 @@ else version (Windows) out SysTime fileCreationTime, out SysTime fileAccessTime, out SysTime fileModificationTime) - if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) + if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { import std.datetime.systime : FILETIMEToSysTime; @@ -1509,8 +1501,7 @@ private void setTimes(R)(R name, SysTime accessTime, SysTime modificationTime) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { auto namez = name.tempCString!FSChar(); static if (isNarrowString!R && is(immutable ElementEncodingType!R == immutable char)) @@ -1657,8 +1648,7 @@ private void setTimesImpl(scope const(char)[] names, scope const(FSChar)* namez, $(LREF FileException) if the given file does not exist. +/ SysTime timeLastModified(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -1742,7 +1732,7 @@ else -------------------- +/ SysTime timeLastModified(R)(R name, SysTime returnIfMissing) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R)) +if (isSomeFiniteCharInputRange!R) { version (Windows) { @@ -1902,8 +1892,7 @@ version (OSX) {} else * true if the file _name specified as input _exists */ bool exists(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { return existsImpl(name.tempCString!FSChar()); } @@ -2004,8 +1993,7 @@ private bool existsImpl(scope const(FSChar)* namez) @trusted nothrow @nogc Throws: $(LREF FileException) on error. +/ uint getAttributes(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -2105,8 +2093,7 @@ if (isConvertibleToString!R) $(LREF FileException) on error. +/ uint getLinkAttributes(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -2214,8 +2201,7 @@ if (isConvertibleToString!R) $(LREF FileException) if the given file does not exist. +/ void setAttributes(R)(R name, uint attributes) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -2323,8 +2309,7 @@ if (isConvertibleToString!R) $(LREF FileException) if the given file does not exist. +/ @property bool isDir(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) { @@ -2503,8 +2488,7 @@ bool attrIsDir(uint attributes) @safe pure nothrow @nogc $(LREF FileException) if the given file does not exist. +/ @property bool isFile(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) return !name.isDir; @@ -2679,8 +2663,7 @@ bool attrIsFile(uint attributes) @safe pure nothrow @nogc $(LREF FileException) if the given file does not exist. +/ @property bool isSymlink(R)(R name) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { version (Windows) return (getAttributes(name) & FILE_ATTRIBUTE_REPARSE_POINT) != 0; @@ -2860,8 +2843,7 @@ Params: Throws: $(LREF FileException) on error. */ void chdir(R)(R pathname) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { // Place outside of @trusted block auto pathz = pathname.tempCString!FSChar(); @@ -2931,8 +2913,7 @@ Throws: if an error occured. */ void mkdir(R)(R pathname) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { // Place outside of @trusted block const pathz = pathname.tempCString!FSChar(); @@ -3135,8 +3116,7 @@ Params: Throws: $(LREF FileException) on error. */ void rmdir(R)(R pathname) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) && - !isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R) { // Place outside of @trusted block auto pathz = pathname.tempCString!FSChar(); @@ -3202,15 +3182,11 @@ if (isConvertibleToString!R) exists). +/ version (StdDdoc) void symlink(RO, RL)(RO original, RL link) -if ((isInputRange!RO && !isInfinite!RO && isSomeChar!(ElementEncodingType!RO) || - isConvertibleToString!RO) && - (isInputRange!RL && !isInfinite!RL && isSomeChar!(ElementEncodingType!RL) || - isConvertibleToString!RL)); +if ((isSomeFiniteCharInputRange!RO || isConvertibleToString!RO) && + (isSomeFiniteCharInputRange!RL || isConvertibleToString!RL)); else version (Posix) void symlink(RO, RL)(RO original, RL link) -if ((isInputRange!RO && !isInfinite!RO && isSomeChar!(ElementEncodingType!RO) || - isConvertibleToString!RO) && - (isInputRange!RL && !isInfinite!RL && isSomeChar!(ElementEncodingType!RL) || - isConvertibleToString!RL)) +if ((isSomeFiniteCharInputRange!RO || isConvertibleToString!RO) && + (isSomeFiniteCharInputRange!RL || isConvertibleToString!RL)) { static if (isConvertibleToString!RO || isConvertibleToString!RL) { @@ -3291,11 +3267,9 @@ version (Posix) @safe unittest $(LREF FileException) on error. +/ version (StdDdoc) string readLink(R)(R link) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || - isConvertibleToString!R); +if (isSomeFiniteCharInputRange!R || isConvertibleToString!R); else version (Posix) string readLink(R)(R link) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) || - isConvertibleToString!R) +if (isSomeFiniteCharInputRange!R || isConvertibleToString!R) { static if (isConvertibleToString!R) { @@ -3392,7 +3366,7 @@ version (Posix) @system unittest // input range of dchars version (Windows) string getcwd() @trusted { import std.conv : to; - import std.experimental.checkedint : checked; + import std.checkedint : checked; /* GetCurrentDirectory's return value: 1. function succeeds: the number of characters that are written to the buffer, not including the terminating null character. @@ -4216,8 +4190,8 @@ Params: Throws: $(LREF FileException) on error. */ void copy(RF, RT)(RF from, RT to, PreserveAttributes preserve = preserveAttributesDefault) -if (isInputRange!RF && !isInfinite!RF && isSomeChar!(ElementEncodingType!RF) && !isConvertibleToString!RF && - isInputRange!RT && !isInfinite!RT && isSomeChar!(ElementEncodingType!RT) && !isConvertibleToString!RT) +if (isSomeFiniteCharInputRange!RF && !isConvertibleToString!RF && + isSomeFiniteCharInputRange!RT && !isConvertibleToString!RT) { // Place outside of @trusted block auto fromz = from.tempCString!FSChar(); @@ -4781,7 +4755,7 @@ private struct DirIteratorImpl } this(R)(R pathname, SpanMode mode, bool followSymlink) - if (isInputRange!R && isSomeChar!(ElementEncodingType!R)) + if (isSomeFiniteCharInputRange!R) { _mode = mode; _followSymlink = followSymlink; diff --git a/libphobos/src/std/format/package.d b/libphobos/src/std/format/package.d index 2d57e489781..6c9e9ae6004 100644 --- a/libphobos/src/std/format/package.d +++ b/libphobos/src/std/format/package.d @@ -179,10 +179,10 @@ $(BOOKTABLE , Depending on the number, a scientific notation or a natural notation is used.)) $(TR $(TD $(B 'a') / $(B 'A')) - $(TD To be formatted as a real number in hexadezimal scientific notation.)) + $(TD To be formatted as a real number in hexadecimal scientific notation.)) $(TR $(TD $(B 'r')) $(TD To be formatted as raw bytes. - The output may not be printable and depends on endianess.)) + The output may not be printable and depends on endianness.)) ) The $(I compound indicator) can be used to describe compound types diff --git a/libphobos/src/std/functional.d b/libphobos/src/std/functional.d index b251e4006ec..bc8d368e970 100644 --- a/libphobos/src/std/functional.d +++ b/libphobos/src/std/functional.d @@ -707,19 +707,43 @@ template partial(alias fun, alias arg) { static assert(false, "Cannot apply partial to a non-callable '" ~ fun.stringof ~ "'."); } - else // Assume fun is callable and uniquely defined. + else { - static if (Parameters!fun.length == 0) + import std.meta : Filter; + + static if (__traits(compiles, __traits(getOverloads, + __traits(parent, fun), __traits(identifier, fun)))) + alias overloads = __traits(getOverloads, __traits(parent, fun), + __traits(identifier, fun)); + else + alias overloads = AliasSeq!(fun); + + enum isCallableWithArg(alias fun) = Parameters!fun.length > 0 && + is(typeof(arg) : Parameters!fun[0]); + alias candidates = Filter!(isCallableWithArg, overloads); + + static if (overloads.length == 1 && Parameters!fun.length == 0) { static assert(0, "Cannot partially apply '" ~ fun.stringof ~ "'." ~ "'" ~ fun.stringof ~ "' has 0 arguments."); } - else static if (!is(typeof(arg) : Parameters!fun[0])) + else static if (candidates.length == 0) { + import std.meta : NoDuplicates, staticMap; + + enum hasParameters(alias fun) = Parameters!fun.length > 0; + alias firstParameter(alias fun) = Parameters!fun[0]; + alias firstParameters = NoDuplicates!( + staticMap!(firstParameter, Filter!(hasParameters, overloads))); + string errorMsg() { - string msg = "Argument mismatch for '" ~ fun.stringof ~ "': expected " ~ - Parameters!fun[0].stringof ~ ", but got " ~ typeof(arg).stringof ~ "."; + string msg = "Argument mismatch for '" ~ fun.stringof ~ + "': expected " ~ firstParameters[0].stringof; + static foreach (firstParam; firstParameters[1 .. $]) + msg ~= " or " ~ firstParam.stringof; + msg ~= ", but got " ~ typeof(arg).stringof ~ "."; + return msg; } static assert(0, errorMsg()); @@ -727,10 +751,11 @@ template partial(alias fun, alias arg) else { import std.traits : ReturnType; - ReturnType!fun partial(Parameters!fun[1..$] args2) - { - return fun(arg, args2); - } + static foreach (candidate; candidates) + ReturnType!candidate partial(Parameters!candidate[1..$] args2) + { + return candidate(arg, args2); + } } } } @@ -746,6 +771,22 @@ template partial(alias fun, alias arg) // functions without committing to a particular type of the function. } +// https://issues.dlang.org/show_bug.cgi?id=21457 +/// +@safe unittest +{ + // Overloads are resolved when the partially applied function is called + // with the remaining arguments. + struct S + { + static char fun(int i, string s) { return s[i]; } + static int fun(int a, int b) { return a * b; } + } + alias fun3 = partial!(S.fun, 3); + assert(fun3("hello") == 'l'); + assert(fun3(10) == 30); +} + // tests for partially evaluating callables @safe unittest { diff --git a/libphobos/src/std/json.d b/libphobos/src/std/json.d index ea22d635766..89def0f02f5 100644 --- a/libphobos/src/std/json.d +++ b/libphobos/src/std/json.d @@ -19,7 +19,7 @@ module std.json; import std.array; import std.conv; -import std.range.primitives; +import std.range; import std.traits; /// @@ -929,7 +929,7 @@ Params: options = enable decoding string representations of NaN/Inf as float values */ JSONValue parseJSON(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none) -if (isInputRange!T && !isInfinite!T && isSomeChar!(ElementEncodingType!T)) +if (isSomeFiniteCharInputRange!T) { import std.ascii : isDigit, isHexDigit, toUpper, toLower; import std.typecons : Nullable, Yes; @@ -1437,7 +1437,7 @@ Params: options = enable decoding string representations of NaN/Inf as float values */ JSONValue parseJSON(T)(T json, JSONOptions options) -if (isInputRange!T && !isInfinite!T && isSomeChar!(ElementEncodingType!T)) +if (isSomeFiniteCharInputRange!T) { return parseJSON!T(json, -1, options); } diff --git a/libphobos/src/std/path.d b/libphobos/src/std/path.d index 2d64684b4a2..20518b86333 100644 --- a/libphobos/src/std/path.d +++ b/libphobos/src/std/path.d @@ -98,7 +98,7 @@ module std.path; import std.file : getcwd; static import std.meta; -import std.range.primitives; +import std.range; import std.traits; version (OSX) @@ -262,8 +262,7 @@ version (Windows) from a path. */ private auto ltrimDirSeparators(R)(R path) -if (isInputRange!R && !isInfinite!R && isSomeChar!(ElementType!R) || - isNarrowString!R) +if (isSomeFiniteCharInputRange!R || isNarrowString!R) { static if (isRandomAccessRange!R && hasSlicing!R || isNarrowString!R) { @@ -3213,12 +3212,8 @@ int filenameCharCmp(CaseSensitive cs = CaseSensitive.osDefault)(dchar a, dchar b */ int filenameCmp(CaseSensitive cs = CaseSensitive.osDefault, Range1, Range2) (Range1 filename1, Range2 filename2) -if (isInputRange!Range1 && !isInfinite!Range1 && - isSomeChar!(ElementEncodingType!Range1) && - !isConvertibleToString!Range1 && - isInputRange!Range2 && !isInfinite!Range2 && - isSomeChar!(ElementEncodingType!Range2) && - !isConvertibleToString!Range2) +if (isSomeFiniteCharInputRange!Range1 && !isConvertibleToString!Range1 && + isSomeFiniteCharInputRange!Range2 && !isConvertibleToString!Range2) { alias C1 = Unqual!(ElementEncodingType!Range1); alias C2 = Unqual!(ElementEncodingType!Range2); diff --git a/libphobos/src/std/process.d b/libphobos/src/std/process.d index 958f606ff52..2c68f36b4e7 100644 --- a/libphobos/src/std/process.d +++ b/libphobos/src/std/process.d @@ -106,9 +106,8 @@ version (Windows) } import std.internal.cstring; -import std.range.primitives; +import std.range; import std.stdio; -import std.traits : isSomeChar; version (OSX) version = Darwin; @@ -1527,7 +1526,7 @@ package(std) string searchPathFor(scope const(char)[] executable) // current user. version (Posix) private bool isExecutable(R)(R path) @trusted nothrow @nogc -if (isInputRange!R && isSomeChar!(ElementEncodingType!R)) +if (isSomeFiniteCharInputRange!R) { return (access(path.tempCString(), X_OK) == 0); } diff --git a/libphobos/src/std/range/package.d b/libphobos/src/std/range/package.d index a21f4d01745..91971342d9a 100644 --- a/libphobos/src/std/range/package.d +++ b/libphobos/src/std/range/package.d @@ -235,7 +235,7 @@ public import std.range.primitives; public import std.typecons : Flag, Yes, No; import std.internal.attributes : betterC; -import std.meta : allSatisfy, staticMap; +import std.meta : allSatisfy, anySatisfy, staticMap; import std.traits : CommonType, isCallable, isFloatingPoint, isIntegral, isPointer, isSomeFunction, isStaticArray, Unqual, isInstanceOf; @@ -1412,7 +1412,8 @@ auto choose(R1, R2)(bool condition, return scope R1 r1, return scope R2 r2) if (isInputRange!(Unqual!R1) && isInputRange!(Unqual!R2) && !is(CommonType!(ElementType!(Unqual!R1), ElementType!(Unqual!R2)) == void)) { - return ChooseResult!(R1, R2)(condition, r1, r2); + size_t choice = condition? 0: 1; + return ChooseResult!(R1, R2)(choice, r1, r2); } /// @@ -1447,76 +1448,102 @@ if (isInputRange!(Unqual!R1) && isInputRange!(Unqual!R2) && } -private struct ChooseResult(R1, R2) +private struct ChooseResult(Ranges...) { - import std.traits : hasElaborateCopyConstructor, hasElaborateDestructor; + import std.meta : aliasSeqOf, ApplyLeft; + import std.traits : hasElaborateCopyConstructor, hasElaborateDestructor, + lvalueOf; private union { - R1 r1; - R2 r2; + Ranges rs; } - private bool r1Chosen; + private size_t chosenI; - private static auto ref actOnChosen(alias foo, ExtraArgs ...)(ref ChooseResult r, - auto ref ExtraArgs extraArgs) + private static auto ref actOnChosen(alias foo, ExtraArgs ...) + (ref ChooseResult r, auto ref ExtraArgs extraArgs) { - if (r.r1Chosen) - { - ref get1(return ref ChooseResult r) @trusted { return r.r1; } - return foo(get1(r), extraArgs); - } - else + ref getI(size_t i)(return ref ChooseResult r) @trusted { return r.rs[i]; } + + switch (r.chosenI) { - ref get2(return ref ChooseResult r) @trusted { return r.r2; } - return foo(get2(r), extraArgs); + static foreach (candI; 0 .. rs.length) + { + case candI: return foo(getI!candI(r), extraArgs); + } + + default: assert(false); } } - this(bool r1Chosen, return scope R1 r1, return scope R2 r2) @trusted + // @trusted because of assignment of r which overlap each other + this(size_t chosen, return scope Ranges rs) @trusted { - // @trusted because of assignment of r1 and r2 which overlap each other import core.lifetime : emplace; - // This should be the only place r1Chosen is ever assigned + // This should be the only place chosenI is ever assigned // independently - this.r1Chosen = r1Chosen; - if (r1Chosen) + this.chosenI = chosen; + + // Otherwise the compiler will complain about skipping these fields + static foreach (i; 0 .. rs.length) { - this.r2 = R2.init; - emplace(&this.r1, r1); + this.rs[i] = Ranges[i].init; } - else + + // The relevant field needs to be initialized last so it will overwrite + // the other initializations and not the other way around. + sw: switch (chosenI) { - this.r1 = R1.init; - emplace(&this.r2, r2); + static foreach (i; 0 .. rs.length) + { + case i: + emplace(&this.rs[i], rs[i]); + break sw; + } + + default: assert(false); } } + // Some legacy code may still call this with typeof(choose(/*...*/))(/*...*/) + // without this overload the regular constructor would invert the meaning of + // the boolean + static if (rs.length == 2) + pragma(inline, true) + deprecated("Call with size_t (0 = first), or use the choose function") + this(bool firstChosen, Ranges rs) + { + import core.lifetime : move; + this(cast(size_t)(firstChosen? 0: 1), rs[0].move, rs[1].move); + } + void opAssign(ChooseResult r) { - static if (hasElaborateDestructor!R1 || hasElaborateDestructor!R2) - if (r1Chosen != r.r1Chosen) - { - // destroy the current item - actOnChosen!((ref r) => destroy(r))(this); - } - r1Chosen = r.r1Chosen; - if (r1Chosen) + ref getI(size_t i)(return ref ChooseResult r) @trusted { return r.rs[i]; } + + static if (anySatisfy!(hasElaborateDestructor, Ranges)) + if (chosenI != r.chosenI) { - ref get1(return ref ChooseResult r) @trusted { return r.r1; } - get1(this) = get1(r); + // destroy the current item + actOnChosen!((ref r) => destroy(r))(this); } - else + chosenI = r.chosenI; + + sw: switch (chosenI) { - ref get2(return ref ChooseResult r) @trusted { return r.r2; } - get2(this) = get2(r); + static foreach (candI; 0 .. rs.length) + { + case candI: getI!candI(this) = getI!candI(r); + break sw; + } + + default: assert(false); } } // Carefully defined postblit to postblit the appropriate range - static if (hasElaborateCopyConstructor!R1 - || hasElaborateCopyConstructor!R2) + static if (anySatisfy!(hasElaborateCopyConstructor, Ranges)) this(this) { actOnChosen!((ref r) { @@ -1524,20 +1551,18 @@ private struct ChooseResult(R1, R2) })(this); } - static if (hasElaborateDestructor!R1 || hasElaborateDestructor!R2) + static if (anySatisfy!(hasElaborateDestructor, Ranges)) ~this() { actOnChosen!((ref r) => destroy(r))(this); } - static if (isInfinite!R1 && isInfinite!R2) - // Propagate infiniteness. - enum bool empty = false; - else - @property bool empty() - { - return actOnChosen!(r => r.empty)(this); - } + // Propagate infiniteness. + static if (allSatisfy!(isInfinite, Ranges)) enum bool empty = false; + else @property bool empty() + { + return actOnChosen!(r => r.empty)(this); + } @property auto ref front() { @@ -1550,34 +1575,38 @@ private struct ChooseResult(R1, R2) return actOnChosen!((ref r) { r.popFront; })(this); } - static if (isForwardRange!R1 && isForwardRange!R2) - @property auto save() return scope + static if (allSatisfy!(isForwardRange, Ranges)) + @property auto save() // return scope inferred { - if (r1Chosen) + auto saveOrInit(size_t i)() { - ref R1 getR1() @trusted { return r1; } - return ChooseResult(r1Chosen, getR1.save, R2.init); - } - else - { - ref R2 getR2() @trusted { return r2; } - return ChooseResult(r1Chosen, R1.init, getR2.save); + ref getI() @trusted { return rs[i]; } + if (i == chosenI) return getI().save; + else return Ranges[i].init; } + + return typeof(this)(chosenI, staticMap!(saveOrInit, + aliasSeqOf!(rs.length.iota))); } - @property void front(T)(T v) - if (is(typeof({ r1.front = v; r2.front = v; }))) + template front(T) { - actOnChosen!((ref r, T v) { r.front = v; })(this, v); - } + private enum overloadValidFor(alias r) = is(typeof(r.front = T.init)); - static if (hasMobileElements!R1 && hasMobileElements!R2) - auto moveFront() + static if (allSatisfy!(overloadValidFor, rs)) + void front(T v) { - return actOnChosen!((ref r) => r.moveFront)(this); + actOnChosen!((ref r, T v) { r.front = v; })(this, v); } + } - static if (isBidirectionalRange!R1 && isBidirectionalRange!R2) + static if (allSatisfy!(hasMobileElements, Ranges)) + auto moveFront() + { + return actOnChosen!((ref r) => r.moveFront)(this); + } + + static if (allSatisfy!(isBidirectionalRange, Ranges)) { @property auto ref back() { @@ -1590,20 +1619,25 @@ private struct ChooseResult(R1, R2) actOnChosen!((ref r) { r.popBack; })(this); } - static if (hasMobileElements!R1 && hasMobileElements!R2) - auto moveBack() - { - return actOnChosen!((ref r) => r.moveBack)(this); - } + static if (allSatisfy!(hasMobileElements, Ranges)) + auto moveBack() + { + return actOnChosen!((ref r) => r.moveBack)(this); + } - @property void back(T)(T v) - if (is(typeof({ r1.back = v; r2.back = v; }))) + template back(T) { - actOnChosen!((ref r, T v) { r.back = v; })(this, v); + private enum overloadValidFor(alias r) = is(typeof(r.back = T.init)); + + static if (allSatisfy!(overloadValidFor, rs)) + void back(T v) + { + actOnChosen!((ref r, T v) { r.back = v; })(this, v); + } } } - static if (hasLength!R1 && hasLength!R2) + static if (allSatisfy!(hasLength, Ranges)) { @property size_t length() { @@ -1612,7 +1646,7 @@ private struct ChooseResult(R1, R2) alias opDollar = length; } - static if (isRandomAccessRange!R1 && isRandomAccessRange!R2) + static if (allSatisfy!(isRandomAccessRange, Ranges)) { auto ref opIndex(size_t index) { @@ -1620,33 +1654,41 @@ private struct ChooseResult(R1, R2) return actOnChosen!get(this, index); } - static if (hasMobileElements!R1 && hasMobileElements!R2) + static if (allSatisfy!(hasMobileElements, Ranges)) auto moveAt(size_t index) { return actOnChosen!((ref r, size_t index) => r.moveAt(index)) (this, index); } - void opIndexAssign(T)(T v, size_t index) - if (is(typeof({ r1[1] = v; r2[1] = v; }))) + private enum indexAssignable(T, R) = is(typeof(lvalueOf!R[1] = T.init)); + + template opIndexAssign(T) + if (allSatisfy!(ApplyLeft!(indexAssignable, T), Ranges)) { - return actOnChosen!((ref r, size_t index, T v) { r[index] = v; }) - (this, index, v); + void opIndexAssign(T v, size_t index) + { + return actOnChosen!((ref r, size_t index, T v) { r[index] = v; }) + (this, index, v); + } } } - static if (hasSlicing!R1 && hasSlicing!R2) - auto opSlice(size_t begin, size_t end) + static if (allSatisfy!(hasSlicing, Ranges)) + auto opSlice(size_t begin, size_t end) + { + alias Slice(R) = typeof(R.init[0 .. 1]); + alias Slices = staticMap!(Slice, Ranges); + + auto sliceOrInit(size_t i)() { - alias Slice1 = typeof(R1.init[0 .. 1]); - alias Slice2 = typeof(R2.init[0 .. 1]); - return actOnChosen!((r, size_t begin, size_t end) { - static if (is(typeof(r) == Slice1)) - return choose(true, r[begin .. end], Slice2.init); - else - return choose(false, Slice1.init, r[begin .. end]); - })(this, begin, end); + ref getI() @trusted { return rs[i]; } + return i == chosenI? getI()[begin .. end]: Slices[i].init; } + + return chooseAmong(chosenI, staticMap!(sliceOrInit, + aliasSeqOf!(rs.length.iota))); + } } // https://issues.dlang.org/show_bug.cgi?id=18657 @@ -1668,8 +1710,9 @@ pure @safe unittest int front; bool empty; void popFront() {} - @property R save() { p = q; return this; } - // `p = q;` is only there to prevent inference of `scope return`. + // `p = q;` is only there to prevent inference of `scope return`. + @property @safe R save() { p = q; return this; } + } R r; choose(true, r, r).save; @@ -1801,10 +1844,7 @@ if (Ranges.length >= 2 && allSatisfy!(isInputRange, staticMap!(Unqual, Ranges)) && !is(CommonType!(staticMap!(ElementType, Ranges)) == void)) { - static if (Ranges.length == 2) - return choose(index == 0, rs[0], rs[1]); - else - return choose(index == 0, rs[0], chooseAmong(index - 1, rs[1 .. $])); + return ChooseResult!Ranges(index, rs); } /// @@ -13521,3 +13561,49 @@ pure @safe unittest assert([1, 2, 3, 4].padRight(0, 10)[7 .. 9].equal([0, 0])); } + +/** +This simplifies a commonly used idiom in phobos for accepting any kind of string +parameter. The type `R` can for example be a simple string, chained string using +$(REF chain, std,range), $(REF chainPath, std,path) or any other input range of +characters. + +Only finite length character ranges are allowed with this constraint. + +This template is equivalent to: +--- +isInputRange!R && !isInfinite!R && isSomeChar!(ElementEncodingType!R) +--- + +See_Also: +$(REF isInputRange, std,range,primitives), +$(REF isInfinite, std,range,primitives), +$(LREF isSomeChar), +$(REF ElementEncodingType, std,range,primitives) +*/ +template isSomeFiniteCharInputRange(R) +{ + import std.traits : isSomeChar; + + enum isSomeFiniteCharInputRange = isInputRange!R && !isInfinite!R + && isSomeChar!(ElementEncodingType!R); +} + +/// +@safe unittest +{ + import std.path : chainPath; + import std.range : chain; + + void someLibraryMethod(R)(R argument) + if (isSomeFiniteCharInputRange!R) + { + // implementation detail, would iterate over each character of argument + } + + someLibraryMethod("simple strings work"); + someLibraryMethod(chain("chained", " ", "strings", " ", "work")); + someLibraryMethod(chainPath("chained", "paths", "work")); + // you can also use custom structs implementing a char range +} + diff --git a/libphobos/src/std/regex/package.d b/libphobos/src/std/regex/package.d index 8db0b1e1f59..e24abc50a07 100644 --- a/libphobos/src/std/regex/package.d +++ b/libphobos/src/std/regex/package.d @@ -170,6 +170,10 @@ $(TR $(TD Objects) $(TD Greedy version - tries as many times as possible.) $(REG_ROW +?, Matches previous character/subexpression 1 or more times. Lazy version - stops as early as possible.) + $(REG_ROW ?, Matches previous character/subexpression 0 or 1 time. + Greedy version - tries as many times as possible.) + $(REG_ROW ??, Matches previous character/subexpression 0 or 1 time. + Lazy version - stops as early as possible.) $(REG_ROW {n}, Matches previous character/subexpression exactly n times. ) $(REG_ROW {n$(COMMA)}, Matches previous character/subexpression n times or more. Greedy version - tries as many times as possible. ) @@ -1745,3 +1749,9 @@ auto escaper(Range)(Range r) assert(s2.escaper.equal("")); }} } + +@system unittest +{ + assert("ab".matchFirst(regex(`a?b?`)).hit == "ab"); + assert("ab".matchFirst(regex(`a??b?`)).hit == ""); +} diff --git a/libphobos/src/std/stdio.d b/libphobos/src/std/stdio.d index f30ea80ae44..bc2d3fe4210 100644 --- a/libphobos/src/std/stdio.d +++ b/libphobos/src/std/stdio.d @@ -50,8 +50,8 @@ import core.stdc.stddef : wchar_t; public import core.stdc.stdio; import std.algorithm.mutation : copy; import std.meta : allSatisfy; -import std.range.primitives : ElementEncodingType, empty, front, - isBidirectionalRange, isInputRange, put; +import std.range : ElementEncodingType, empty, front, isBidirectionalRange, + isInputRange, isSomeFiniteCharInputRange, put; import std.traits : isSomeChar, isSomeString, Unqual, isPointer; import std.typecons : Flag, No, Yes; @@ -555,7 +555,7 @@ Throws: `ErrnoException` if the file could not be opened. /// ditto this(R1, R2)(R1 name) - if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1)) + if (isSomeFiniteCharInputRange!R1) { import std.conv : to; this(name.to!string, "rb"); @@ -563,8 +563,8 @@ Throws: `ErrnoException` if the file could not be opened. /// ditto this(R1, R2)(R1 name, R2 mode) - if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) && - isInputRange!R2 && isSomeChar!(ElementEncodingType!R2)) + if (isSomeFiniteCharInputRange!R1 && + isSomeFiniteCharInputRange!R2) { import std.conv : to; this(name.to!string, mode.to!string); @@ -957,7 +957,7 @@ Throws: `Exception` if the file is not opened. } /** -If the file is not opened, returns `true`. Otherwise, returns +If the file is closed or not yet opened, returns `true`. Otherwise, returns $(HTTP cplusplus.com/reference/clibrary/cstdio/ferror.html, ferror) for the file handle. */ @@ -1013,8 +1013,8 @@ Throws: `ErrnoException` on failure if closing the file. } /** -If the file was unopened, succeeds vacuously. Otherwise closes the -file (by calling $(HTTP +If the file was closed or not yet opened, succeeds vacuously. Otherwise +closes the file (by calling $(HTTP cplusplus.com/reference/clibrary/cstdio/fclose.html, fclose)), throwing on error. Even if an exception is thrown, afterwards the $(D File) object is empty. This is different from `detach` in that it @@ -1042,7 +1042,7 @@ Throws: `ErrnoException` on error. } /** -If the file is not opened, succeeds vacuously. Otherwise, returns +If the file is closed or not yet opened, succeeds vacuously. Otherwise, returns $(HTTP cplusplus.com/reference/clibrary/cstdio/_clearerr.html, _clearerr) for the file handle. */ @@ -4642,8 +4642,8 @@ if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && * with appropriately-constructed C-style strings. */ private FILE* _fopen(R1, R2)(R1 name, R2 mode = "r") -if ((isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) || isSomeString!R1) && - (isInputRange!R2 && isSomeChar!(ElementEncodingType!R2) || isSomeString!R2)) +if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) && + (isSomeFiniteCharInputRange!R2 || isSomeString!R2)) { import std.internal.cstring : tempCString; @@ -4684,8 +4684,8 @@ version (Posix) * with appropriately-constructed C-style strings. */ FILE* _popen(R1, R2)(R1 name, R2 mode = "r") @trusted nothrow @nogc - if ((isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) || isSomeString!R1) && - (isInputRange!R2 && isSomeChar!(ElementEncodingType!R2) || isSomeString!R2)) + if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) && + (isSomeFiniteCharInputRange!R2 || isSomeString!R2)) { import std.internal.cstring : tempCString; diff --git a/libphobos/src/std/traits.d b/libphobos/src/std/traits.d index c1d6bc97402..596c11cfb00 100644 --- a/libphobos/src/std/traits.d +++ b/libphobos/src/std/traits.d @@ -5195,16 +5195,54 @@ enum isAssignable(Lhs, Rhs = Lhs) = isRvalueAssignable!(Lhs, Rhs) && isLvalueAss /** Returns `true` iff an rvalue of type `Rhs` can be assigned to a variable of -type `Lhs` +type `Lhs`. */ enum isRvalueAssignable(Lhs, Rhs = Lhs) = __traits(compiles, { lvalueOf!Lhs = rvalueOf!Rhs; }); +/// +@safe unittest +{ + struct S1 + { + void opAssign(S1); + } + + struct S2 + { + void opAssign(ref S2); + } + + static assert( isRvalueAssignable!(long, int)); + static assert(!isRvalueAssignable!(int, long)); + static assert( isRvalueAssignable!S1); + static assert(!isRvalueAssignable!S2); +} + /** Returns `true` iff an lvalue of type `Rhs` can be assigned to a variable of -type `Lhs` +type `Lhs`. */ enum isLvalueAssignable(Lhs, Rhs = Lhs) = __traits(compiles, { lvalueOf!Lhs = lvalueOf!Rhs; }); +/// +@safe unittest +{ + struct S1 + { + void opAssign(S1); + } + + struct S2 + { + void opAssign(ref S2); + } + + static assert( isLvalueAssignable!(long, int)); + static assert(!isLvalueAssignable!(int, long)); + static assert( isLvalueAssignable!S1); + static assert( isLvalueAssignable!S2); +} + @safe unittest { static assert(!isAssignable!(immutable int, int)); @@ -6095,7 +6133,7 @@ template BuiltinTypeOf(T) alias X = OriginalType!T; static if (__traits(isArithmetic, X) && !is(X == __vector) || __traits(isStaticArray, X) || is(X == E[], E) || - __traits(isAssociativeArray, X)) + __traits(isAssociativeArray, X) || is(X == typeof(null))) alias BuiltinTypeOf = X; else static assert(0); @@ -6117,7 +6155,13 @@ enum bool isBoolean(T) = __traits(isUnsigned, T) && is(T : bool); static assert( isBoolean!bool); enum EB : bool { a = true } static assert( isBoolean!EB); - static assert(!isBoolean!(SubTypeOf!bool)); + + struct SubTypeOfBool + { + bool val; + alias val this; + } + static assert(!isBoolean!(SubTypeOfBool)); } @safe unittest @@ -6994,6 +7038,18 @@ enum bool isArray(T) = isStaticArray!T || isDynamicArray!T; */ enum bool isAssociativeArray(T) = __traits(isAssociativeArray, T); +/// +@safe unittest +{ + struct S; + + static assert( isAssociativeArray!(int[string])); + static assert( isAssociativeArray!(S[S])); + static assert(!isAssociativeArray!(string[])); + static assert(!isAssociativeArray!S); + static assert(!isAssociativeArray!(int[4])); +} + @safe unittest { struct Foo @@ -7037,6 +7093,7 @@ enum bool isBuiltinType(T) = is(BuiltinTypeOf!T) && !isAggregateType!T; static assert( isBuiltinType!string); static assert( isBuiltinType!(int[])); static assert( isBuiltinType!(C[string])); + static assert( isBuiltinType!(typeof(null))); static assert(!isBuiltinType!C); static assert(!isBuiltinType!U); static assert(!isBuiltinType!S); @@ -7049,6 +7106,7 @@ enum bool isBuiltinType(T) = is(BuiltinTypeOf!T) && !isAggregateType!T; */ enum bool isSIMDVector(T) = is(T : __vector(V[N]), V, size_t N); +/// @safe unittest { static if (is(__vector(float[4]))) @@ -7066,6 +7124,20 @@ enum bool isSIMDVector(T) = is(T : __vector(V[N]), V, size_t N); */ enum bool isPointer(T) = is(T == U*, U) && __traits(isScalar, T); +/// +@safe unittest +{ + void fun(); + + static assert( isPointer!(int*)); + static assert( isPointer!(int function())); + static assert(!isPointer!int); + static assert(!isPointer!string); + static assert(!isPointer!(typeof(null))); + static assert(!isPointer!(typeof(fun))); + static assert(!isPointer!(int delegate())); +} + @safe unittest { static foreach (T; AliasSeq!(int*, void*, char[]*)) @@ -8835,6 +8907,27 @@ enum bool allSameType(Ts...) = */ enum ifTestable(T, alias pred = a => a) = __traits(compiles, { if (pred(T.init)) {} }); +/// +@safe unittest +{ + class C; + struct S1; + struct S2 + { + T opCast(T)() const; + } + + static assert( ifTestable!bool); + static assert( ifTestable!int); + static assert( ifTestable!(S1*)); + static assert( ifTestable!(typeof(null))); + static assert( ifTestable!(int[])); + static assert( ifTestable!(int[string])); + static assert( ifTestable!S2); + static assert( ifTestable!C); + static assert(!ifTestable!S1); +} + @safe unittest { import std.meta : AliasSeq, allSatisfy; diff --git a/libphobos/src/std/typecons.d b/libphobos/src/std/typecons.d index cde2b9da055..28edb9b8c29 100644 --- a/libphobos/src/std/typecons.d +++ b/libphobos/src/std/typecons.d @@ -76,36 +76,42 @@ import std.range.primitives : isOutputRange; import std.traits; import std.internal.attributes : betterC; -/// +/// Value tuples @safe unittest { - // value tuples alias Coord = Tuple!(int, "x", int, "y", int, "z"); Coord c; c[1] = 1; // access by index c.z = 1; // access by given name assert(c == Coord(0, 1, 1)); - // names can be omitted - alias DicEntry = Tuple!(string, string); + // names can be omitted, types can be mixed + alias DictEntry = Tuple!(string, int); + auto dict = DictEntry("seven", 7); - // tuples can also be constructed on instantiation + // element types can be inferred assert(tuple(2, 3, 4)[1] == 3); - // construction on instantiation works with names too - assert(tuple!("x", "y", "z")(2, 3, 4).y == 3); + // type inference works with names too + auto tup = tuple!("x", "y", "z")(2, 3, 4); + assert(tup.y == 3); +} - // Rebindable references to const and immutable objects +/// Rebindable references to const and immutable objects +@safe unittest +{ + class Widget { - class Widget { void foo() const @safe {} } - const w1 = new Widget, w2 = new Widget; - w1.foo(); - // w1 = w2 would not work; can't rebind const object - auto r = Rebindable!(const Widget)(w1); - // invoke method as if r were a Widget object - r.foo(); - // rebind r to refer to another object - r = w2; + void foo() const @safe {} } + const w1 = new Widget, w2 = new Widget; + w1.foo(); + // w1 = w2 would not work; can't rebind const object + + auto r = Rebindable!(const Widget)(w1); + // invoke method as if r were a Widget object + r.foo(); + // rebind r to refer to another object + r = w2; } /** @@ -4036,7 +4042,7 @@ template apply(alias fun) import std.functional : unaryFun; auto apply(T)(auto ref T t) - if (isInstanceOf!(Nullable, T) && is(typeof(unaryFun!fun(T.init.get)))) + if (isInstanceOf!(Nullable, T)) { alias FunType = typeof(unaryFun!fun(T.init.get)); @@ -5107,6 +5113,46 @@ private static: static abstract class C_9 : K {} auto o = new BlackHole!C_9; }+/ + // test `parent` alias + { + interface I_11 + { + void simple(int) @safe; + int anotherSimple(string); + int overloaded(int); + /+ XXX [BUG 19715] + void overloaded(string) @safe; + +/ + } + + static class C_11 + { + import std.traits : Parameters, ReturnType; + import std.meta : Alias; + + protected ReturnType!fn _impl(alias fn)(Parameters!fn) + if (is(Alias!(__traits(parent, fn)) == interface)) + { + static if (!is(typeof(return) == void)) + return typeof(return).init; + } + } + + template tpl(I, alias fn) + if (is(I == interface) && __traits(isSame, __traits(parent, fn), I)) + { + enum string tpl = q{ + enum bool haveReturn = !is(typeof(return) == void); + + static if (is(typeof(return) == void)) + _impl!parent(args); + else + return _impl!parent(args); + }; + } + + auto o = new AutoImplement!(I_11, C_11, tpl); + } } // https://issues.dlang.org/show_bug.cgi?id=17177 @@ -5188,6 +5234,7 @@ version (StdUnittest) void bar(int a) { } } } + @system unittest { auto foo = new issue10647_DoNothing!issue10647_Foo(); @@ -5424,8 +5471,8 @@ private static: if (!isCtor) { preamble ~= "alias self = " ~ name ~ ";\n"; - if (WITH_BASE_CLASS && !__traits(isAbstractFunction, func)) - preamble ~= `alias parent = __traits(getMember, super, "` ~ name ~ `");`; + static if (WITH_BASE_CLASS) + preamble ~= `alias parent = __traits(getMember, ` ~ Policy.BASE_CLASS_ID ~ `, "` ~ name ~ `");`; } // Function body diff --git a/libphobos/src/std/utf.d b/libphobos/src/std/utf.d index a29025a179a..5c23684b9ae 100644 --- a/libphobos/src/std/utf.d +++ b/libphobos/src/std/utf.d @@ -65,9 +65,9 @@ module std.utf; import std.exception : basicExceptionCtors; import core.exception : UnicodeException; import std.meta : AliasSeq; -import std.range.primitives; -import std.traits : isAutodecodableString, isPointer, isSomeChar, - isSomeString, isStaticArray, Unqual, isConvertibleToString; +import std.range; +import std.traits : isAutodecodableString, isConvertibleToString, isPointer, + isSomeChar, isSomeString, isStaticArray, Unqual; import std.typecons : Flag, Yes, No; @@ -2809,7 +2809,7 @@ if (isSomeChar!C) The number of code units in `input` when encoded to `C` +/ size_t codeLength(C, InputRange)(InputRange input) -if (isInputRange!InputRange && !isInfinite!InputRange && isSomeChar!(ElementType!InputRange)) +if (isSomeFiniteCharInputRange!InputRange) { alias EncType = Unqual!(ElementEncodingType!InputRange); static if (isSomeString!InputRange && is(EncType == C) && is(typeof(input.length))) @@ -2961,7 +2961,7 @@ if (isSomeString!S) * For a lazy, non-allocating version of these functions, see $(LREF byUTF). */ string toUTF8(S)(S s) -if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)) +if (isSomeFiniteCharInputRange!S) { return toUTFImpl!string(s); } @@ -3003,7 +3003,7 @@ if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)) * For a lazy, non-allocating version of these functions, see $(LREF byUTF). */ wstring toUTF16(S)(S s) -if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)) +if (isSomeFiniteCharInputRange!S) { return toUTFImpl!wstring(s); } @@ -3047,7 +3047,7 @@ if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)) * For a lazy, non-allocating version of these functions, see $(LREF byUTF). */ dstring toUTF32(S)(scope S s) -if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S)) +if (isSomeFiniteCharInputRange!S) { return toUTFImpl!dstring(s); } diff --git a/libphobos/src/std/variant.d b/libphobos/src/std/variant.d index ce635fb9b34..41cd4848b12 100644 --- a/libphobos/src/std/variant.d +++ b/libphobos/src/std/variant.d @@ -472,6 +472,20 @@ private: auto rhsPA = getPtr(&temp.store); return compare(rhsPA, zis, selector); } + // Generate the function below only if the Variant's type is + // comparable with 'null' + static if (__traits(compiles, () => A.init == null)) + { + if (rhsType == typeid(null)) + { + // if rhsType is typeof(null), then we're comparing with 'null' + // this takes into account 'opEquals' and 'opCmp' + // all types that can compare with null have to following properties: + // if it's 'null' then it's equal to null, otherwise it's always greater + // than 'null' + return *zis == null ? 0 : 1; + } + } return ptrdiff_t.min; // dunno case OpID.toString: auto target = cast(string*) parm; @@ -1608,6 +1622,42 @@ pure nothrow @nogc assert(v != b); } +// https://issues.dlang.org/show_bug.cgi?id=22647 +// Can compare with 'null' +@system unittest +{ + static struct Bar + { + int* ptr; + alias ptr this; + } + + static class Foo {} + int* iptr; + int[] arr; + + Variant v = Foo.init; // 'null' + assert(v != null); // can only compare objects with 'null' by using 'is' + + v = iptr; + assert(v == null); // pointers can be compared with 'null' + + v = arr; + assert(v == null); // arrays can be compared with 'null' + + v = ""; + assert(v == null); // strings are arrays, an empty string is considered 'null' + + v = Bar.init; + assert(v == null); // works with alias this + + v = [3]; + assert(v != null); + assert(v > null); + assert(v >= null); + assert(!(v < null)); +} + /** _Algebraic data type restricted to a closed set of possible types. It's an alias for $(LREF VariantN) with an @@ -2052,10 +2102,10 @@ static class VariantException : Exception assert(v == 2); assert(v < 3); - static assert(!__traits(compiles, {v == long.max;})); - static assert(!__traits(compiles, {v == null;})); - static assert(!__traits(compiles, {v < long.max;})); - static assert(!__traits(compiles, {v > null;})); + static assert(!__traits(compiles, () => v == long.max)); + static assert(!__traits(compiles, () => v == null)); + static assert(!__traits(compiles, () => v < long.max)); + static assert(!__traits(compiles, () => v > null)); } // https://issues.dlang.org/show_bug.cgi?id=1558 |