From f8f5dd0d4fa2ae4d48894a186491b8cc0d95aa1a Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Mon, 4 Nov 2024 21:49:23 +0100 Subject: [PATCH] add fake connection to C API --- .../examples/lang_c/include/servicepoint.h | 14 ++++++++++++++ .../servicepoint_binding_c/src/connection.rs | 18 +++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/servicepoint_binding_c/examples/lang_c/include/servicepoint.h b/crates/servicepoint_binding_c/examples/lang_c/include/servicepoint.h index 0d716d1..ca57468 100644 --- a/crates/servicepoint_binding_c/examples/lang_c/include/servicepoint.h +++ b/crates/servicepoint_binding_c/examples/lang_c/include/servicepoint.h @@ -1201,6 +1201,20 @@ SPCommand *sp_command_hard_reset(void); */ SPCommand *sp_command_try_from_packet(SPPacket *packet); +/** + * Creates a new instance of [SPConnection] for testing that does not actually send anything. + * + * returns: a new instance. Will never return NULL. + * + * # Safety + * + * The caller has to make sure that: + * + * - the returned instance is freed in some way, either by using a consuming function or + * by explicitly calling `sp_connection_free`. + */ +SPConnection *sp_connection_fake(void); + /** * Closes and deallocates a [SPConnection]. * diff --git a/crates/servicepoint_binding_c/src/connection.rs b/crates/servicepoint_binding_c/src/connection.rs index 3f54438..8b31243 100644 --- a/crates/servicepoint_binding_c/src/connection.rs +++ b/crates/servicepoint_binding_c/src/connection.rs @@ -3,7 +3,7 @@ //! prefix `sp_connection_` use std::ffi::{c_char, CStr}; -use std::ptr::null_mut; +use std::ptr::{null_mut, NonNull}; use crate::{SPCommand, SPPacket}; @@ -46,6 +46,22 @@ pub unsafe extern "C" fn sp_connection_open( Box::into_raw(Box::new(SPConnection(connection))) } +/// Creates a new instance of [SPConnection] for testing that does not actually send anything. +/// +/// returns: a new instance. Will never return NULL. +/// +/// # Safety +/// +/// The caller has to make sure that: +/// +/// - the returned instance is freed in some way, either by using a consuming function or +/// by explicitly calling `sp_connection_free`. +#[no_mangle] +pub unsafe extern "C" fn sp_connection_fake() -> NonNull { + let result = Box::new(SPConnection(servicepoint::Connection::Fake)); + NonNull::from(Box::leak(result)) +} + /// Sends a [SPPacket] to the display using the [SPConnection]. /// /// The passed `packet` gets consumed.