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
// 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 crate::simulation;
use crate::simulation::error::*;
use crate::simulation::Run;
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::*;

/// The resources that gather its statistics.
pub mod stats;

/// Request for the resource within `Process` computation.
#[inline]
pub fn request_resource<S>(resource: Rc<Resource<S>>) -> Request<S>
    where S: QueueStrategy + Clone + 'static
{
    Request { resource: resource }
}

/// Request for the resource within `Process` computation with the specified priority.
#[inline]
pub fn request_resource_with_priority<S>(resource: Rc<Resource<S>>, priority: S::Priority) -> RequestWithPriority<S>
    where S: QueueStrategy + Clone + 'static,
          S::Priority: Clone
{
    RequestWithPriority { resource: resource, priority: priority }
}

/// Release the resource within `Process` computation.
#[inline]
pub fn release_resource<S>(resource: Rc<Resource<S>>) -> Release<S>
    where S: QueueStrategy
{
    Release { resource: resource }
}

/// Release the resource within `Event` computation.
#[inline]
pub fn release_resource_within_event<S>(resource: Rc<Resource<S>>) -> ReleaseWithinEvent<S>
    where S: QueueStrategy
{
    ReleaseWithinEvent { resource: resource }
}

/// Try to request for the resource immediately and return a flag
/// indicating whether the resource was aquired.
#[inline]
pub fn try_request_resource_within_event<S>(resource: Rc<Resource<S>>) -> TryRequestWithinEvent<S>
    where S: QueueStrategy
{
    TryRequestWithinEvent { resource: resource }
}

/// Create a new FCFS (a.k.a FIFO) resource by the specified initial count that becomes the capacity as well.
#[inline]
pub fn new_fcfs_resource(count: isize) -> NewResource<FCFSStrategy> {
    NewResource { strategy: FCFSStrategy::Instance, count: count, max_count: Some(count) }
}

/// Create a new FCFS (a.k.a FIFO) resource by the specified initial count and optional maximum count, i.e. capacity.
#[inline]
pub fn new_fcfs_resource_with_max_count(count: isize, max_count: Option<isize>) -> NewResource<FCFSStrategy> {
    NewResource { strategy: FCFSStrategy::Instance, count: count, max_count: max_count }
}

/// Create a new LCFS (a.k.a LIFO) resource by the specified initial count that becomes the capacity as well.
#[inline]
pub fn new_lcfs_resource(count: isize) -> NewResource<LCFSStrategy> {
    NewResource { strategy: LCFSStrategy::Instance, count: count, max_count: Some(count) }
}

/// Create a new LCFS (a.k.a LIFO) resource by the specified initial count and optional maximum count, i.e. capacity.
#[inline]
pub fn new_lcfs_resource_with_max_count(count: isize, max_count: Option<isize>) -> NewResource<LCFSStrategy> {
    NewResource { strategy: LCFSStrategy::Instance, count: count, max_count: max_count }
}

/// The `Resource` based on using the FCFS (a.k.a. FIFO) strategy (First Come - First Served).
pub type FCFSResource = Resource<FCFSStrategy>;

/// The `Resource` based on using the LCFS (a.k.a. LIFO) strategy (Last Come - First Served).
pub type LCFSResource = Resource<LCFSStrategy>;

/// Represents a simple resource that gathers its statistics.
pub struct Resource<S> where S: QueueStrategy {

    /// The maximum count of the resource, where `None` means that there is no upper bound.
    max_count: Option<isize>,

    /// The count.
    count: RefComp<isize>,

    /// The Wait list.
    wait_list: QueueStorageBox<ResourceItem, S::Priority>
}

impl<S> PartialEq for Resource<S> where S: QueueStrategy {

    fn eq(&self, other: &Self) -> bool {
        self.count == other.count
    }
}

impl<S> Eq for Resource<S> where S: QueueStrategy {}

/// Identifies the resource item.
#[derive(Clone)]
struct ResourceItem {

    /// The process identifier.
    pid: Rc<ProcessId>,

    /// The continuation of the corresponding process.
    cont: FrozenProcess<()>
}

impl<S> Resource<S> where S: QueueStrategy {

    /// Create a new resource by the specified queue storage and initial count,
    /// where the latter becomes the capacity as well.
    #[inline]
    pub fn new(strategy: S, count: isize) -> NewResource<S> {
        NewResource { strategy: strategy, count: count, max_count: Some(count) }
    }

