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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#![deny(missing_docs)]
/*!
See [README.md]
**/

mod sys;

pub use self::sys::types::{Net, Node, State};

use self::sys::functions::*;

/// A wrapper type for net to support managing multiple states for simulations.
pub struct SimulatedNet {
    net: Box<Net>,
    states: Vec<State<'static>>,
}

impl std::ops::Deref for SimulatedNet {
    type Target = Net;
    fn deref(&self) -> &Net {
        &self.net
    }
}

impl State<'_> {
    /// Get a list of newly fireable transitions in the specified direction since the last call of this method.
    /// Automatically clears that list.
    pub fn added_transitions(&mut self, forward: bool) -> Box<[u32]> {
        unsafe {
            let mut count = std::mem::uninitialized();
            pnsState_addedTransitions(self, &mut count, std::ptr::null_mut(), forward);
            let mut transitions = Vec::with_capacity(count as usize);
            transitions.set_len(count as usize);
            pnsState_addedTransitions(self, &mut count, transitions.as_mut_ptr(), forward);
            transitions.into_boxed_slice()
        }
    }

    /// Get a list of nomore fireable transitions in the specified direction since the last call of this method.
    /// Automatically clears that list.
    pub fn removed_transitions(&mut self, forward: bool) -> Box<[u32]> {
        unsafe {
            let mut count = std::mem::uninitialized();
            pnsState_removedTransitions(self, &mut count, std::ptr::null_mut(), forward);
            let mut transitions = Vec::with_capacity(count as usize);
            transitions.set_len(count as usize);
            pnsState_removedTransitions(self, &mut count, transitions.as_mut_ptr(), forward);
            transitions.into_boxed_slice()
        }
    }
}

/// A dynamic type, able to store both net kinds.
pub enum DynamicNet {
    /// Variant for the default `Net` type.
    Default(Net),
    /// Variant for the `SimulatedNet` type.
    Simulated(SimulatedNet),
}

/// A trait to share safe functionality for the default `Net` type and the `SimulatedNet`
pub trait SafeNet {
    /// Save the petri net to a file. Result represents success.
    fn save(&self, filename: &str) -> bool;
    /// A slice of nodes representing the transitions of the petri net.
    fn transitions(&self) -> &[Node];
    /// A slice of nodes representing the places of the petri net.
    fn places(&self) -> &[Node];
    /// A slice of initial token counts for the places of the petri net.
    fn initial_token_counts(&self) -> &[u32];

    /// Add a new place to the petri net and get the index.
    fn add_place(&mut self) -> u32;

    /// Add a new transition to the petri net and get the index.
    fn add_transition(&mut self) -> u32;

    /// Add a new transition to the petri net, connct it to the specified places and get the index.
    fn add_connected_transition(&mut self, pids: &[u32]) -> u32;

    /// Remove a place at index `pid` from petri net.
    fn remove_place(&mut self, pid: u32);

    /// Make a connection out from the transitoin with index `tid` to place with index `pid`.
    /// Result represents success.
    fn connect_out(&mut self, tid: u32, pid: u32) -> bool;

    /// Make a connection into transition with index `tid` from place with index `pid`.
    fn disconnect_in(&mut self, tid: u32, pid: u32);

    /// Duplicate the transition and get the index of the clone.
    fn duplicate_transition(&mut self, tid: u32) -> u32;

    /// Duplicate the place and get the index of the clone.
    fn duplicate_place(&mut self, pid: u32) -> u32;

    /// Increase the initial token count in place indexed by `pid`.
    fn start(&mut self, pid: u32, count: u32) -> u32;

    /// Creates a dynamic net type from a net.
    fn dynamic(self) -> DynamicNet;
}

