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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
// Copyright (C) 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

//! SIMICS APIs for event management

#![allow(clippy::not_unsafe_ptr_arg_deref)]

use crate::{
    simics_exception,
    sys::{
        cycles_t, event_class_t, SIM_event_cancel_step, SIM_event_cancel_time,
        SIM_event_find_next_cycle, SIM_event_find_next_step, SIM_event_find_next_time,
        SIM_event_post_cycle, SIM_event_post_step, SIM_event_post_time, SIM_register_event,
    },
    ConfClass, ConfObject, Error, PcStep, Result,
};
use raw_cstr::raw_cstr;
use std::{ffi::c_void, ptr::null_mut};
use typed_builder::TypedBuilder;

/// Flags for an event
pub use crate::api::sys::event_class_flag_t as EventClassFlag;
/// Alias for `event_class_t`
pub type EventClass = event_class_t;
/// Alias for `cycles_t`
pub type Cycles = cycles_t;

/// A callable closure which receives a pointer to the triggering object when an event
/// occurs
pub type EventCallbackClosure = Box<dyn FnMut(*mut ConfObject)>;
/// A callback which is called to determine whether action should be taken on an event
pub type EventFilterClosure = Box<dyn Fn(*mut c_void) -> i32>;

extern "C" fn event_callback_handler(obj: *mut ConfObject, cb: *mut c_void) {
    let closure = Box::leak(unsafe { Box::from_raw(cb as *mut EventCallbackClosure) });
    closure(obj)
}

extern "C" fn event_destroy_handler(_: *mut ConfObject, cb: *mut c_void) {
    let _ = unsafe { Box::from_raw(cb as *mut EventCallbackClosure) };
    // NOTE: _ dropped
}

extern "C" fn event_filter_handler(data: *mut c_void, callback: *mut c_void) -> i32 {
    let closure = Box::leak(unsafe { Box::from_raw(callback as *mut EventFilterClosure) });
    closure(data)
}
#[derive(TypedBuilder, Debug, Clone)]
/// Simplified event management mechanism using dynamic dispatch to circumvent complex trait
/// requirements due to difference in callback specification and post time when using the
/// canonical SIMICS APIs
pub struct Event {
    #[builder(setter(into))]
    #[allow(unused)]
    /// The name of the event. This should identify the event uniquely.
    name: String,
    #[allow(unused)]
    /// The class the event will be posted for. This should be the class that is *posting* the
    /// events, not the class the events are posting on. For example, if you are implementing
    /// a module, `cls` should be the main class in your module.
    cls: *mut ConfClass,
    #[builder(default = EventClassFlag(0), setter(into))]
    #[allow(unused)]
    /// Flags of the event. Should either be 0 (the default), which indicates the event should not
    /// be saved, or [`simics::api::sys::Sim_EC_Notsaved`] which indicates this may not be saved
    /// in the configuration.
    flags: EventClassFlag,
    #[builder(default = register_event(&name, cls, flags).expect("Failed to register event"))]
    event_class: *mut EventClass,
}

impl Event {
    /// Return the class an event is posted for
    pub fn cls(&self) -> *mut ConfClass {
        self.cls
    }

    /// Return the class of this event
    pub fn event_class(&self) -> *mut EventClass {
        self.event_class
    }

    /// Register a new event to be posted for objects of class cl, and
    /// returns the event class to be used in other calls.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the event to register for
    /// * `cls` - The class events will be posted for objects of
    /// * `flags` - Flags describing the events
    ///
    /// # Context
    ///
    /// Global Context
    pub fn register<S>(name: S, cls: *mut ConfClass, flags: EventClassFlag) -> Result<Self>
    where
        S: AsRef<str>,
    {
        Ok(Self {
            name: name.as_ref().to_string(),
            cls,
            flags,
            event_class: register_event(name, cls, flags)?,
        })
    }

