Skip to main content

nautilus_plugin/surfaces/
instrument.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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
16//! Boundary-owned handle for [`InstrumentAny`].
17//!
18//! [`InstrumentAny`] is a Rust enum whose variant payloads (e.g.
19//! `FuturesContract`, `CurrencyPair`) own heap-allocated fields and
20//! cannot be `#[repr(C)]`, so the host wraps it in a `#[repr(C)]` handle
21//! that owns the boxed value and passes a borrowed pointer to the
22//! plug-in. The plug-in's thunk dereferences the handle once and hands
23//! an `&InstrumentAny` to the trait method. Mirrors the ownership
24//! contract that
25//! [`OrderBookDeltasHandle`](crate::surfaces::book::OrderBookDeltasHandle)
26//! uses for [`OrderBookDeltas`](nautilus_model::data::OrderBookDeltas).
27
28#![allow(unsafe_code)]
29
30use std::ops::Deref;
31
32use nautilus_model::instruments::InstrumentAny;
33
34/// Boundary-owned wrapper that lets [`InstrumentAny`] cross the cdylib
35/// FFI boundary by reference.
36///
37/// The host constructs an instance, hands a
38/// `*const InstrumentAnyHandle` to the plug-in for the duration of the
39/// callback, and drops the handle when the call returns. The plug-in
40/// only borrows the handle and never owns it.
41#[repr(C)]
42#[derive(Debug, Clone)]
43pub struct InstrumentAnyHandle(Box<InstrumentAny>);
44
45impl InstrumentAnyHandle {
46    /// Wraps `instrument` in a boundary-owned handle.
47    #[must_use]
48    pub fn new(instrument: InstrumentAny) -> Self {
49        Self(Box::new(instrument))
50    }
51
52    /// Returns a reference to the wrapped instrument.
53    #[must_use]
54    pub fn instrument(&self) -> &InstrumentAny {
55        &self.0
56    }
57
58    /// Consumes the wrapper and returns the inner instrument.
59    #[must_use]
60    pub fn into_inner(self) -> InstrumentAny {
61        *self.0
62    }
63}
64
65impl Deref for InstrumentAnyHandle {
66    type Target = InstrumentAny;
67
68    fn deref(&self) -> &Self::Target {
69        &self.0
70    }
71}