impl DynamicNet {
    /// Convert the dynamic net into a `Net`
    pub fn default(&self) -> Option<&Net> {
        if let DynamicNet::Default(net) = self {
            Some(net)
        } else {
            None
        }
    }
    /// Convert the dynamic net into a mutable `Net`
    pub fn default_mut(&mut self) -> Option<&mut Net> {
        if let DynamicNet::Default(net) = self {
            Some(net)
        } else {
            None
        }
    }
    /// Convert the dynamic net into a `SimulatedNet`
    pub fn simulated(&self) -> Option<&SimulatedNet> {
        if let DynamicNet::Simulated(net) = self {
            Some(net)
        } else {
            None
        }
    }
    /// Convert the dynamic net into a mutable `SimulatedNet`
    pub fn simulated_mut(&mut self) -> Option<&mut SimulatedNet> {
        if let DynamicNet::Simulated(net) = self {
            Some(net)
        } else {
            None
        }
    }
    /// Convert the dynamic net into a `SafeNet`
    pub fn safe(&self) -> &SafeNet {
        match self {
            DynamicNet::Default(net) => net,
            DynamicNet::Simulated(net) => net,
        }
    }
    /// Convert the dynamic net into a mutable `SafeNet`
    pub fn safe_mut(&mut self) -> &mut SafeNet {
        match self {
            DynamicNet::Default(net) => net,
            DynamicNet::Simulated(net) => net,
        }
    }
}

impl SimulatedNet {
    /// Convert a `Net` to a `SimulatedNet` for advanced simulation.
    pub fn new(net: Net) -> SimulatedNet {
        let mut net = net;
        unsafe { pnsNet_clearEdits(&mut net) }
        SimulatedNet {
            net: Box::new(net),
            states: Vec::new(),
        }
    }

    /// Call methods on the net and and a vector of states of it.
    /// To fill the vector use `with`.
    pub fn with_ref<'net, F: FnMut(&'net Net, &Vec<State<'net>>)>(&self, mut f: F)
    where
        Self: 'net,
    {
        unsafe {
            let net = std::mem::transmute::<_, &&Net>(&self.net);
            let states = std::mem::transmute(&self.states);
            f(*net, states)
        }
    }

    /// Call methods on the net and and a mutable vector of states of it.
    /// This way new states can be added to the vector.
    pub fn with<'net, F: FnMut(&'net Net, &mut Vec<State<'net>>)>(&mut self, mut f: F)
    where
        Self: 'net,
    {
        unsafe {
            let net = std::mem::transmute::<_, &&Net>(&self.net);
            let states = std::mem::transmute(&mut self.states);
            f(*net, states)
        }
    }

    /// Supply a closure to it, which takes a reference to a net nad create a state to be added.
    /// This way it's even easier to add elements to a net.
    pub fn add<'net, F: FnMut(&'net Net) -> State<'net>>(&mut self, mut f: F)
    where
        Self: 'net,
    {
        unsafe {
            let net = std::mem::transmute::<_, &&Net>(&self.net);
            self.states.push(std::mem::transmute(f(*net)));
        }
    }

    /// A simple way to add a default state to the net.
    pub fn add_state<'net>(&mut self)
    where
        Self: 'net,
    {
        self.add(|net| State::new(net));
    }

    /// Calculate the number of states.
    pub fn len(&self) -> usize {
        self.states.len()
    }

    /// Access all states.
    pub fn states<'net>(&'net self) -> &[State<'net>] {
        unsafe { std::mem::transmute(&self.states[..]) }
    }

    /// Access all states mutable.
    pub fn states_mut<'net>(&'net mut self) -> &mut [State<'net>] {
        unsafe { std::mem::transmute(&mut self.states[..]) }
    }

    /// Release the `Net` from the `SimulatedNet` again.
    pub fn release(self) -> Net {
        *self.net
    }

    // ensure all states are updated
    fn update_states(&mut self) {
        for state in &mut self.states {
            unsafe {
                pnsState_updateEdits(state);
            }
        }
        unsafe { pnsNet_clearEdits(&mut *self.net) }
    }
}

impl SafeNet for SimulatedNet {
    #[inline]
    fn save(&self, filename: &str) -> bool {
        self.net.save(filename)
    }

    #[inline]
    fn transitions(&self) -> &[Node] {
        self.net.transitions()
    }
    #[inline]
    fn places(&self) -> &[Node] {
        self.net.places()
    }
    #[inline]
    fn initial_token_counts(&self) -> &[u32] {
        self.net.initial_token_counts()
    }

    #[inline]
    fn add_place(&mut self) -> u32 {
        let result = self.net.add_place();;
        self.update_states();
        result
    }
    #[inline]
    fn add_transition(&mut self) -> u32 {
        let result = self.net.add_transition();
        self.update_states();
        result
    }
    #[inline]
    fn add_connected_transition(&mut self, pids: &[u32]) -> u32 {
        let result = self.net.add_connected_transition(pids);
        self.update_states();
        result
    }

    #[inline]
    fn remove_place(&mut self, pid: u32) {
        let result = self.net.remove_place(pid);
        self.update_states();
        result
    }

    #[inline]
    fn connect_out(&mut self, tid: u32, pid: u32) -> bool {
        let result = self.net.connect_out(tid, pid);
        self.update_states();
        result
    }
    #[inline]
    fn disconnect_in(&mut self, tid: u32, pid: u32) {
        let result = self.net.disconnect_in(tid, pid);
        self.update_states();
        result
    }

    #[inline]
    fn duplicate_transition(&mut self, tid: u32) -> u32 {
        let result = self.net.duplicate_transition(tid);
        self.update_states();
        result
    }
    #[inline]
    fn duplicate_place(&mut self, pid: u32) -> u32 {
        let result = self.net.duplicate_place(pid);
        self.update_states();
        result
    }
    #[inline]
    fn start(&mut self, pid: u32, count: u32) -> u32 {
        let result = self.net.start(pid, count);
        self.update_states();
        result
    }

    fn dynamic(self) -> DynamicNet {
        DynamicNet::Simulated(self)
    }
}

use std::ffi::CString;

impl Node {
    /// Get a slice of indices to the next nodes.
    pub fn next(&self) -> &[u32] {
        unsafe { std::slice::from_raw_parts(self.next, self.next_count as usize) }
    }

    /// Get a slice of indices to the previous nodes.
    pub fn prev(&self) -> &[u32] {
        unsafe { std::slice::from_raw_parts(self.prev, self.prev_count as usize) }
    }
}

impl Net {
    /// Create a new, empty petri net.
    pub fn new() -> Net {
        unsafe {
            let mut net = std::mem::uninitialized();
            pnsCreateNet(&mut net);
            net
        }
    }
    /// Load a petri net from a file.
    pub fn load(filename: &str) -> Option<Net> {
        unsafe {
            let mut net: Net = std::mem::uninitialized();
            if pnsLoadNet(&mut net, CString::new(filename).unwrap().as_ptr()) {
                Some(net)
            } else {
                std::mem::forget(net);
                None
            }
        }
    }
    /// Remove a transition at index `tid` from petri net.
    pub fn remove_transition(&mut self, tid: u32) {
        assert!(tid < self.transition_count, "Transition id out of range");
        unsafe { pnsNet_removeTransition_unsafe(self, tid) }
    }
    /// Make a connection into transition with index `tid` from place with index `pid`.
    /// Result represents success.
    pub fn connect_in(&mut self, tid: u32, pid: u32) -> bool {
        assert!(tid < self.transition_count, "Transition id out of range");
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_connectIn_unsafe(self, tid, pid) }
    }
    /// Remove the connection out from transition with index `tid` to place with index `pid`.
    pub fn disconnect_out(&mut self, tid: u32, pid: u32) {
        assert!(tid < self.transition_count, "Transition id out of range");
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_disconnectOut_unsafe(self, tid, pid) }
    }
}

impl SafeNet for Net {
    fn save(&self, filename: &str) -> bool {
        unsafe { pnsNet_save(self, CString::new(filename).unwrap().as_ptr()) }
    }

    fn transitions(&self) -> &[Node] {
        unsafe { std::slice::from_raw_parts(self.transitions, self.transition_count as usize) }
    }
    fn places(&self) -> &[Node] {
        unsafe { std::slice::from_raw_parts(self.places, self.place_count as usize) }
    }
    fn initial_token_counts(&self) -> &[u32] {
        unsafe { std::slice::from_raw_parts(self.initial_token_counts, self.place_count as usize) }
    }

    fn add_place(&mut self) -> u32 {
        unsafe { pnsNet_addPlace(self) }
    }
    fn add_transition(&mut self) -> u32 {
        unsafe { pnsNet_addTransition(self) }
    }
    fn add_connected_transition(&mut self, pids: &[u32]) -> u32 {
        for pid in pids {
            assert!(*pid < self.place_count, "Place id out of range");
        }
        unsafe { pnsNet_addConnectedTransition(self, pids.len() as u32, pids.as_ptr()) }
    }

    fn remove_place(&mut self, pid: u32) {
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_removePlace(self, pid) }
    }

    fn connect_out(&mut self, tid: u32, pid: u32) -> bool {
        assert!(tid < self.transition_count, "Transition id out of range");
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_connectOut(self, tid, pid) }
    }
    fn disconnect_in(&mut self, tid: u32, pid: u32) {
        assert!(tid < self.transition_count, "Transition id out of range");
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_disconnectIn(self, tid, pid) }
    }

    fn duplicate_transition(&mut self, tid: u32) -> u32 {
        assert!(tid < self.transition_count, "Transition id out of range");
        unsafe { pnsNet_duplicateTransition(self, tid) }
    }
    fn duplicate_place(&mut self, pid: u32) -> u32 {
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_duplicatePlace(self, pid) }
    }
    fn start(&mut self, pid: u32, count: u32) -> u32 {
        assert!(pid < self.place_count, "Place id out of range");
        unsafe { pnsNet_start(self, pid, count) }
    }

    fn dynamic(self) -> DynamicNet {
        DynamicNet::Default(self)
    }
}

impl Clone for Net {
    fn clone(&self) -> Self {
        unsafe {
            let mut net = std::mem::uninitialized();
            pnsCloneNet(&mut net, self);
            net
        }
    }
}

impl Drop for Net {
    fn drop(&mut self) {
        unsafe {
            pnsDestroyNet(self);
        }
    }
}

impl<'net> State<'net> {
    /// Create a new, empty state for simulation of a petri net.
    /// The state is bound to the lifetime of the simulated net.
    pub fn new(net: &'net Net) -> State<'net> {
        unsafe {
            let mut state = std::mem::uninitialized();
            pnsCreateState(&mut state, net);
            state
        }
    }
    /// Load a simulation state from a file.
    /// Using the wrong file layout will fail or create confusing state.
    pub fn load(net: &'net Net, filename: &str) -> Option<State<'net>> {
        unsafe {
            let mut state = std::mem::uninitialized();
            if pnsLoadState(&mut state, net, CString::new(filename).unwrap().as_ptr()) {
                Some(state)
            } else {
                std::mem::forget(net);
                None
            }
        }
    }
    /// Save the current state of the simulation.
    pub fn save(&self, filename: &str) -> bool {
        unsafe { pnsState_save(self, CString::new(filename).unwrap().as_ptr()) }
    }
    /// List the current call counts of all transitions.
    /// Counts are counted down again when playing backwards.
    pub fn call_counts(&self) -> &[u32] {
        unsafe { std::slice::from_raw_parts(self.call_counts, self.net.transition_count as usize) }
    }
    /// List the current token counts of all transitions.
    pub fn token_counts(&self) -> &[u32] {
        unsafe { std::slice::from_raw_parts(self.token_counts, self.net.place_count as usize) }
    }

    /// Generate a `FireState` to fire a transition later.
    pub fn fire<'state>(&'state mut self) -> FireState<'net, 'state> {
        FireState::new(self)
    }
    /// Reverse the play direction. Result represents forward.
    pub fn reverse(&mut self) -> bool {
        unsafe { pnsState_reverse(self) }
    }
}

impl Clone for State<'_> {
    fn clone(&self) -> Self {
        unsafe {
            let mut state = std::mem::uninitialized();
            pnsCloneState(&mut state, self);
            state
        }
    }
}

impl Drop for State<'_> {
    fn drop(&mut self) {
        unsafe {
            pnsDestroyState(self);
        }
    }
}

/// A temporary object for selecting a transition to fire.
pub struct FireState<'net, 'state> {
    state: &'state mut State<'net>,
    /// A slice of indices of the current available transitions.
    pub transitions: Box<[u32]>,
}

impl<'net, 'state> FireState<'net, 'state> {
    fn new(state: &'state mut State<'net>) -> Self {
        unsafe {
            let mut count = std::mem::uninitialized();
            pnsState_transitions(state, &mut count, std::ptr::null_mut());
            let mut transitions = Vec::with_capacity(count as usize);
            transitions.set_len(count as usize);
            pnsState_transitions(state, &mut count, transitions.as_mut_ptr());
            FireState {
                state,
                transitions: transitions.into_boxed_slice(),
            }
        }
    }
    /// Finish the fire by specifying the index of the transition index inside the slice of available indices.
    /// Not using the index of the transition directly may seem weird, but this way it's easy and efficient to ensure, no invalid transition will be called.
    /// And nomrally you know the index anyway and you save the work to get the index manually.
    /// As a result you get back your original state.
    pub fn finish(self, id: u32) {
        unsafe {
            pnsState_fire(self.state, self.transitions[id as usize]);
        }
    }
}