    /// An event of evclass for object obj is posted on clock to occur at a given point in
    /// the future. The user_data will be associated with the event.  The clock is the
    /// object that should be used for keeping track of time for the event.  It can be a
    /// processor or an instance of the clock class.
    ///
    /// If a configuration class was specified when evclass was registered, then obj must be
    /// an instance of that class.
    ///
    /// The expiration point can be specified in seconds, cycles or steps by using the
    /// appropriate call, and these values are relative to the current state. Events that
    /// need to run synchronized (Sim_EC_Machine_Sync) can only be posted in seconds or
    /// cycles, not steps, since synchronization can only be perform in virtual time.
    ///
    /// Note: Events posted with SIM_event_post_cycle are posted at a certain point in time
    /// based on the clock's current frequency, not at a certain clock cycle. The difference
    /// is significant if the frequency of the clock object can change dynamically.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event is being posted on
    /// * `clock` - The clock whose time this event is being posted for
    /// * `seconds` - The number of seconds until this event expires
    /// * `callback` - Callback to run for this event
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn post_time<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        seconds: f64,
        callback: F,
    ) -> Result<()>
    where
        F: FnMut(*mut ConfObject) + 'static,
    {
        event_post_time(clock, self.event_class, obj, seconds, callback)
    }

    /// All unexpired evclass events posted for obj on clock for which pred returns nonzero
    /// will be cancelled and their destructor methods (if any) called. pred will be called
    /// with the data associated with the event and the supplied match_data. If pred is null
    /// (None in Python), all evclass events for obj on clock will be cancelled.
    ///
    /// There are separate calls for events posted at a point in time (cycle or seconds) and
    /// on a specific step.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event was posted on
    /// * `clock` - The clock the event to cancel was posted on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn cancel_time(&self, obj: *mut ConfObject, clock: *mut ConfObject) -> Result<()> {
        event_cancel_time::<Box<dyn Fn(*mut c_void) -> i32>>(clock, self.event_class, obj, None)
    }

    #[deprecated = "Filter function will not be freed. This will lead to memory leaks."]
    /// All unexpired evclass events posted for obj on clock for which pred returns nonzero
    /// will be cancelled and their destructor methods (if any) called. pred will be called
    /// with the data associated with the event and the supplied match_data. If pred is null
    /// (None in Python), all evclass events for obj on clock will be cancelled.
    ///
    /// There are separate calls for events posted at a point in time (cycle or seconds) and
    /// on a specific step.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event was posted on
    /// * `clock` - The clock the event to cancel was posted on
    /// * `filter` - The filter function. Note that there is a limitation currently
    ///   which does not allow this filter function to be freed once it is boxed, which can
    ///   lead to memory leaks, so this method is deprecated as a warning.
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn cancel_time_filter<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        filter: Option<F>,
    ) -> Result<()>
    where
        F: Fn(*mut c_void) -> i32 + 'static,
    {
        event_cancel_time(clock, self.event_class, obj, filter)
    }

    /// An event of evclass for object obj is posted on clock to occur at a given point in
    /// the future. The user_data will be associated with the event.  The clock is the
    /// object that should be used for keeping track of time for the event.  It can be a
    /// processor or an instance of the clock class.
    ///
    /// If a configuration class was specified when evclass was registered, then obj must be
    /// an instance of that class.
    ///
    /// The expiration point can be specified in seconds, cycles or steps by using the
    /// appropriate call, and these values are relative to the current state. Events that
    /// need to run synchronized (Sim_EC_Machine_Sync) can only be posted in seconds or
    /// cycles, not steps, since synchronization can only be perform in virtual time.
    ///
    /// Note: Events posted with SIM_event_post_cycle are posted at a certain point in time
    /// based on the clock's current frequency, not at a certain clock cycle. The difference
    /// is significant if the frequency of the clock object can change dynamically.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event is being posted on
    /// * `clock` - The clock whose time this event is being posted for
    /// * `steps` - The number of seconds until this event expires
    /// * `callback` - Callback to run for this event
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn post_step<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        steps: PcStep,
        callback: F,
    ) -> Result<()>
    where
        F: FnMut(*mut ConfObject) + 'static,
    {
        event_post_step(clock, self.event_class, obj, steps, callback)
    }

    /// All unexpired evclass events posted for obj on clock for which pred returns nonzero
    /// will be cancelled and their destructor methods (if any) called. pred will be called
    /// with the data associated with the event and the supplied match_data. If pred is null
    /// (None in Python), all evclass events for obj on clock will be cancelled.
    ///
    /// There are separate calls for events posted at a point in time (cycle or seconds) and
    /// on a specific step.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event was posted on
    /// * `clock` - The clock the event to cancel was posted on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn cancel_step(&self, obj: *mut ConfObject, clock: *mut ConfObject) -> Result<()> {
        event_cancel_step::<Box<dyn Fn(*mut c_void) -> i32>>(clock, self.event_class, obj, None)
    }

    #[deprecated = "Filter function will not be freed. This will lead to memory leaks."]
    /// All unexpired evclass events posted for obj on clock for which pred returns nonzero
    /// will be cancelled and their destructor methods (if any) called. pred will be called
    /// with the data associated with the event and the supplied match_data. If pred is null
    /// (None in Python), all evclass events for obj on clock will be cancelled.
    ///
    /// There are separate calls for events posted at a point in time (cycle or seconds) and
    /// on a specific step.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event was posted on
    /// * `clock` - The clock the event to cancel was posted on
    /// * `filter` - The filter function. Note that there is a limitation currently
    ///   which does not allow this filter function to be freed once it is boxed, which can
    ///   lead to memory leaks, so this method is deprecated as a warning.
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn cancel_step_filter<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        filter: Option<F>,
    ) -> Result<()>
    where
        F: Fn(*mut c_void) -> i32 + 'static,
    {
        event_cancel_step(clock, self.event_class, obj, filter)
    }

    /// An event of evclass for object obj is posted on clock to occur at a given point in
    /// the future. The user_data will be associated with the event.  The clock is the
    /// object that should be used for keeping track of time for the event.  It can be a
    /// processor or an instance of the clock class.
    ///
    /// If a configuration class was specified when evclass was registered, then obj must be
    /// an instance of that class.
    ///
    /// The expiration point can be specified in seconds, cycles or steps by using the
    /// appropriate call, and these values are relative to the current state. Events that
    /// need to run synchronized (Sim_EC_Machine_Sync) can only be posted in seconds or
    /// cycles, not steps, since synchronization can only be perform in virtual time.
    ///
    /// Note: Events posted with SIM_event_post_cycle are posted at a certain point in time
    /// based on the clock's current frequency, not at a certain clock cycle. The difference
    /// is significant if the frequency of the clock object can change dynamically.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object the event is being posted on
    /// * `clock` - The clock whose time this event is being posted for
    /// * `cycles` - The number of seconds until this event expires
    /// * `callback` - Callback to run for this event
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn post_cycle<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        cycles: Cycles,
        callback: F,
    ) -> Result<()>
    where
        F: FnMut(*mut ConfObject) + 'static,
    {
        event_post_cycle(clock, self.event_class, obj, cycles, callback)
    }

    /// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
    /// on clock for which pred is true, or −1 if no event matched. pred will be called with
    /// the data associated with the event and the supplied match_data. If pred is null (None
    /// in Python), the first evclass event for obj on clock will be used.
    ///
    /// There are separate calls of events posted at a point in time (cycle or seconds) and
    /// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
    /// preliminary estimate; the number of remaining cycles will change if the clock's
    /// frequency changes dynamically. To handle dynamically changing clock frequencies
    /// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
    /// interface.
    ///
    /// # Arguments
    ///
    /// * `clock` - The clock for the posted event
    /// * `obj` - The object posted on
    ///
    /// # Return Value
    ///
    /// If found, the cycle number the event will next trigger on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn find_next_time(&self, obj: *mut ConfObject, clock: *mut ConfObject) -> Result<f64> {
        event_find_next_time::<Box<dyn Fn(*mut c_void) -> i32>>(clock, self.event_class, obj, None)
    }

    /// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
    /// on clock for which pred is true, or −1 if no event matched. pred will be called with
    /// the data associated with the event and the supplied match_data. If pred is null (None
    /// in Python), the first evclass event for obj on clock will be used.
    ///
    /// There are separate calls of events posted at a point in time (cycle or seconds) and
    /// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
    /// preliminary estimate; the number of remaining cycles will change if the clock's
    /// frequency changes dynamically. To handle dynamically changing clock frequencies
    /// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
    /// interface.
    ///
    /// # Arguments
    ///
    /// * `clock` - The clock for the posted event
    /// * `obj` - The object posted on
    /// * `filter` - A function to filter objects by returning true or false
    ///
    /// # Return Value
    ///
    /// If found, the cycle number the event will next trigger on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn find_next_time_filter<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        filter: F,
    ) -> Result<f64>
    where
        F: Fn(*mut c_void) -> i32 + 'static,
    {
        event_find_next_time(clock, self.event_class, obj, Some(filter))
    }

    /// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
    /// on clock for which pred is true, or −1 if no event matched. pred will be called with
    /// the data associated with the event and the supplied match_data. If pred is null (None
    /// in Python), the first evclass event for obj on clock will be used.
    ///
    /// There are separate calls of events posted at a point in time (cycle or seconds) and
    /// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
    /// preliminary estimate; the number of remaining cycles will change if the clock's
    /// frequency changes dynamically. To handle dynamically changing clock frequencies
    /// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
    /// interface.
    ///
    /// # Arguments
    ///
    /// * `clock` - The clock for the posted event
    /// * `obj` - The object posted on
    ///
    /// # Return Value
    ///
    /// If found, the cycle number the event will next trigger on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn find_next_cycle(&self, obj: *mut ConfObject, clock: *mut ConfObject) -> Result<Cycles> {
        event_find_next_cycle::<Box<dyn Fn(*mut c_void) -> i32>>(clock, self.event_class, obj, None)
    }

    /// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
    /// on clock for which pred is true, or −1 if no event matched. pred will be called with
    /// the data associated with the event and the supplied match_data. If pred is null (None
    /// in Python), the first evclass event for obj on clock will be used.
    ///
    /// There are separate calls of events posted at a point in time (cycle or seconds) and
    /// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
    /// preliminary estimate; the number of remaining cycles will change if the clock's
    /// frequency changes dynamically. To handle dynamically changing clock frequencies
    /// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
    /// interface.
    ///
    /// # Arguments
    ///
    /// * `clock` - The clock for the posted event
    /// * `obj` - The object posted on
    /// * `filter` - A function to filter objects by returning true or false
    ///
    /// # Return Value
    ///
    /// If found, the cycle number the event will next trigger on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn find_next_cycle_filter<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        filter: F,
    ) -> Result<Cycles>
    where
        F: Fn(*mut c_void) -> i32 + 'static,
    {
        event_find_next_cycle(clock, self.event_class, obj, Some(filter))
    }

    /// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
    /// on clock for which pred is true, or −1 if no event matched. pred will be called with
    /// the data associated with the event and the supplied match_data. If pred is null (None
    /// in Python), the first evclass event for obj on clock will be used.
    ///
    /// There are separate calls of events posted at a point in time (cycle or seconds) and
    /// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
    /// preliminary estimate; the number of remaining cycles will change if the clock's
    /// frequency changes dynamically. To handle dynamically changing clock frequencies
    /// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
    /// interface.
    ///
    /// # Arguments
    ///
    /// * `clock` - The clock for the posted event
    /// * `obj` - The object posted on
    ///
    /// # Return Value
    ///
    /// If found, the cycle number the event will next trigger on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn find_next_step(&self, obj: *mut ConfObject, clock: *mut ConfObject) -> Result<PcStep> {
        event_find_next_step::<Box<dyn Fn(*mut c_void) -> i32>>(clock, self.event_class, obj, None)
    }

    /// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
    /// on clock for which pred is true, or −1 if no event matched. pred will be called with
    /// the data associated with the event and the supplied match_data. If pred is null (None
    /// in Python), the first evclass event for obj on clock will be used.
    ///
    /// There are separate calls of events posted at a point in time (cycle or seconds) and
    /// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
    /// preliminary estimate; the number of remaining cycles will change if the clock's
    /// frequency changes dynamically. To handle dynamically changing clock frequencies
    /// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
    /// interface.
    ///
    /// # Arguments
    ///
    /// * `clock` - The clock for the posted event
    /// * `obj` - The object posted on
    /// * `filter` - A function to filter objects by returning true or false
    ///
    /// # Return Value
    ///
    /// If found, the cycle number the event will next trigger on
    ///
    /// # Context
    ///
    /// Cell Context
    pub fn find_next_step_filter<F>(
        &self,
        obj: *mut ConfObject,
        clock: *mut ConfObject,
        filter: F,
    ) -> Result<PcStep>
    where
        F: Fn(*mut c_void) -> i32 + 'static,
    {
        event_find_next_step(clock, self.event_class, obj, Some(filter))
    }
}

#[simics_exception]
/// Registers events identified by name and to be posted for objects of class cl, and
/// returns the event class to be used in other calls. Callbacks are provided when
/// posting events individually, this function registers a FFI callback compatible with the
/// closure parameters for posting events.
///
/// The supplied methods are:
///
/// * `callback` - Called when the event expires.
/// * `destroy` - Called when the event is removed from the queue without being called.
/// The method is not allowed to use any event API calls; it is mainly intended for
/// freeing event data. May be null.
/// * `describe` - Called to generate a human-readable description of the event to be
/// used in the print-event-queue command.
///
/// Null function pointers correspond to the value None when invoked from Python.
///
/// The flags is typically either zero or [`EventFlags::Sim_EC_Notsaved`], where
/// [`EventFlags::Sim_EC_Notsaved`] indicates that the event should not be saved as part
/// of the configuration.
///
/// # Arguments
///
/// * `name` - The name of the event to register for
/// * `cls` - The class events will be posted for objects of
/// * `flags` - Flags describing the events
///
/// # Context
///
/// Global Context
fn register_event<S>(name: S, cls: *mut ConfClass, flags: EventClassFlag) -> Result<*mut EventClass>
where
    S: AsRef<str>,
{
    let event = unsafe {
        SIM_register_event(
            raw_cstr(name.as_ref())?,
            cls,
            flags,
            Some(event_callback_handler),
            // NOTE: Destroy callback frees the callback itself
            Some(event_destroy_handler),
            None,
            None,
            None,
        )
    };

    Ok(event)
}

