strex: added `detectUrl()`
[iv.d.git] / bclamp.d
blobfbae113618529bbac31c2e9eed18968b0dbe587a
1 /* Invisible Vector Library
2 * coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
3 * Understanding is not required. Only obedience.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License ONLY.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 // just `clampToByte()`, so i can easily find and copypaste it
18 module iv.bclamp /*is aliced*/;
21 // this is actually branch-less for ints on x86, and even for longs on x86_64
22 ubyte clampToByte(T) (T n) pure nothrow @safe @nogc if (__traits(isIntegral, T)) {
23 pragma(inline, true);
24 static if (T.sizeof == 2 || T.sizeof == 4) {
25 static if (__traits(isUnsigned, T)) {
26 return cast(ubyte)(n&0xff|(255-((-cast(int)(n < 256))>>24)));
27 } else {
28 n &= -cast(int)(n >= 0);
29 return cast(ubyte)(n|((255-cast(int)n)>>31));
31 } else static if (T.sizeof == 1) {
32 static assert(__traits(isUnsigned, T), "clampToByte: signed byte? no, really?");
33 return cast(ubyte)n;
34 } else static if (T.sizeof == 8) {
35 static if (__traits(isUnsigned, T)) {
36 return cast(ubyte)(n&0xff|(255-((-cast(long)(n < 256))>>56)));
37 } else {
38 n &= -cast(long)(n >= 0);
39 return cast(ubyte)(n|((255-cast(long)n)>>63));
41 } else {
42 static assert(false, "clampToByte: integer too big");
47 unittest {
48 static assert(clampToByte(666) == 255);
49 static assert(clampToByte(-666) == 0);
50 static assert(clampToByte(250) == 250);
51 static assert(clampToByte(-250) == 0);
52 static assert(clampToByte(cast(uint)250) == 250);
53 static assert(clampToByte(cast(uint)1000) == 255);
54 static assert(clampToByte(cast(uint)0xfffffff0) == 255);
55 static assert(clampToByte(false) == 0);
56 static assert(clampToByte(true) == 1);
57 static assert(clampToByte('A') == 65);
59 static assert(clampToByte(666L) == 255);
60 static assert(clampToByte(-666L) == 0);
61 static assert(clampToByte(250L) == 250);
62 static assert(clampToByte(-250L) == 0);
63 static assert(clampToByte(-666UL) == 255);