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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright (c) 2020-2022  David Sorokin <david.sorokin@gmail.com>, based in Yoshkar-Ola, Russia
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::rc::Rc;
use std::marker::PhantomData;

use crate::simulation;
use crate::simulation::error::*;
use crate::simulation::Point;
use crate::simulation::ref_comp::RefComp;
use crate::simulation::simulation::*;
use crate::simulation::event::*;
use crate::simulation::process::*;
use crate::simulation::strategy::*;
use crate::simulation::resource::*;

/// The queues that gather their statistics when simulating.
pub mod stats;

/// Represents unbounded queues.
pub mod unbounded;

/// A type synonym for the ordinary FIFO queue, also known as the FCFS
/// (First Come - First Serviced) queue.
pub type FCFSQueue<T> = Queue<FCFSStrategy, FCFSStrategy, FCFSStrategy, T>;

/// A type synonym for the ordinary LIFO queue, also known as the LCFS
/// (Last Come - First Serviced) queue.
pub type LCFSQueue<T> = Queue<FCFSStrategy, LCFSStrategy, FCFSStrategy, T>;

/// Represents an optimized bounded queue by using the specified strategies for enqueueing (input), `SI`,
/// internal storing (in memory), `SM`, and dequeueing (output), `SO`, where `T` denotes
/// the type of items stored in the queue.
pub struct Queue<SI, SM, SO, T>
    where SI: QueueStrategy,
          SM: QueueStrategy,
          SO: QueueStrategy
{
    /// The queue capacity.
    max_count: isize,

    /// The enqueue resource.
    enqueue_resource: Rc<Resource<SI>>,

    /// The queue store.
    queue_store: QueueStorageBox<T, SM::Priority>,

    /// The dequeue resource.
    dequeue_resource: Rc<Resource<SO>>,

    /// The queue size.
    count: RefComp<isize>
}

/// Create a new bounded FCFS (a.k.a FIFO) queue by the specified capacity.
#[inline]
pub fn new_fcfs_queue<T>(max_count: isize) -> NewQueue<FCFSStrategy, FCFSStrategy, FCFSStrategy, T>
    where T: 'static
{
    NewQueue {
        enqueue_strategy: FCFSStrategy::Instance,
        storing_strategy: FCFSStrategy::Instance,
        dequeue_strategy: FCFSStrategy::Instance,
        max_count: max_count,
        _phantom: PhantomData
    }
}

/// Create a new bounded LCFS (a.k.a LIFO) queue by the specified capacity.
#[inline]
pub fn new_lcfs_queue<T>(max_count: isize) -> NewQueue<FCFSStrategy, LCFSStrategy, FCFSStrategy, T>
    where T: 'static
{
    NewQueue {
        enqueue_strategy: FCFSStrategy::Instance,
        storing_strategy: LCFSStrategy::Instance,
        dequeue_strategy: FCFSStrategy::Instance,
        max_count: max_count,
        _phantom: PhantomData
    }
}