#[simics_exception]
/// An event of evclass for object obj is posted on clock to occur at a given point in
/// the future. The user_data will be associated with the event.  The clock is the
/// object that should be used for keeping track of time for the event.  It can be a
/// processor or an instance of the clock class.
///
/// If a configuration class was specified when evclass was registered, then obj must be
/// an instance of that class.
///
/// The expiration point can be specified in seconds, cycles or steps by using the
/// appropriate call, and these values are relative to the current state. Events that
/// need to run synchronized (Sim_EC_Machine_Sync) can only be posted in seconds or
/// cycles, not steps, since synchronization can only be perform in virtual time.
///
/// Note: Events posted with SIM_event_post_cycle are posted at a certain point in time
/// based on the clock's current frequency, not at a certain clock cycle. The difference
/// is significant if the frequency of the clock object can change dynamically.
///
/// # Arguments
///
/// * `clock` - The clock whose time this event is being posted for
/// * `event` - The event class registered with [`register_event`] being posted
/// * `obj` - The object the event is being posted on
/// * `seconds` - The number of seconds until this event expires
/// * `callbacks` - Callbacks to run for this event
///
/// # Context
///
/// Cell Context
pub fn event_post_time<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    seconds: f64,
    callback: F,
) where
    F: FnMut(*mut ConfObject) + 'static,
{
    let callbacks: EventCallbackClosure = Box::new(callback);
    let callbacks_box = Box::new(callbacks);
    let callbacks_raw = Box::into_raw(callbacks_box);

    unsafe { SIM_event_post_time(clock, event, obj, seconds, callbacks_raw as *mut c_void) };
}

