summary refs log tree commit diff
path: root/src/libcore/bool.rs
blob: 1f0d9174c735921f88ba4e8a1af0d860c7214dad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// -*- rust -*-

//! Boolean logic

export not, and, or, xor, implies;
export eq, ne, is_true, is_false;
export from_str, to_str, all_values, to_bit;

/// Negation / inverse
pure fn not(v: bool) -> bool { !v }

/// Conjunction
pure fn and(a: bool, b: bool) -> bool { a && b }

/// Disjunction
pure fn or(a: bool, b: bool) -> bool { a || b }

/**
 * Exclusive or
 *
 * Identical to `or(and(a, not(b)), and(not(a), b))`
 */
pure fn xor(a: bool, b: bool) -> bool { (a && !b) || (!a && b) }

/// Implication in the logic, i.e. from `a` follows `b`
pure fn implies(a: bool, b: bool) -> bool { !a || b }

/// true if truth values `a` and `b` are indistinguishable in the logic
pure fn eq(a: bool, b: bool) -> bool { a == b }

/// true if truth values `a` and `b` are distinguishable in the logic
pure fn ne(a: bool, b: bool) -> bool { a != b }

/// true if `v` represents truth in the logic
pure fn is_true(v: bool) -> bool { v }

/// true if `v` represents falsehood in the logic
pure fn is_false(v: bool) -> bool { !v }

/// Parse logic value from `s`
pure fn from_str(s: str) -> option<bool> {
    alt check s {
      "true" { some(true) }
      "false" { some(false) }
      _ { none }
    }
}

/// Convert `v` into a string
pure fn to_str(v: bool) -> str { if v { "true" } else { "false" } }

/**
 * Iterates over all truth values by passing them to `blk` in an unspecified
 * order
 */
fn all_values(blk: fn(v: bool)) {
    blk(true);
    blk(false);
}

/// converts truth value to an 8 bit byte
pure fn to_bit(v: bool) -> u8 { if v { 1u8 } else { 0u8 } }

#[test]
fn test_bool_from_str() {
    do all_values |v| {
        assert some(v) == from_str(bool::to_str(v))
    }
}

#[test]
fn test_bool_to_str() {
    assert to_str(false) == "false";
    assert to_str(true) == "true";
}

#[test]
fn test_bool_to_bit() {
    do all_values |v| {
        assert to_bit(v) == if is_true(v) { 1u8 } else { 0u8 };
    }
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End: