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
//! `Labels` are unique names associated with each block.

/// Last ID set by the Label framework
static mut LAST_ID: u128 = 0;

/// Labels are a unique identifier attributed to a block. It represents this
/// block and is unique.
#[derive(Debug)]
pub struct Label {
    name: String,
}

impl Label {
    /// Return a new, unique label according to the given prefix
    ///
    /// # Example
    ///
    /// ```
    /// use stir::label::Label;
    ///
    /// let l = Label::new("bool");
    ///
    /// assert!(l.name().contains("__bool_"));
    /// ```
    pub fn new(prefix: &str) -> Label {
        Label {
            name: Label::unique_identifier(prefix),
        }
    }

    /// Create a new unique identifier from a given prefix using the following
    /// layout:
    ///     __<prefix>_<last_id + 1>
    fn unique_identifier(prefix: &str) -> String {
        let mut unique = String::from("__");
        unique.push_str(prefix);
        unique.push_str("_");

        // Get the last ID given and increment it. Then, append it to the
        // unique identifier
        unsafe {
            LAST_ID += 1;
            unique.push_str(&LAST_ID.to_string());
        }

        unique
    }

    /// Return the label's actual name
    pub fn name(&self) -> &String {
        &self.name
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn id_layout() {
        let l = Label::new("a");

        assert!(l.name().contains("__a_"));
    }

    #[test]
    fn id_layout_complex_prefix() {
        let l = Label::new("this_is_complex");

        assert!(l.name().contains("__this_is_complex_"));
    }

    #[test]
    fn last_id_increases() {
        let l0 = Label::new("a");
        let l1 = Label::new("a");

        assert_ne!(l0.name(), l1.name());
    }
}