#[simics_exception]
/// An event of evclass for object obj is posted on clock to occur at a given point in
/// the future. The user_data will be associated with the event.  The clock is the
/// object that should be used for keeping track of time for the event.  It can be a
/// processor or an instance of the clock class.
///
/// If a configuration class was specified when evclass was registered, then obj must be
/// an instance of that class.
///
/// The expiration point can be specified in seconds, cycles or steps by using the
/// appropriate call, and these values are relative to the current state. Events that
/// need to run synchronized (Sim_EC_Machine_Sync) can only be posted in seconds or
/// cycles, not steps, since synchronization can only be perform in virtual time.
///
/// Note: Events posted with SIM_event_post_cycle are posted at a certain point in time
/// based on the clock's current frequency, not at a certain clock cycle. The difference
/// is significant if the frequency of the clock object can change dynamically.
///
/// # Arguments
///
/// * `clock` - The clock whose time this event is being posted for
/// * `event` - The event class registered with [`register_event`] being posted
/// * `obj` - The object the event is being posted on
/// * `cycles` - The number of seconds until this event expires
/// * `callbacks` - Callbacks to run for this event
///
/// # Context
///
/// Cell Context
pub fn event_post_cycle<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    cycles: Cycles,
    callback: F,
) where
    F: FnMut(*mut ConfObject) + 'static,
{
    let callbacks: EventCallbackClosure = Box::new(callback);
    let callbacks_box = Box::new(callbacks);
    let callbacks_raw = Box::into_raw(callbacks_box);

    unsafe { SIM_event_post_cycle(clock, event, obj, cycles, callbacks_raw as *mut c_void) };
}