    /// Create a new resource by the specified queue storage, initial count
    /// and optional maximum count, i.e. capacity.
    #[inline]
    pub fn new_with_max_count(strategy: S, count: isize, max_count: Option<isize>) -> NewResource<S> {
        NewResource { strategy: strategy, count: count, max_count: max_count }
    }

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

/// Computation that creates a new `Resource`.
#[derive(Clone)]
pub struct NewResource<S> {

    /// The queue strategy.
    strategy: S,

    /// The initial count.
    count: isize,

    /// The optional maximum count.
    max_count: Option<isize>
}

impl<S> Simulation for NewResource<S> where S: QueueStrategy {

    type Item = Resource<S>;

    #[doc(hidden)]
    #[inline]
    fn call_simulation(self, _r: &Run) -> simulation::Result<Self::Item> {
        let NewResource { strategy, count, max_count } = self;
        if count < 0 {
            let msg = String::from("The resource count cannot be actually negative");
            let err = Error::retry(msg);
            Result::Err(err)
        } else if count > max_count.unwrap_or(count) {
            let msg = String::from("The resource count cannot be greater than its upper bound");
            let err = Error::retry(msg);
            Result::Err(err)
        } else {
            let wait_list = strategy.new_storage();
            Result::Ok(Resource {
                max_count: max_count,
                count: RefComp::new(count),
                wait_list: wait_list
            })
        }
    }
}

/// Request for the resource.
#[must_use = "computations are lazy and do nothing unless to be run"]
#[derive(Clone)]
pub struct Request<S>
    where S: QueueStrategy + Clone + 'static
{
    /// The resource.
    resource: Rc<Resource<S>>
}

impl<S> Process for Request<S>
    where S: QueueStrategy + Clone + 'static
{
    type Item = ();

    #[doc(hidden)]
    #[inline]
    fn call_process<C>(self, cont: C, pid: Rc<ProcessId>, p: &Point) -> simulation::Result<()>
        where C: FnOnce(simulation::Result<Self::Item>, Rc<ProcessId>, &Point) -> simulation::Result<()> + Clone + 'static
    {
        let Request { resource } = self;
        let a = resource.count.read_at(p);
        if a > 0 {
            resource.count.write_at(a - 1, p);
            resume_process(cont, pid, (), p)
        } else {
            let comp = Request { resource: resource.clone() };
            let cont = ProcessBoxCont::new(cont);
            let cont = FrozenProcess::with_reentering(cont, pid.clone(), (), comp, p)?;
            let item = ResourceItem {
                pid: pid,
                cont: cont
            };
            resource.wait_list.push(item, p);
            Result::Ok(())
        }
    }

    #[doc(hidden)]
    fn call_process_boxed(self, cont: ProcessBoxCont<Self::Item>, pid: Rc<ProcessId>, p: &Point) -> simulation::Result<()> {
        let Request { resource } = self;
        let a = resource.count.read_at(p);
        if a > 0 {
            resource.count.write_at(a - 1, p);
            resume_process_boxed(cont, pid, (), p)
        } else {
            let comp = Request { resource: resource.clone() };
            let cont = FrozenProcess::with_reentering(cont, pid.clone(), (), comp, p)?;
            let item = ResourceItem {
                pid: pid,
                cont: cont
            };
            resource.wait_list.push(item, p);
            Result::Ok(())
        }
    }
}

/// Request for the resource with priority.
#[must_use = "computations are lazy and do nothing unless to be run"]
#[derive(Clone)]
pub struct RequestWithPriority<S>
    where S: QueueStrategy + Clone + 'static
{
    /// The resource.
    resource: Rc<Resource<S>>,

    /// The priority of the request.
    priority: S::Priority
}

impl<S> Process for RequestWithPriority<S>
    where S: QueueStrategy + Clone + 'static,
          S::Priority: Clone
{
    type Item = ();

    #[doc(hidden)]
    #[inline]
    fn call_process<C>(self, cont: C, pid: Rc<ProcessId>, p: &Point) -> simulation::Result<()>
        where C: FnOnce(simulation::Result<Self::Item>, Rc<ProcessId>, &Point) -> simulation::Result<()> + Clone + 'static
    {
        let RequestWithPriority { resource, priority } = self;
        let a = resource.count.read_at(p);
        if a > 0 {
            resource.count.write_at(a - 1, p);
            resume_process(cont, pid, (), p)
        } else {
            let comp = RequestWithPriority { resource: resource.clone(), priority: priority.clone() };
            let cont = ProcessBoxCont::new(cont);
            let cont = FrozenProcess::with_reentering(cont, pid.clone(), (), comp, p)?;
            let item = ResourceItem {
                pid: pid,
                cont: cont
            };
            resource.wait_list.push_with_priority(priority, item, p);
            Result::Ok(())
        }
    }

    #[doc(hidden)]
    fn call_process_boxed(self, cont: ProcessBoxCont<Self::Item>, pid: Rc<ProcessId>, p: &Point) -> simulation::Result<()> {
        let RequestWithPriority { resource, priority } = self;
        let a = resource.count.read_at(p);
        if a > 0 {
            resource.count.write_at(a - 1, p);
            resume_process_boxed(cont, pid, (), p)
        } else {
            let comp = RequestWithPriority { resource: resource.clone(), priority: priority.clone() };
            let cont = FrozenProcess::with_reentering(cont, pid.clone(), (), comp, p)?;
            let item = ResourceItem {
                pid: pid,
                cont: cont
            };
            resource.wait_list.push_with_priority(priority, item, p);
            Result::Ok(())
        }
    }
}

/// Release the resource.
#[must_use = "computations are lazy and do nothing unless to be run"]
#[derive(Clone)]
pub struct Release<S> where S: QueueStrategy {

