Struct wstp::Link

source ·
pub struct Link { /* private fields */ }
Expand description

WSTP link endpoint.

WSClose() is called on the underlying WSLINK when Drop::drop() is called for a value of this type.

WSTP C API Documentation: WSLINK

Wolfram Language Documentation: LinkObject

Implementations§

source

pub fn wait(&mut self) -> Result<(), Error>

WSTP C API Documentation: WSWaitForLinkActivity

source

pub fn wait_with_callback<F>(&mut self, callback: F) -> Result<bool, Error>
where F: FnMut(&mut Link) -> ControlFlow<()> + Send + Sync,

Wait for data to become available, periodically calling a callback.

true will be returned if data is available. false will be returned if the callback returns Break.

Example
use wstp::{Link, Protocol};

let mut listener = Link::listen(Protocol::IntraProcess, "").unwrap();

let mut counter = 0;

listener
    .wait_with_callback(|_: &mut Link| {
        use std::ops::ControlFlow;

        counter += 1;

        if counter < 5 {
            ControlFlow::Continue(())
        } else {
            ControlFlow::Break(())
        }
    })
    .unwrap();
User data fields

This function will temporarily replace any user data values (set using Link::set_user_data) which are associated with the current link. The user data values on the &mut Link parameter inside the callback are an implementation detail of this function and must not be modified.

WSTP C API Documentation: WSWaitForLinkActivityWithCallback

source

pub fn get_type(&self) -> Result<TokenType, Error>

Get the type of the next token available to read on this link.

See also Link::get_token().

source

pub fn get_token(&mut self) -> Result<Token<'_>, Error>

Read the next token from this link.

See also Link::get_type().

Example

Read the expression {5, "second", foo} from a link one Token at a time:

use wstp::{Link, Token};

// Put {5, "second", foo}
let mut link = Link::new_loopback().unwrap();
link.put_function("System`List", 3).unwrap();
link.put_i64(5).unwrap();
link.put_str("second").unwrap();
link.put_symbol("Global`foo").unwrap();

// Read it back
assert!(matches!(link.get_token().unwrap(), Token::Function { length: 3 }));
assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "System`List"));
assert!(matches!(link.get_token().unwrap(), Token::Integer(5)));
assert!(matches!(link.get_token().unwrap(), Token::String(s) if s.as_str() == "second"));
assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "Global`foo"));
source

pub fn get_raw_type(&self) -> Result<i32, Error>

Get the raw type of the next token available to read on this link.

If the returned type is WSTKERR, an error is returned.

See also Link::get_type().

WSTP C API Documentation: WSGetType()

source

pub fn get_string_ref<'link>( &'link mut self ) -> Result<LinkStr<'link, str>, Error>

WSTP C API Documentation: WSGetUTF8String()

source

pub fn get_string(&mut self) -> Result<String, Error>

Convenience wrapper around Link::get_string_ref().

source

pub fn get_symbol_ref<'link>( &'link mut self ) -> Result<LinkStr<'link, str>, Error>

WSTP C API Documentation: WSGetUTF8Symbol()

source

pub fn get_utf8_str<'link>( &'link mut self ) -> Result<LinkStr<'link, Utf8Str>, Error>

WSTP C API Documentation: WSGetUTF8String()

source

pub fn get_utf16_str<'link>( &'link mut self ) -> Result<LinkStr<'link, Utf16Str>, Error>

WSTP C API Documentation: WSGetUTF16String()

source

pub fn get_utf32_str<'link>( &'link mut self ) -> Result<LinkStr<'link, Utf32Str>, Error>

WSTP C API Documentation: WSGetUTF32String()

source

pub fn test_head(&mut self, symbol: &str) -> Result<usize, Error>

Check that the incoming expression is a function with head symbol.

If the check succeeds, the number of elements in the incoming expression is returned. Otherwise, an error is returned.

Example
use wstp::Link;

#[derive(Debug, PartialEq)]
struct Quantity {
    value: f64,
    unit: String,
}

fn get_quantity(link: &mut Link) -> Result<Quantity, wstp::Error> {
    // Use test_head() to verify that the incoming expression has the expected
    // head.
    let argc = link.test_head("System`Quantity")?;

    assert!(argc == 2, "expected Quantity to have 2 arguments");

    let value = link.get_f64()?;
    let unit = link.get_string()?;

    Ok(Quantity { value, unit })
}

let mut link = Link::new_loopback().unwrap();
link.put_function("System`Quantity", 2).unwrap();
link.put_f64(5.0).unwrap();
link.put_str("Seconds").unwrap();

assert_eq!(
    get_quantity(&mut link),
    Ok(Quantity { value: 5.0, unit: "Seconds".into() })
);
source

