nautilus_common/ffi/
timer.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::ffi::c_char;
17
18use nautilus_core::{
19    ffi::string::{cstr_to_ustr, str_to_cstr},
20    UUID4,
21};
22
23use crate::timer::{TimeEvent, TimeEventCallback, TimeEventHandlerV2};
24
25#[repr(C)]
26#[derive(Clone, Debug)]
27/// Legacy time event handler for Cython/FFI inter-operatbility
28///
29/// TODO: Remove once Cython is deprecated
30///
31/// `TimeEventHandler` associates a `TimeEvent` with a callback function that is triggered
32/// when the event's timestamp is reached.
33pub struct TimeEventHandler {
34    /// The time event.
35    pub event: TimeEvent,
36    /// The callable raw pointer.
37    pub callback_ptr: *mut c_char,
38}
39
40impl From<TimeEventHandlerV2> for TimeEventHandler {
41    fn from(value: TimeEventHandlerV2) -> Self {
42        Self {
43            event: value.event,
44            callback_ptr: match value.callback {
45                TimeEventCallback::Python(callback) => callback.as_ptr().cast::<c_char>(),
46                TimeEventCallback::Rust(_) => {
47                    panic!("Legacy time event handler is not supported for Rust callback")
48                }
49            },
50        }
51    }
52}
53
54/// # Safety
55///
56/// - Assumes `name_ptr` is borrowed from a valid Python UTF-8 `str`.
57#[no_mangle]
58pub unsafe extern "C" fn time_event_new(
59    name_ptr: *const c_char,
60    event_id: UUID4,
61    ts_event: u64,
62    ts_init: u64,
63) -> TimeEvent {
64    TimeEvent::new(
65        cstr_to_ustr(name_ptr),
66        event_id,
67        ts_event.into(),
68        ts_init.into(),
69    )
70}
71
72/// Returns a [`TimeEvent`] as a C string pointer.
73#[no_mangle]
74pub extern "C" fn time_event_to_cstr(event: &TimeEvent) -> *const c_char {
75    str_to_cstr(&event.to_string())
76}
77
78// This function only exists so that `TimeEventHandler` is included in the definitions
79#[no_mangle]
80pub const extern "C" fn dummy(v: TimeEventHandler) -> TimeEventHandler {
81    v
82}