1 module viva.types.number;
2 
3 /++
4  + Checks whether or not the given type is a number type
5  + Returns: `true` if the type is a number, else `false`
6  +/
7 template isNumber(T)
8 {
9     static if (is(T : short)) enum bool isNumber = true;
10     else static if (is(T : ushort)) enum bool isNumber = true;
11     else static if (is(T : int)) enum bool isNumber = true;
12     else static if (is(T : uint)) enum bool isNumber = true;
13     else static if (is(T : long)) enum bool isNumber = true;
14     else static if (is(T : ulong)) enum bool isNumber = true;
15     else static if (is(T : float)) enum bool isNumber = true;
16     else static if (is(T : double)) enum bool isNumber = true;
17     else enum bool isNumber = false;
18 }
19 
20 /++
21  + Checks whether or not the given value is a number
22  + Returns: `true` if the value is a number, else `false`
23  +/
24 public bool isValueNumber(T)(T value) pure nothrow @safe
25 {
26     static if (is(T : short)) return true;
27     else static if (is(T : ushort)) return true;
28     else static if (is(T : int)) return true;
29     else static if (is(T : uint)) return true;
30     else static if (is(T : long)) return true;
31     else static if (is(T : ulong)) return true;
32     else static if (is(T : float)) return true;
33     else static if (is(T : double)) return true;
34     else return false;
35 }
36 
37 /++
38  + Clamps a reference to a value to minimum and maximum value
39  + Params:
40  +      value = The value to clamp
41  +      min = The minimum value
42  +      max = The maximum value
43  +/
44 public void clampRef(T)(ref T value, T min, T max) pure nothrow @safe
45 if (isNumber!T)
46 {
47     if (value < min) value = min;
48     if (value > max) value = max;
49 }
50 
51 /++
52  + Clamps a value to minimum and maximum value
53  + Params:
54  +      value = The value to clamp
55  +      min = The minimum value
56  +      max = The maximum value
57  + Returns: The clamped value
58  +/
59 public T clamp(T)(T value, T min, T max) pure nothrow @safe
60 if (isNumber!T)
61 {
62     if (value < min) value = min;
63     if (value > max) value = max;
64     return value;
65 }
66 
67 /++
68  +
69  +/
70 bool inRange(T)(ref T value, T min, T max) pure nothrow @safe
71 if (isNumber!T)
72 {
73     return value >= min && value <= max;
74 }
75 
76 /++
77  +
78  +/
79 bool inRange(T)(T value, T min, T max) pure nothrow @safe
80 if (isNumber!T)
81 {
82     return inRange(value, min, max);
83 }