impl<SI, SM, SO, T> Queue<SI, SM, SO, T>
    where SI: QueueStrategy + Clone + 'static,
          SM: QueueStrategy + Clone + 'static,
          SO: QueueStrategy + Clone + 'static,
          T: Clone + 'static
{
    /// Create a new bounded queue by the specified strategies and capacity.
    #[inline]
    pub fn new(enqueue_strategy: SI,
        storing_strategy: SM,
        dequeue_strategy: SO,
        max_count: isize) -> NewQueue<SI, SM, SO, T>
    {
        NewQueue {
            enqueue_strategy: enqueue_strategy,
            storing_strategy: storing_strategy,
            dequeue_strategy: dequeue_strategy,
            max_count: max_count,
            _phantom: PhantomData
        }
    }

    /// Return the queue capacity, i.e. its maximum size.
    #[inline]
    pub fn max_count(&self) -> isize {
        self.max_count
    }

    /// Test whether the queue is empty.
    #[inline]
    pub fn is_empty(queue: Rc<Self>) -> impl Event<Item = bool> + Clone {
        cons_event(move |p| {
            Result::Ok(queue.count.read_at(p) == 0)
        })
    }

    /// Test whether the queue is full.
    #[inline]
    pub fn is_full(queue: Rc<Self>) -> impl Event<Item = bool> + Clone {
        cons_event(move |p| {
            Result::Ok(queue.count.read_at(p) == queue.max_count)
        })
    }

    /// Return the current queue size.
    #[inline]
    pub fn count(queue: Rc<Self>) -> impl Event<Item = isize> + Clone {
        cons_event(move |p| {
            Result::Ok(queue.count.read_at(p))
        })
    }

    /// Return the load factor: the queue size divided by its capacity, i.e. maximum size.
    #[inline]
    pub fn load_factor(queue: Rc<Self>) -> impl Event<Item = f64> + Clone {
        cons_event(move |p| {
            Result::Ok({
                let x = queue.count.read_at(p);
                let y = queue.max_count;
                (x as f64) / (y as f64)
            })
        })
    }

    /// Dequeue by suspending the process if the queue is empty.
    pub fn dequeue(queue: Rc<Self>) -> impl Process<Item = T> + Clone {
        request_resource(queue.dequeue_resource.clone())
            .flat_map(move |()| {
                cons_event(move |p| {
                    queue.dequeue_extract(p)
                })
                .into_process()
            })
    }

    /// Dequeue with output prioerity by suspending the process if the queue is empty.
    pub fn dequeue_with_output_priority(queue: Rc<Self>, po: SO::Priority) -> impl Process<Item = T> + Clone
        where SO::Priority: Clone
    {
        request_resource_with_priority(queue.dequeue_resource.clone(), po)
            .flat_map(move |()| {
                cons_event(move |p| {
                    queue.dequeue_extract(p)
                })
                .into_process()
            })
    }

    /// Try to dequeue immediately.
    pub fn try_dequeue(queue: Rc<Self>) -> impl Event<Item = Option<T>> + Clone {
        try_request_resource_within_event(queue.dequeue_resource.clone())
            .flat_map(move |f| {
                if f {
                    cons_event(move |p| {
                        let x = queue.dequeue_extract(p)?;
                        Result::Ok(Some(x))
                    }).into_boxed()
                } else {
                    return_event(None)
                        .into_boxed()
                }
            })
    }

    /// Remove the item from the queue and return a flag indicating
    /// whether the item was found and actually removed.
    pub fn delete(queue: Rc<Self>, item: T) -> impl Event<Item = bool> + Clone
        where T: PartialEq
    {
        let pred = move |x: &T| { *x == item };
        Queue::delete_by(queue, pred)
            .map(|x| { x.is_some() })
    }

    /// Remove the specified item from the queue.
    pub fn delete_(queue: Rc<Self>, item: T) -> impl Event<Item = ()> + Clone
        where T: PartialEq
    {
        let pred = move |x: &T| { *x == item };
        Queue::delete_by(queue, pred)
            .map(|_| ())
    }

    /// Remove an item satisfying the specified predicate and return the item if found.
    pub fn delete_by<F>(queue: Rc<Self>, pred: F) -> impl Event<Item = Option<T>> + Clone
        where F: Fn(&T) -> bool + Clone + 'static
    {
        try_request_resource_within_event(queue.dequeue_resource.clone())
            .flat_map(move |f| {
                if f {
                    cons_event(move |p| {
                        let pred = move |x: &T| { pred(x) };
                        let pred = Rc::new(pred);
                        match queue.queue_store.remove_boxed_by(pred, p) {
                            None => {
                                release_resource_within_event(queue.dequeue_resource.clone())
                                    .call_event(p)?;
                                Result::Ok(None)
                            },
                            Some(i) => {
                                let x = queue.dequeue_post_extract(i, p)?;
                                Result::Ok(Some(x))
                            }
                        }
                    }).into_boxed()
                } else {
                    return_event(None)
                        .into_boxed()
                }
            })
    }

    /// Test whether there is an item satisfying the specified predicate.
    pub fn exists<F>(queue: Rc<Self>, pred: F) -> impl Event<Item = bool> + Clone
        where F: Fn(&T) -> bool + Clone + 'static
    {
        cons_event(move |p| {
            let pred = move |x: &T| { pred(x) };
            let pred = Rc::new(pred);
            Result::Ok(queue.queue_store.exists_boxed(pred, p))
        })
    }

    /// Find an item satisfying the specified predicate.
    pub fn find<F>(queue: Rc<Self>, pred: F) -> impl Event<Item = Option<T>> + Clone
        where F: Fn(&T) -> bool + Clone + 'static,
              T: Clone
    {
        cons_event(move |p| {
            let pred = move |x: &T| { pred(x) };
            let pred = Rc::new(pred);
            Result::Ok(queue.queue_store.find_boxed(pred, p).map(|x| { x.clone() }))
        })
    }

    /// Clear the queue.
    pub fn clear(queue: Rc<Self>) -> impl Event<Item = ()> + Clone {
        cons_event(move |p| {
            loop {
                let x = Queue::try_dequeue(queue.clone()).call_event(p)?;
                match x {
                    None => return Result::Ok(()),
                    Some(_) => {}
                }
            }
        })
    }

    /// Enqueue the item by suspending the process if the queue is full.
    pub fn enqueue(queue: Rc<Self>, item: T) -> impl Process<Item = ()> + Clone {
        request_resource(queue.enqueue_resource.clone())
            .flat_map(move |()| {
                cons_event(move |p| {
                    queue.enqueue_store(item, p)
                })
                .into_process()
            })
    }

    /// Enqueue the item with input priority by suspending the process
    /// if the queue is full.
    pub fn enqueue_with_input_priority(queue: Rc<Self>, pi: SI::Priority, item: T) -> impl Process<Item = ()> + Clone
        where SI::Priority: Clone
    {
        request_resource_with_priority(queue.enqueue_resource.clone(), pi)
            .flat_map(move |()| {
                cons_event(move |p| {
                    queue.enqueue_store(item, p)
                })
                .into_process()
            })
    }

    /// Enqueue the item with storing priority by suspending the process
    /// if the queue is full.
    pub fn enqueue_with_storing_priority(queue: Rc<Self>, pm: SM::Priority, item: T) -> impl Process<Item = ()> + Clone
        where SM::Priority: Clone
    {
        request_resource(queue.enqueue_resource.clone())
            .flat_map(move |()| {
                cons_event(move |p| {
                    queue.enqueue_store_with_priority(pm, item, p)
                })
                .into_process()
            })
    }

    /// Enqueue the item with input and storing priorities by suspending the process
    /// if the queue is full.
    pub fn enqueue_with_input_and_storing_priorities(queue: Rc<Self>, pi: SI::Priority, pm: SM::Priority, item: T) -> impl Process<Item = ()> + Clone
        where SI::Priority: Clone,
              SM::Priority: Clone
    {
        request_resource_with_priority(queue.enqueue_resource.clone(), pi)
            .flat_map(move |()| {
                cons_event(move |p| {
                    queue.enqueue_store_with_priority(pm, item, p)
                })
                .into_process()
            })
    }

    /// Try to enqueue the item. Return `false` within `Event` computation if the queue is full.
    pub fn try_enqueue(queue: Rc<Self>, item: T) -> impl Event<Item = bool> + Clone {
        cons_event(move |p| {
            let x = {
                try_request_resource_within_event(queue.enqueue_resource.clone())
                    .call_event(p)
            }?;
            if x {
                queue.enqueue_store(item, p)?;
                Result::Ok(true)
            } else {
                Result::Ok(false)
            }
        })
    }

    /// Try to enqueue the item with storing priority. Return `false`
    /// within `Event` computation if the queue is full.
    pub fn try_enqueue_with_storing_priority(queue: Rc<Self>, pm: SM::Priority, item: T) -> impl Event<Item = bool> + Clone
        where SM::Priority: Clone
    {
        cons_event(move |p| {
            let x = {
                try_request_resource_within_event(queue.enqueue_resource.clone())
                    .call_event(p)
            }?;
            if x {
                queue.enqueue_store_with_priority(pm, item, p)?;
                Result::Ok(true)
            } else {
                Result::Ok(false)
            }
        })
    }

    /// Extract an item by the dequeue request.
    fn dequeue_extract(&self, p: &Point) -> simulation::Result<T> {
        let i = self.queue_store.pop(p).unwrap();
        self.dequeue_post_extract(i, p)
    }

    /// A post action after extracting the item by the dequeue request.
    fn dequeue_post_extract(&self, i: T, p: &Point) -> simulation::Result<T> {
        let c  = self.count.read_at(p);
        let c2 = c - 1;
        self.count.write_at(c2, p);
        release_resource_within_event(self.enqueue_resource.clone())
            .call_event(p)?;
        Result::Ok(i)
    }

    /// Store the item.
    fn enqueue_store(&self, item: T, p: &Point) -> simulation::Result<()> {
        self.queue_store.push(item, p);
        let c  = self.count.read_at(p);
        let c2 = c + 1;
        self.count.write_at(c2, p);
        release_resource_within_event(self.dequeue_resource.clone())
            .call_event(p)
    }

    /// Store the item with priority.
    fn enqueue_store_with_priority(&self, pm: SM::Priority, item: T, p: &Point) -> simulation::Result<()> {
        self.queue_store.push_with_priority(pm, item, p);
        let c  = self.count.read_at(p);
        let c2 = c + 1;
        self.count.write_at(c2, p);
        release_resource_within_event(self.dequeue_resource.clone())
            .call_event(p)
    }
}

