zymosis: cosmetix
[iv.d.git] / bclamp.d
blobb232c90cf42f1ead0a32140e9b9b5df90cdf058d
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, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 // just `clampToByte()`, so i can easily find and copypaste it
19 module iv.bclamp /*is aliced*/;
22 // this is actually branch-less for ints on x86, and even for longs on x86_64
23 ubyte clampToByte(T) (T n) pure nothrow @safe @nogc if (__traits(isIntegral, T)) {
24 pragma(inline, true);
25 static if (T.sizeof == 2 || T.sizeof == 4) {
26 static if (__traits(isUnsigned, T)) {
27 return cast(ubyte)(n&0xff|(255-((-cast(int)(n < 256))>>24)));
28 } else {
29 n &= -cast(int)(n >= 0);
30 return cast(ubyte)(n|((255-cast(int)n)>>31));
32 } else static if (T.sizeof == 1) {
33 static assert(__traits(isUnsigned, T), "clampToByte: signed byte? no, really?");
34 return cast(ubyte)n;
35 } else static if (T.sizeof == 8) {
36 static if (__traits(isUnsigned, T)) {
37 return cast(ubyte)(n&0xff|(255-((-cast(long)(n < 256))>>56)));
38 } else {
39 n &= -cast(long)(n >= 0);
40 return cast(ubyte)(n|((255-cast(long)n)>>63));
42 } else {
43 static assert(false, "clampToByte: integer too big");
48 unittest {
49 static assert(clampToByte(666) == 255);
50 static assert(clampToByte(-666) == 0);
51 static assert(clampToByte(250) == 250);
52 static assert(clampToByte(-250) == 0);
53 static assert(clampToByte(cast(uint)250) == 250);
54 static assert(clampToByte(cast(uint)1000) == 255);
55 static assert(clampToByte(cast(uint)0xfffffff0) == 255);
56 static assert(clampToByte(false) == 0);
57 static assert(clampToByte(true) == 1);
58 static assert(clampToByte('A') == 65);
60 static assert(clampToByte(666L) == 255);
61 static assert(clampToByte(-666L) == 0);
62 static assert(clampToByte(250L) == 250);
63 static assert(clampToByte(-250L) == 0);
64 static assert(clampToByte(-666UL) == 255);