    /// The resource.
    resource: Rc<Resource<S>>
}

impl<S> Process for Release<S>
    where S: QueueStrategy
{
    type Item = ();

    #[doc(hidden)]
    #[inline]
    fn call_process<C>(self, cont: C, pid: Rc<ProcessId>, p: &Point) -> simulation::Result<()>
        where C: FnOnce(simulation::Result<Self::Item>, Rc<ProcessId>, &Point) -> simulation::Result<()> + Clone + 'static
    {
        let Release { resource } = self;
        let comp = ReleaseWithinEvent { resource: resource };
        comp.call_event(p)?;
        resume_process(cont, pid, (), p)
    }

    #[doc(hidden)]
    fn call_process_boxed(self, cont: ProcessBoxCont<Self::Item>, pid: Rc<ProcessId>, p: &Point) -> simulation::Result<()> {
        let Release { resource } = self;
        let comp = ReleaseWithinEvent { resource: resource };
        comp.call_event(p)?;
        resume_process_boxed(cont, pid, (), p)
    }
}

/// Release the resource.
#[must_use = "computations are lazy and do nothing unless to be run"]
#[derive(Clone)]
pub struct ReleaseWithinEvent<S> where S: QueueStrategy {

    /// The resource.
    resource: Rc<Resource<S>>
}

impl<S> Event for ReleaseWithinEvent<S>
    where S: QueueStrategy
{
    type Item = ();

    #[doc(hidden)]
    fn call_event(self, p: &Point) -> simulation::Result<()> {
        let ReleaseWithinEvent { resource } = self;
        let a  = resource.count.read_at(p);
        let a2 = a + 1;
        if a2 > resource.max_count.unwrap_or(a2) {
            let msg = String::from("The resource count cannot be greater than its upper bound");
            let err = Error::retry(msg);
            Result::Err(err)
        } else {
            let t = p.time;
            loop {
                if resource.wait_list.is_empty(p) {
                    resource.count.write_at(a2, p);
                    break;
                } else {
                    let ResourceItem { pid, cont: cont0 } = {
                        resource.wait_list.pop(p).unwrap()
                    };
                    match cont0.unfreeze(p)? {
                        None => continue,
                        Some(cont) => {
                            enqueue_event(t, {
                                cons_event(move |p| {
                                    resume_process_boxed(cont, pid, (), p)
                                }).into_boxed()
                            }).call_event(p)?;
                            break;
                        }
                    }
                }
            }
            Result::Ok(())
        }
    }
}

/// Try to request for the resource immediately and return a flag
/// indicating whether the resource was aquired.
#[must_use = "computations are lazy and do nothing unless to be run"]
#[derive(Clone)]
pub struct TryRequestWithinEvent<S>
    where S: QueueStrategy
{
    /// The resource.
    resource: Rc<Resource<S>>
}

impl<S> Event for TryRequestWithinEvent<S>
    where S: QueueStrategy
{
    type Item = bool;

    #[doc(hidden)]
    #[inline]
    fn call_event(self, p: &Point) -> simulation::Result<Self::Item> {
        let TryRequestWithinEvent { resource } = self;
        let a = resource.count.read_at(p);
        if a > 0 {
            resource.count.write_at(a - 1, p);
            Result::Ok(true)
        } else {
            Result::Ok(false)
        }
    }
}