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
// 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::marker::PhantomData;

#[cfg(feature="cons_mode")]
use std::mem;

#[cfg(feature="cons_mode")]
use std::ptr;

#[cfg(feature="cons_mode")]
use libc::*;

use crate::simulation;
use crate::simulation::point::Point;
use crate::simulation::event::Event;

#[cfg(feature="cons_mode")]
use crate::simulation::error::*;

/// Create a `Disposable` by the specified function.
#[inline]
pub fn cons_disposable<F>(f: F) -> Cons<F>
    where F: FnOnce(&Point) -> simulation::Result<()>
{
    Cons { f: f }
}

/// Create an empty `Disposable`.
#[inline]
pub fn empty_disposable() -> Empty {
    Empty {}
}

/// Concatenate `Disposable` objects.
#[inline]
pub fn concat_disposables<I, M>(disposables: I) -> Concat<I::IntoIter, M>
    where I: IntoIterator<Item = M>,
          M: Disposable
{
    Concat { disposables: disposables.into_iter(), _phantom: PhantomData }
}

/// Trace the computation.
#[inline]
pub fn trace_disposable<M>(msg: String, comp: M) -> Trace<M>
    where M: Disposable
{
    Trace { comp: comp, msg: msg}
}

/// The computation that disposes the observable subscription.
pub trait Disposable {

    /// Dispose something at the specified modeling time.
    #[doc(hidden)]
    fn dispose(self, p: &Point) -> simulation::Result<()>;

    /// Convert to the `Event` computation.
    #[inline]
    fn into_event(self) -> DisposableEvent<Self>
        where Self: Sized
    {
        DisposableEvent { disposable: self }
    }

    /// Merge with another `Disposable` computation.
    #[inline]
    fn merge<U>(self, other: U) -> Merge<Self, U>
        where Self: Sized,
              U: Disposable
    {
        Merge { disposable: self, other: other }
    }

    /// Convert into a boxed representation.
    #[inline]
    fn into_boxed(self) -> DisposableBox
        where Self: Sized + 'static
    {
        DisposableBox::new(move |p: &Point| { self.dispose(p) })
    }
}

/// Allows converting to `Disposable` computations.
pub trait IntoDisposable {

    type Disposable: Disposable;

    /// Convert to the `Disposable` computation.
    fn into_disposable(self) -> Self::Disposable;
}

impl<M: Disposable> IntoDisposable for M {

    type Disposable = M;

    #[inline]
    fn into_disposable(self) -> Self::Disposable {
        self
    }
}

/// The `Disposable` box value.
pub struct DisposableBox {
    f: Box<dyn DisposableFnBox>
}

impl DisposableBox {

    /// Create a new boxed computation.
    #[doc(hidden)]
    #[inline]
    fn new<F>(f: F) -> Self
        where F: FnOnce(&Point) -> simulation::Result<()> + 'static
    {
        DisposableBox {
            f: Box::new(f)
        }
    }

    /// Call the boxed function.
    #[doc(hidden)]
    #[inline]
    pub fn call_box(self, arg: (&Point,)) -> simulation::Result<()> {
        let DisposableBox { f } = self;
        f.call_box(arg)
    }
}

impl Disposable for DisposableBox {

    #[doc(hidden)]
    #[inline]
    fn dispose(self, p: &Point) -> simulation::Result<()> {
        self.call_box((p,))
    }

    #[inline]
    fn into_boxed(self) -> DisposableBox
        where Self: Sized + 'static
    {
        self
    }
}

/// A trait to support the stable version of Rust, where there is no `FnBox`.
trait DisposableFnBox {

    /// Call the corresponding function.
    fn call_box(self: Box<Self>, args: (&Point,)) -> simulation::Result<()>;
}

impl<F> DisposableFnBox for F
    where F: for<'a> FnOnce(&'a Point) -> simulation::Result<()>
{
    fn call_box(self: Box<Self>, args: (&Point,)) -> simulation::Result<()> {
        let this: Self = *self;
        this(args.0)
    }
}

/// It represents a raw trait object.
#[cfg(feature="cons_mode")]
#[repr(C)]
#[derive(Copy, Clone)]
struct DisposableTraitObject {

    field1: *mut c_void,
    field2: *mut c_void
}

/// A C-friendly representaton of the `Disposable` action.
#[cfg(feature="cons_mode")]
#[repr(C)]
pub struct DisposableRepr {

    /// Delete the object.
    delete: unsafe extern "C" fn(obj: *mut DisposableTraitObject),

    /// The callback.
    callback: unsafe extern "C" fn(obj: *mut DisposableTraitObject, p: *const Point) -> *mut ErrorRepr,

    /// The trait object.
    trait_object: DisposableTraitObject
}

#[cfg(feature="cons_mode")]
impl Drop for DisposableRepr {

    fn drop(&mut self) {
        unsafe {
            (self.delete)(&mut self.trait_object);
        }
    }
}

#[cfg(feature="cons_mode")]
impl DisposableRepr {

    /// Convert to a C-friendly representation.
    #[inline]
    pub fn into_repr(comp: DisposableBox) -> DisposableRepr {
        unsafe {
            DisposableRepr {
                delete: delete_disposable_repr,
                callback: call_disposable_repr,
                trait_object: mem::transmute(comp)
            }
        }
    }

    /// Call the representation.
    #[inline]
    fn call_repr(mut self, p: &Point) -> *mut ErrorRepr {
        unsafe {
            let x = (self.callback)(&mut self.trait_object, p);
            mem::forget(self);
            x
        }
    }
}

/// Call the `DisposableBox` representation.
#[cfg(feature="cons_mode")]
unsafe extern "C" fn call_disposable_repr(comp: *mut DisposableTraitObject, p: *const Point) -> *mut ErrorRepr {
    let comp: DisposableBox = mem::transmute(*comp);
    match comp.call_box((&*p,)) {
        Result::Ok(()) => ptr::null_mut(),
        Result::Err(e) => {
            let e = ErrorRepr::new(e);
            Box::into_raw(Box::new(e))
        }
    }
}

/// Delete the `DisposableBox` representation.
#[cfg(feature="cons_mode")]
unsafe extern "C" fn delete_disposable_repr(comp: *mut DisposableTraitObject) {
    let _: DisposableBox = mem::transmute(*comp);
}

#[cfg(feature="cons_mode")]
impl Disposable for DisposableRepr {

    #[doc(hidden)]
    #[inline]
    fn dispose(self, p: &Point) -> simulation::Result<()> {
        unsafe {
            let e = self.call_repr(p);
            if e == ptr::null_mut() {
                Result::Ok(())
            } else {
                let e = ffi_error_repr_into_error(e);
                Result::Err(e)
            }
        }
    }
}

/// The `Disposable` constructed by the specified function.
#[derive(Clone)]
pub struct Cons<F> {

    /// The function that disposes the subscription.
    f: F
}

impl<F> Disposable for Cons<F>
    where F: FnOnce(&Point) -> simulation::Result<()>
{
    #[doc(hidden)]
    #[inline]
    fn dispose(self, p: &Point) -> simulation::Result<()> {
        let Cons { f } = self;
        f(p)
    }
}

/// An empty `Disposable` that disposes nothing.
#[derive(Clone)]
pub struct Empty {}

impl Disposable for Empty {

    #[doc(hidden)]
    #[inline]
    fn dispose(self, _p: &Point) -> simulation::Result<()> {
        Result::Ok(())
    }
}

/// A merge of two `Disposable` computations.
#[derive(Clone)]
pub struct Merge<M, U> {

    /// The current computation.
    disposable: M,

    /// Another computation.
    other: U
}

impl<M, U> Disposable for Merge<M, U>
    where M: Disposable,
          U: Disposable
{
    #[doc(hidden)]
    #[inline]
    fn dispose(self, p: &Point) -> simulation::Result<()> {
        let Merge { disposable, other } = self;
        disposable.dispose(p)?;
        other.dispose(p)
    }
}

/// An event that calls the `Disposable` computation.
#[derive(Clone)]
pub struct DisposableEvent<D> {

    /// The disposable computation.
    disposable: D
}

impl<D> Event for DisposableEvent<D>
    where D: Disposable
{
    type Item = ();

    #[doc(hidden)]
    #[inline]
    fn call_event(self, p: &Point) -> simulation::Result<Self::Item> {
        let DisposableEvent { disposable } = self;
        disposable.dispose(p)
    }
}

/// A concatenation of the `Disposable` computations.
#[derive(Clone)]
pub struct Concat<I, M> {

    /// The disposable computations.
    disposables: I,

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

impl<I, M> Disposable for Concat<I, M>
    where I: Iterator<Item = M>,
          M: Disposable
{
    #[doc(hidden)]
    #[inline]
    fn dispose(self, p: &Point) -> simulation::Result<()> {
        let Concat { disposables, _phantom } = self;
        for disposable in disposables {
            disposable.dispose(p)?;
        }
        Result::Ok(())
    }
}

/// Trace the computation.
#[must_use = "computations are lazy and do nothing unless to be run"]
#[derive(Clone)]
pub struct Trace<M> {

    /// The computation.
    comp: M,

    /// The message to print.
    msg: String
}

impl<M> Disposable for Trace<M>
    where M: Disposable
{
    #[doc(hidden)]
    #[inline]
    fn dispose(self, p: &Point) -> simulation::Result<()> {
        let Trace { comp, msg } = self;
        p.trace(&msg);
        comp.dispose(p)
    }
}