pub fn test_head_cstr(&mut self, symbol: &CStr) -> Result<usize, Error>

Check that the incoming expression is a function with head symbol.

This method is an optimized variant of Link::test_head().

source

pub fn get_arg_count(&mut self) -> Result<usize, Error>

WSTP C API Documentation: WSGetArgCount()

source

pub fn get_i64(&mut self) -> Result<i64, Error>

WSTP C API Documentation: WSGetInteger64()

source

pub fn get_i32(&mut self) -> Result<i32, Error>

WSTP C API Documentation: WSGetInteger32()

source

pub fn get_i16(&mut self) -> Result<i16, Error>

WSTP C API Documentation: WSGetInteger16()

source

pub fn get_u8(&mut self) -> Result<u8, Error>

WSTP C API Documentation: WSGetInteger8()

source

pub fn get_f64(&mut self) -> Result<f64, Error>

WSTP C API Documentation: WSGetReal64()

source

pub fn get_f32(&mut self) -> Result<f32, Error>

WSTP C API Documentation: WSGetReal32()

source

pub fn get_i64_array(&mut self) -> Result<Array<'_, i64>, Error>

Get a multidimensional array of i64.

Example
use wstp::Link;

let mut link = Link::new_loopback().unwrap();

link.put_i64_array(&[1, 2, 3, 4], &[2, 2]).unwrap();

let out = link.get_i64_array().unwrap();

assert_eq!(out.data().len(), 4);
assert_eq!(out.dimensions(), &[2, 2]);

WSTP C API Documentation: WSGetInteger64Array()

source

pub fn get_i32_array(&mut self) -> Result<Array<'_, i32>, Error>

WSTP C API Documentation: WSGetInteger32Array()

source

pub fn get_i16_array(&mut self) -> Result<Array<'_, i16>, Error>

WSTP C API Documentation: WSGetInteger16Array()

source

pub fn get_u8_array(&mut self) -> Result<Array<'_, u8>, Error>

WSTP C API Documentation: WSGetInteger8Array()

source

pub fn get_f64_array(&mut self) -> Result<Array<'_, f64>, Error>

Get a multidimensional array of f64.

Example
use wstp::Link;

let mut link = Link::new_loopback().unwrap();

link.put_f64_array(&[3.141, 1.618, 2.718], &[3]).unwrap();

let out = link.get_f64_array().unwrap();

assert_eq!(out.data().len(), 3);
assert_eq!(out.data(), &[3.141, 1.618, 2.718]);
assert_eq!(out.dimensions(), &[3]);

WSTP C API Documentation: WSGetReal64Array()

source

pub fn get_f32_array(&mut self) -> Result<Array<'_, f32>, Error>

WSTP C API Documentation: WSGetReal32Array()

source

pub fn put_raw_type(&mut self, type_: i32) -> Result<(), Error>

TODO: Augment this function with a put_type() method which takes a (non-exhaustive) enum value.

WSTP C API Documentation: WSPutType()

source

pub fn end_packet(&mut self) -> Result<(), Error>

WSTP C API Documentation: WSEndPacket()

source

pub fn put_str(&mut self, string: &str) -> Result<(), Error>

WSTP C API Documentation: WSPutUTF8String()

source

pub fn put_symbol(&mut self, symbol: &str) -> Result<(), Error>

WSTP C API Documentation: WSPutUTF8Symbol()

source

pub fn put_utf8_str(&mut self, utf8: &[u8]) -> Result<(), Error>

WSTP C API Documentation: WSPutUTF8String()

This function will return a WSTP error if utf8 is not a valid UTF-8 encoded string.

source

pub fn put_utf16_str(&mut self, utf16: &[u16]) -> Result<(), Error>

Put a UTF-16 encoded string.

This function will return a WSTP error if utf16 is not a valid UTF-16 encoded string.

WSTP C API Documentation: WSPutUTF16String()

source

pub fn put_utf32_str(&mut self, utf32: &[u32]) -> Result<(), Error>

Put a UTF-32 encoded string.

This function will return a WSTP error if utf32 is not a valid UTF-32 encoded string.

WSTP C API Documentation: WSPutUTF32String()

source

pub fn put_function<'h, H: Into<Option<&'h str>>>( &mut self, head: H, count: usize ) -> Result<(), Error>

Begin putting a function onto this link.

Examples

Put the expression {1, 2, 3} on the link:

let mut link = Link::new_loopback()?;

link.put_function("System`List", 3)?;
link.put_i64(1)?;
link.put_i64(2)?;
link.put_i64(3)?;

Put the expression foo["a"]["b"] on the link:

let mut link = Link::new_loopback()?;

link.put_function(None, 1)?;
link.put_function("Global`foo", 1)?;
link.put_str("a")?;
link.put_str("b")?;
source

pub fn put_arg_count(&mut self, count: usize) -> Result<(), Error>

WSTP C API Documentation: WSPutArgCount()

source

pub fn put_i64(&mut self, value: i64) -> Result<(), Error>

WSTP C API Documentation: WSPutInteger64()

source

pub fn put_i32(&mut self, value: i32) -> Result<(), Error>

WSTP C API Documentation: WSPutInteger32()

source

pub fn put_i16(&mut self, value: i16) -> Result<(), Error>

WSTP C API Documentation: WSPutInteger16()

source

pub fn put_u8(&mut self, value: u8) -> Result<(), Error>

WSTP C API Documentation: WSPutInteger8()

source

pub fn put_f64(&mut self, value: f64) -> Result<(), Error>

WSTP C API Documentation: WSPutReal64()

source

pub fn put_f32(&mut self, value: f32) -> Result<(), Error>

WSTP C API Documentation: WSPutReal32()

source

pub fn put_i64_array( &mut self, data: &[i64], dimensions: &[usize] ) -> Result<(), Error>

Put a multidimensional array of i64.

Panics

This function will panic if the product of dimensions is not equal to data.len().

WSTP C API Documentation: WSPutInteger64Array()

source

pub fn put_i32_array( &mut self, data: &[i32], dimensions: &[usize] ) -> Result<(), Error>

Put a multidimensional array of i32.

Panics

This function will panic if the product of dimensions is not equal to data.len().

WSTP C API Documentation: WSPutInteger32Array()

source

pub fn put_i16_array( &mut self, data: &[i16], dimensions: &[usize] ) -> Result<(), Error>

Put a multidimensional array of i16.

Panics

This function will panic if the product of dimensions is not equal to data.len().

WSTP C API Documentation: WSPutInteger16Array()

source

pub fn put_u8_array( &mut self, data: &[u8], dimensions: &[usize] ) -> Result<(), Error>

WSTP C API Documentation: WSPutInteger8Array()

source

pub fn put_f64_array( &mut self, data: &[f64], dimensions: &[usize] ) -> Result<(), Error>

Put a multidimensional array of f64.

Panics

This function will panic if the product of dimensions is not equal to data.len().

WSTP C API Documentation: WSPutReal64Array()

source

pub fn put_f32_array( &mut self, data: &[f32], dimensions: &[usize] ) -> Result<(), Error>

Put a multidimensional array of f32.

Panics

This function will panic if the product of dimensions is not equal to data.len().

WSTP C API Documentation: WSPutReal32Array()

source

pub fn put_eval_packet(&mut self, expr: &Expr) -> Result<(), Error>

Put an EvaluatePacket[expr] onto the link.

source

pub unsafe fn unchecked_ref_cast_mut(from: &mut WSLINK) -> &mut Self

Transmute a &mut WSLINK into a &mut Link.

This operation enables usage of the safe Link wrapper type without assuming ownership over the underying raw WSLINK.

Use this function to construct a Link from a borrowed WSLINK. This function should be used in LibraryLink functions loaded via LibraryFunctionLoad instead of Link::unchecked_new().

Safety

For this operation to be safe, the caller must ensure:

  • the WSLINK is validly initialized.
  • they have unique ownership of the WSLINK value; no aliasing is possible.

and the maintainer of this functionality must ensure:

  • The Link type is a #[repr(transparent)] wrapper around around a single field of type WSLINK.
source

pub fn new_loopback() -> Result<Self, Error>

Create a new Loopback type link.

WSTP C API Documentation: WSLoopbackOpen()

source

pub fn listen(protocol: Protocol, name: &str) -> Result<Self, Error>

Create a new named WSTP link using protocol.

source

pub fn connect(protocol: Protocol, name: &str) -> Result<Self, Error>

Connect to an existing named WSTP link.

source

pub fn tcpip_listen<A: ToSocketAddrs>(addr: A) -> Result<Self, Error>

Create a new WSTP TCPIP link bound to addr.

If addr yields multiple addresses, listening will be attempted with each of the addresses until one succeeds and returns the listener. If none of the addresses succeed in creating a listener, the error returned from the last attempt (the last address) is returned.

source

pub fn tcpip_connect<A: ToSocketAddrs>(addr: A) -> Result<Self, Error>

Connect to an existing WSTP TCPIP link listening at addr.

If addr yields multiple addresses, a connection will be attempted with each of the addresses until a connection is successful. If none of the addresses result in a successful connection, the error returned from the last connection attempt (the last address) is returned.

Open a WSTP Protocol::TCPIP connection to a LinkServer.

If addrs yields multiple addresses, a connection will be attempted with each of the addresses until a connection is successful. If none of the addresses result in a successful connection, the error returned from the last connection attempt (the last address) is returned.

source

pub fn connect_with_options( protocol: Protocol, name: &str, options: &[&str] ) -> Result<Self, Error>

source

pub fn open_with_args(args: &[&str]) -> Result<Self, Error>

WSTP C API Documentation: WSOpenArgcArgv()

This function can be used to create a Link of any protocol and mode. Prefer to use one of the constructor methods listed below when you know the type of link to be created.

source

pub unsafe fn unchecked_new(raw_link: WSLINK) -> Self

Construct a Link from a raw WSLINK pointer.

source

pub fn activate(&mut self) -> Result<(), Error>

WSTP C API Documentation: WSActivate()

source

pub fn close(self)

Close this end of the link.

WSTP C API Documentation: WSClose()

Get the name of this link.

WSTP C API Documentation: WSLinkName()

source

pub fn is_ready(&self) -> bool

Check if there is data ready to be read from this link.

WSTP C API Documentation: WSReady()

source

pub fn is_loopback(&self) -> bool

WSTP C API Documentation: WSIsLinkLoopback()

source

pub fn error(&self) -> Option<Error>

Returns an Error describing the last error to occur on this link.

Examples

TODO: Example of getting an error code.

source

pub fn error_message(&self) -> Option<String>

Returns a string describing the last error to occur on this link.

TODO: If the most recent operation was successful, does the error message get cleared?

WSTP C API Documentation: WSErrorMessage()

source

pub fn clear_error(&mut self)

Clear errors on this link.

WSTP C API Documentation: WSClearError()

WSTP C API Documentation: WSLINK

source

pub unsafe fn user_data(&self) -> (*mut c_void, WSUserFunction)

WSTP C API Documentation: WSUserData

source

pub unsafe fn set_user_data( &mut self, data_obj: *mut c_void, user_func: WSUserFunction )

WSTP C API Documentation: WSSetUserData

source

pub fn is_message_ready(&self) -> bool

Returns true if there is an out-of-band urgent message available to read.

WSTP C API Documentation: WSMessageReady()

source

pub fn put_message(&mut self, message: UrgentMessage) -> Result<(), Error>

Send an out-of-band message.

WSTP C API Documentation: WSPutMessage()

use wstp::{Protocol, UrgentMessage};

let (mut a, mut b) = wstp::channel(Protocol::SharedMemory).unwrap();

a.put_message(UrgentMessage::ABORT).unwrap();

assert_eq!(b.get_message(), Some(UrgentMessage::ABORT));
source

pub fn get_message(&mut self) -> Option<UrgentMessage>

This function does not block if no urgent message is available.

WSTP C API Documentation: WSGetMessage()

source

pub fn flush(&mut self) -> Result<(), Error>

Flush out any buffers containing data waiting to be sent on this link.

WSTP C API Documentation: WSFlush()

source

pub fn raw_get_next(&mut self) -> Result<i32, Error>

WSTP C API Documentation: WSGetNext()

source

pub fn raw_next_packet(&mut self) -> Result<i32, Error>

WSTP C API Documentation: WSNextPacket()

source

pub fn new_packet(&mut self) -> Result<(), Error>

WSTP C API Documentation: WSNewPacket()

source

pub fn get_expr(&mut self) -> Result<Expr, Error>

Read an expression off of this link.

source

pub fn put_expr(&mut self, expr: &Expr) -> Result<(), Error>

Write an expression to this link.

source

pub fn transfer_expr_to(&mut self, dest: &mut Link) -> Result<(), Error>

Transfer an expression from this link to another.

Example

Transfer an expression between two loopback links:

use wstp::Link;

let mut a = Link::new_loopback().unwrap();
let mut b = Link::new_loopback().unwrap();

// Put an expression into `a`
a.put_i64(5).unwrap();

// Transfer it to `b`
a.transfer_expr_to(&mut b).unwrap();

assert_eq!(b.get_i64().unwrap(), 5);

WSTP C API Documentation: WSTransferExpression()

Transfer the full contents of this loopback link to dest.

WSTP C API Documentation: WSTransferToEndOfLoopbackLink()

Panics

This function will panic if !self.is_loopback().

Trait Implementations§

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Safety

Links can be sent between threads, but they cannot be used from multiple threads at once (unless WSEnableLinkLock() has been called on the link). So Link satisfies Send but not Sync.

TODO: Add a wrapper type for Link which enforces that WSEnableLinkLock() has been called, and implements Sync.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.