#[simics_exception]
/// An event of evclass for object obj is posted on clock to occur at a given point in
/// the future. The user_data will be associated with the event.  The clock is the
/// object that should be used for keeping track of time for the event.  It can be a
/// processor or an instance of the clock class.
///
/// If a configuration class was specified when evclass was registered, then obj must be
/// an instance of that class.
///
/// The expiration point can be specified in seconds, cycles or steps by using the
/// appropriate call, and these values are relative to the current state. Events that
/// need to run synchronized (Sim_EC_Machine_Sync) can only be posted in seconds or
/// cycles, not steps, since synchronization can only be perform in virtual time.
///
/// Note: Events posted with SIM_event_post_cycle are posted at a certain point in time
/// based on the clock's current frequency, not at a certain clock cycle. The difference
/// is significant if the frequency of the clock object can change dynamically.
///
/// # Arguments
///
/// * `clock` - The clock whose time this event is being posted for
/// * `event` - The event class registered with [`register_event`] being posted
/// * `obj` - The object the event is being posted on
/// * `steps` - The number of seconds until this event expires
/// * `callback` - Callback to run for this event
///
/// # Context
///
/// Cell Context
pub fn event_post_step<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    steps: PcStep,
    callback: F,
) where
    F: FnMut(*mut ConfObject) + 'static,
{
    let callbacks: EventCallbackClosure = Box::new(callback);
    let callbacks_box = Box::new(callbacks);
    let callbacks_raw = Box::into_raw(callbacks_box);

    unsafe { SIM_event_post_step(clock, event, obj, steps, callbacks_raw as *mut c_void) };
}

#[simics_exception]
/// All unexpired evclass events posted for obj on clock for which pred returns nonzero
/// will be cancelled and their destructor methods (if any) called. pred will be called
/// with the data associated with the event and the supplied match_data. If pred is null
/// (None in Python), all evclass events for obj on clock will be cancelled.
///
/// There are separate calls for events posted at a point in time (cycle or seconds) and
/// on a specific step.
///
/// # Arguments
///
/// * `clock` - The clock the event to cancel was posted on
/// * `event` - The event to cancel
/// * `obj` - The object the event was posted on
///
/// # Context
///
/// Cell Context
pub fn event_cancel_time<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    filter: Option<F>,
) where
    F: Fn(*mut c_void) -> i32 + 'static,
{
    let (callback, callback_data) = if let Some(filter) = filter {
        let filter: EventFilterClosure = Box::new(filter);
        let filter_box = Box::new(filter);
        (Some(event_filter_handler as _), Box::into_raw(filter_box))
    } else {
        (None, null_mut())
    };
    unsafe { SIM_event_cancel_time(clock, event, obj, callback, callback_data as *mut c_void) }
}

#[simics_exception]
/// All unexpired evclass events posted for obj on clock for which pred returns nonzero
/// will be cancelled and their destructor methods (if any) called. pred will be called
/// with the data associated with the event and the supplied match_data. If pred is null
/// (None in Python), all evclass events for obj on clock will be cancelled.
///
/// There are separate calls for events posted at a point in time (cycle or seconds) and
/// on a specific step.
///
/// # Arguments
///
/// * `clock` - The clock the event to cancel was posted on
/// * `event` - The event to cancel
/// * `obj` - The object the event was posted on
/// * `filter` - An optional closure to filter events that returns nonzero if an event
/// should be canceled or zero if it should not be canceled. If not provided, all events for class
/// `event` will be canceled.
///
/// # Context
///
/// Cell Context
pub fn event_cancel_step<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    filter: Option<F>,
) where
    F: Fn(*mut c_void) -> i32 + 'static,
{
    let (callback, callback_data) = if let Some(filter) = filter {
        let filter: EventFilterClosure = Box::new(filter);
        let filter_box = Box::new(filter);
        (Some(event_filter_handler as _), Box::into_raw(filter_box))
    } else {
        (None, null_mut())
    };
    unsafe { SIM_event_cancel_step(clock, event, obj, callback, callback_data as *mut c_void) }
}

// NOTE: There is no such function event_cancel_cycle

#[simics_exception]
/// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
/// on clock for which pred is true, or −1 if no event matched. pred will be called with
/// the data associated with the event and the supplied match_data. If pred is null (None
/// in Python), the first evclass event for obj on clock will be used.
///
/// There are separate calls of events posted at a point in time (cycle or seconds) and
/// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
/// preliminary estimate; the number of remaining cycles will change if the clock's
/// frequency changes dynamically. To handle dynamically changing clock frequencies
/// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
/// interface.
///
/// # Arguments
///
/// * `clock` - The clock for the posted event
/// * `event` - The posted event class
/// * `obj` - The object posted on
///
/// # Return Value
///
/// If found, the cycle number the event will next trigger on
///
/// # Context
///
/// Cell Context
pub fn event_find_next_cycle<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    filter: Option<F>,
) -> Result<Cycles>
where
    F: Fn(*mut c_void) -> i32 + 'static,
{
    let (callback, callback_data) = if let Some(filter) = filter {
        let filter: EventFilterClosure = Box::new(filter);
        let filter_box = Box::new(filter);
        (Some(event_filter_handler as _), Box::into_raw(filter_box))
    } else {
        (None, null_mut())
    };

    let time =
        unsafe { SIM_event_find_next_cycle(clock, event, obj, callback, callback_data as _) };

    if time == -1 {
        Err(Error::NoEventFound)
    } else {
        Ok(time)
    }
}

#[simics_exception]
/// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
/// on clock for which pred is true, or −1 if no event matched. pred will be called with
/// the data associated with the event and the supplied match_data. If pred is null (None
/// in Python), the first evclass event for obj on clock will be used.
///
/// There are separate calls of events posted at a point in time (cycle or seconds) and
/// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
/// preliminary estimate; the number of remaining cycles will change if the clock's
/// frequency changes dynamically. To handle dynamically changing clock frequencies
/// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
/// interface.
///
/// # Arguments
///
/// * `clock` - The clock for the posted event
/// * `event` - The posted event class
/// * `obj` - The object posted on
///
/// # Return Value
///
/// If found, the cycle number the event will next trigger on
///
/// # Context
///
/// Cell Context
pub fn event_find_next_time<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    filter: Option<F>,
) -> Result<f64>
where
    F: Fn(*mut c_void) -> i32 + 'static,
{
    let (callback, callback_data) = if let Some(filter) = filter {
        let filter: EventFilterClosure = Box::new(filter);
        let filter_box = Box::new(filter);
        (Some(event_filter_handler as _), Box::into_raw(filter_box))
    } else {
        (None, null_mut())
    };

    let time = unsafe { SIM_event_find_next_time(clock, event, obj, callback, callback_data as _) };

    if time == -1.0 {
        Err(Error::NoEventFound)
    } else {
        Ok(time)
    }
}

#[simics_exception]
/// Return the number of cycles/seconds/steps to the first event of evclass of obj posted
/// on clock for which pred is true, or −1 if no event matched. pred will be called with
/// the data associated with the event and the supplied match_data. If pred is null (None
/// in Python), the first evclass event for obj on clock will be used.
///
/// There are separate calls of events posted at a point in time (cycle or seconds) and
/// on a specific step. Note that the return value of SIM_event_find_next_cycle is only a
/// preliminary estimate; the number of remaining cycles will change if the clock's
/// frequency changes dynamically. To handle dynamically changing clock frequencies
/// correctly, subscribe to the frequency changes via the clock's simple_dispatcher
/// interface.
///
/// # Arguments
///
/// * `clock` - The clock for the posted event
/// * `event` - The posted event class
/// * `obj` - The object posted on
///
/// # Return Value
///
/// If found, the cycle number the event will next trigger on
///
/// # Context
///
/// Cell Context
pub fn event_find_next_step<F>(
    clock: *mut ConfObject,
    event: *mut EventClass,
    obj: *mut ConfObject,
    filter: Option<F>,
) -> Result<PcStep>
where
    F: Fn(*mut c_void) -> i32 + 'static,
{
    let (callback, callback_data) = if let Some(filter) = filter {
        let filter: EventFilterClosure = Box::new(filter);
        let filter_box = Box::new(filter);
        (Some(event_filter_handler as _), Box::into_raw(filter_box))
    } else {
        (None, null_mut())
    };

    let time = unsafe { SIM_event_find_next_step(clock, event, obj, callback, callback_data as _) };

    if time == -1 {
        Err(Error::NoEventFound)
    } else {
        Ok(time)
    }
}