]> git.lizzy.rs Git - rust.git/blob - src/lib/int.rs
Implement pattern ranges for all numeric types.
[rust.git] / src / lib / int.rs
1
2
3 pure fn add(x: int, y: int) -> int { ret x + y; }
4
5 pure fn sub(x: int, y: int) -> int { ret x - y; }
6
7 pure fn mul(x: int, y: int) -> int { ret x * y; }
8
9 pure fn div(x: int, y: int) -> int { ret x / y; }
10
11 pure fn rem(x: int, y: int) -> int { ret x % y; }
12
13 pure fn lt(x: int, y: int) -> bool { ret x < y; }
14
15 pure fn le(x: int, y: int) -> bool { ret x <= y; }
16
17 pure fn eq(x: int, y: int) -> bool { ret x == y; }
18
19 pure fn ne(x: int, y: int) -> bool { ret x != y; }
20
21 pure fn ge(x: int, y: int) -> bool { ret x >= y; }
22
23 pure fn gt(x: int, y: int) -> bool { ret x > y; }
24
25 pure fn positive(x: int) -> bool { ret x > 0; }
26
27 pure fn negative(x: int) -> bool { ret x < 0; }
28
29 pure fn nonpositive(x: int) -> bool { ret x <= 0; }
30
31 pure fn nonnegative(x: int) -> bool { ret x >= 0; }
32
33
34 // FIXME: Make sure this works with negative integers.
35 fn hash(x: int) -> uint { ret x as uint; }
36
37 fn eq_alias(x: int, y: int) -> bool { ret x == y; }
38
39 iter range(lo: int, hi: int) -> int {
40     let lo_: int = lo;
41     while lo_ < hi { put lo_; lo_ += 1; }
42 }
43
44 fn parse_buf(buf: [u8], radix: uint) -> int {
45     if vec::len::<u8>(buf) == 0u {
46         log_err "parse_buf(): buf is empty";
47         fail;
48     }
49     let i = vec::len::<u8>(buf) - 1u;
50     let power = 1;
51     if buf[0] == ('-' as u8) {
52         power = -1;
53         i -= 1u;
54     }
55     let n = 0;
56     while true {
57         n += (buf[i] - ('0' as u8) as int) * power;
58         power *= radix as int;
59         if i == 0u { ret n; }
60         i -= 1u;
61     }
62     fail;
63 }
64
65 fn from_str(s: str) -> int { parse_buf(str::bytes(s), 10u) }
66
67 fn to_str(n: int, radix: uint) -> str {
68     assert (0u < radix && radix <= 16u);
69     ret if n < 0 {
70             "-" + uint::to_str(-n as uint, radix)
71         } else { uint::to_str(n as uint, radix) };
72 }
73 fn str(i: int) -> str { ret to_str(i, 10u); }
74
75 fn pow(base: int, exponent: uint) -> int {
76     ret if exponent == 0u {
77             1
78         } else if base == 0 {
79             0
80         } else {
81             let accum = base;
82             let count = exponent;
83             while count > 1u { accum *= base; count -= 1u; }
84             accum
85         };
86 }
87 // Local Variables:
88 // mode: rust;
89 // fill-column: 78;
90 // indent-tabs-mode: nil
91 // c-basic-offset: 4
92 // buffer-file-coding-system: utf-8-unix
93 // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
94 // End: