corewars_sim/core/
process.rs

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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/// Container for managing the process queue of warriors. A given core has
/// a single queue, but the queue itself may have numerous "threads" of execution
/// and determines what process is scheduled when.
use std::collections::{BTreeMap, VecDeque};

use thiserror::Error as ThisError;

use super::Offset;

#[derive(Debug, Eq, PartialEq)]
pub struct Entry {
    pub name: String,
    pub thread: usize,
    pub offset: Offset,
}

/// A representation of the process queue. This is effectively a simple FIFO queue.
// TODO enforce size limits based on MAXPROCESSES
#[derive(Debug)]
pub struct Queue {
    /// The actual offsets enqueued to be executed
    queue: VecDeque<Entry>,

    /// A map of process names to the number of tasks each has in the queue.
    /// This is updated whenever instructions are added to/removed from the queue,
    /// and can be used to determine whether a process is alive or not.
    processes: BTreeMap<String, usize>,

    /// An increasing counter per process to give unique thread ids
    next_thread_id: BTreeMap<String, usize>,
}

impl Queue {
    /// Create an empty queue
    pub fn new() -> Self {
        Self {
            queue: VecDeque::new(),
            processes: BTreeMap::new(),
            next_thread_id: BTreeMap::new(),
        }
    }

    /// Get the next offset for execution, removing it from the queue.
    pub fn pop(&mut self) -> Result<Entry, Error> {
        self.queue
            .pop_front()
            .map_or(Err(Error::NoRemainingProcesses), |entry| {
                let decremented = self.processes[&entry.name].saturating_sub(1);
                self.processes
                    .entry(entry.name.clone())
                    .and_modify(|count| *count = decremented);

                Ok(entry)
            })
    }

    /// Get the next offset for execution without modifying the queue.
    // TODO: this should probably just return Option<&ProcessEntry>
    pub fn peek(&self) -> Result<&Entry, Error> {
        self.queue.get(0).ok_or(Error::NoRemainingProcesses)
    }

    /// Add an entry to the process queue. If specified, it will use the given thread ID,
    /// otherwise a new thread ID will be created based on the current number of
    /// threads active for this process name.
    pub fn push(&mut self, process_name: String, offset: Offset, thread: Option<usize>) {
        let thread_id = thread.map_or_else(
            || {
                let entry = self.next_thread_id.entry(process_name.clone()).or_insert(0);
                let id = *entry;
                *entry += 1;
                id
            },
            |id| id,
        );

        self.queue.push_back(Entry {
            name: process_name.clone(),
            thread: thread_id,
            offset,
        });

        *self.processes.entry(process_name).or_insert(0) += 1;
    }

    /// Check the status of a process in the queue. Panics if the process was
    /// never added to the queue.
    pub fn thread_count(&self, name: &str) -> usize {
        self.processes[name]
    }
}

/// An process-related error occurred
#[derive(ThisError, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// All processes terminated
    #[error("no process running to execute")]
    NoRemainingProcesses,

    /// A process already exists with the given name
    #[error("a process with the name '{0}' already exists")]
    ProcessNameExists(String),

    /// The warrior attempted to execute a DAT instruction
    #[error("terminated due to reaching a DAT at offset {0}")]
    ExecuteDat(Offset),

    /// The warrior attempted to execute a division by zero
    #[error("terminated due to division by 0")]
    DivideByZero,
}

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

    #[test]
    fn queue_multiple_processes() {
        let mut queue = Queue::new();

        assert_eq!(queue.peek().unwrap_err(), Error::NoRemainingProcesses);
        assert_eq!(queue.pop().unwrap_err(), Error::NoRemainingProcesses);

        let starting_offset = Offset::new(10, 8000);

        queue.push("p1".into(), starting_offset, None);
        assert_eq!(
            queue.peek().unwrap(),
            &Entry {
                name: "p1".into(),
                thread: 0,
                offset: starting_offset
            }
        );
        assert!(queue.thread_count("p1") > 0);

        queue.push("p2".into(), starting_offset + 5, None);
        assert!(queue.thread_count("p2") > 0);

        assert_eq!(
            queue.pop().unwrap(),
            Entry {
                name: "p1".into(),
                thread: 0,
                offset: starting_offset
            }
        );
        assert_eq!(
            queue.peek().unwrap(),
            &Entry {
                name: "p2".into(),
                thread: 0,
                offset: starting_offset + 5
            }
        );
        assert!(!queue.thread_count("p1") > 0);
        assert!(queue.thread_count("p2") > 0);

        assert_eq!(
            queue.pop().unwrap(),
            Entry {
                name: "p2".into(),
                thread: 0,
                offset: starting_offset + 5
            }
        );
        assert!(!queue.thread_count("p1") > 0);
        assert!(!queue.thread_count("p2") > 0);

        assert_eq!(queue.peek().unwrap_err(), Error::NoRemainingProcesses);
        assert_eq!(queue.pop().unwrap_err(), Error::NoRemainingProcesses);

        assert!(!queue.thread_count("p1") > 0);
        assert!(!queue.thread_count("p2") > 0);
    }

    #[test]
    fn queue_single_process() {
        let mut queue = Queue::new();
        let starting_offset = Offset::new(10, 8000);

        queue.push("p1".into(), starting_offset, None);
        assert_eq!(
            queue.peek().unwrap(),
            &Entry {
                name: "p1".into(),
                thread: 0,
                offset: starting_offset
            }
        );
        assert!(queue.thread_count("p1") > 0);

        // should increment the thread id to 1
        queue.push("p1".into(), starting_offset, None);
        queue.pop().unwrap();
        assert_eq!(
            queue.peek().unwrap(),
            &Entry {
                name: "p1".into(),
                thread: 1,
                offset: starting_offset
            }
        );
        assert!(queue.thread_count("p1") > 0);

        queue.push("p1".into(), starting_offset, Some(1));
        queue.pop().unwrap();
        assert_eq!(
            queue.peek().unwrap(),
            &Entry {
                name: "p1".into(),
                thread: 1,
                offset: starting_offset
            }
        );
        assert!(queue.thread_count("p1") > 0);
    }
}