/// Computation that creates a new `Queue`.
#[derive(Clone)]
pub struct NewQueue<SI, SM, SO, T> {

    /// The enqueue strategy.
    enqueue_strategy: SI,

    /// The storing strategy.
    storing_strategy: SM,

    /// The output strategy.
    dequeue_strategy: SO,

    /// The capacity.
    max_count: isize,

    /// To keep the type parameter.
    _phantom: PhantomData<T>
}

impl<SI, SM, SO, T> Event for NewQueue<SI, SM, SO, T>
    where SI: QueueStrategy,
          SM: QueueStrategy,
          SO: QueueStrategy,
          T: Clone + 'static
{
    type Item = Queue<SI, SM, SO, T>;

    #[doc(hidden)]
    #[inline]
    fn call_event(self, p: &Point) -> simulation::Result<Self::Item> {
        let NewQueue { enqueue_strategy, storing_strategy, dequeue_strategy, max_count, _phantom } = self;
        if max_count < 0 {
            let msg = String::from("The queue capacity cannot be actually negative");
            let err = Error::retry(msg);
            Result::Err(err)
        } else {
            let enqueue_resource = {
                Resource::<SI>::new_with_max_count(enqueue_strategy, max_count, Some(max_count))
                    .call_simulation(p.run)?
            };
            let queue_store = storing_strategy.new_storage();
            let dequeue_resource = {
                Resource::<SO>::new_with_max_count(dequeue_strategy, 0, Some(max_count))
                    .call_simulation(p.run)?
            };
            Result::Ok(Queue {
                max_count: max_count,
                enqueue_resource: Rc::new(enqueue_resource),
                queue_store: queue_store,
                dequeue_resource: Rc::new(dequeue_resource),
                count: RefComp::new(0)
            })
        }
    }
}