├── .cargo └── config.toml ├── .gitignore ├── .rustfmt.toml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── docs ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Development.md └── Maintenance.md ├── wstp-sys ├── .gitignore ├── Cargo.toml ├── README.md ├── build.rs ├── generated │ ├── 12.1.0 │ │ └── MacOSX-x86-64 │ │ │ └── WSTP_bindings.rs │ ├── 12.1.1 │ │ └── MacOSX-x86-64 │ │ │ └── WSTP_bindings.rs │ ├── 12.2.0 │ │ └── MacOSX-x86-64 │ │ │ └── WSTP_bindings.rs │ ├── 12.3.0 │ │ └── MacOSX-x86-64 │ │ │ └── WSTP_bindings.rs │ ├── 12.3.1 │ │ └── Windows-x86-64 │ │ │ └── WSTP_bindings.rs │ ├── 13.0.0 │ │ └── MacOSX-x86-64 │ │ │ └── WSTP_bindings.rs │ ├── 13.0.1 │ │ ├── Linux-x86-64 │ │ │ └── WSTP_bindings.rs │ │ ├── MacOSX-ARM64 │ │ │ └── WSTP_bindings.rs │ │ ├── MacOSX-x86-64 │ │ │ └── WSTP_bindings.rs │ │ └── Windows-x86-64 │ │ │ └── WSTP_bindings.rs │ └── 13.2.0 │ │ ├── Linux-ARM64 │ │ └── WSTP_bindings.rs │ │ ├── MacOSX-ARM64 │ │ └── WSTP_bindings.rs │ │ └── MacOSX-x86-64 │ │ └── WSTP_bindings.rs └── src │ └── lib.rs ├── wstp ├── Cargo.toml ├── examples │ ├── connect_to_link_server.rs │ └── link_server.rs ├── src │ ├── env.rs │ ├── error.rs │ ├── get.rs │ ├── kernel │ │ └── mod.rs │ ├── lib.rs │ ├── link_server.rs │ ├── put.rs │ ├── strx.rs │ └── wait.rs └── tests │ ├── test_link_server.rs │ ├── test_links.rs │ ├── test_loopback_links.rs │ └── test_shutdown.rs └── xtask ├── Cargo.toml └── src └── main.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [alias] 2 | xtask = "run --package xtask --" 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | 4 | # User preferences 5 | /.vscode 6 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 90 2 | comment_width = 90 3 | match_block_trailing_comma = true 4 | blank_lines_upper_bound = 2 5 | merge_derives = false 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | 4 | members = [ 5 | "wstp", 6 | "wstp-sys", 7 | # xtask convention. See: https://github.com/matklad/cargo-xtask 8 | "xtask" 9 | ] -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Wolfram Research Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wstp 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/wstp.svg)](https://crates.io/crates/wstp) 4 | ![License](https://img.shields.io/crates/l/wstp.svg) 5 | [![Documentation](https://docs.rs/wstp/badge.svg)](https://docs.rs/wstp) 6 | 7 | #### [API Documentation](https://docs.rs/CRATE-NAME) | [Changelog](./docs/CHANGELOG.md) | [Contributing](./docs/CONTRIBUTING.md) 8 | 9 | 10 | Bindings to the [Wolfram Symbolic Transfer Protocol (WSTP)](https://www.wolfram.com/wstp/). 11 | 12 | This crate provides a set of safe and ergonomic bindings to the WSTP library, used to 13 | transfer Wolfram Language expressions between programs. 14 | 15 | ## Quick Examples 16 | 17 | #### Loopback links 18 | 19 | Write an expression to a loopback [`Link`][Link], and then read it back from the same link 20 | object: 21 | 22 | ```rust 23 | use wstp::Link; 24 | 25 | fn example() -> Result<(), wstp::Error> { 26 | let mut link = Link::new_loopback()?; 27 | 28 | // Write the expression {"a", "b", "c"} 29 | link.put_function("System`List", 3)?; 30 | link.put_str("a")?; 31 | link.put_str("b")?; 32 | link.put_str("c")?; 33 | 34 | // Read back the expression, concatenating the elements as we go: 35 | let mut buffer = String::new(); 36 | 37 | for _ in 0 .. link.test_head("System`List")? { 38 | buffer.push_str(link.get_string_ref()?.as_str()) 39 | } 40 | 41 | assert_eq!(buffer, "abc"); 42 | 43 | Ok(()) 44 | } 45 | 46 | example(); 47 | ``` 48 | 49 | #### Full-duplex links 50 | 51 | Transfer the expression `"hello!"` from one [`Link`][Link] endpoint to another: 52 | 53 | ```rust 54 | use wstp::Protocol; 55 | 56 | let (mut a, mut b) = wstp::channel(Protocol::SharedMemory).unwrap(); 57 | 58 | a.put_str("hello!").unwrap(); 59 | a.flush().unwrap(); 60 | 61 | assert_eq!(b.get_string().unwrap(), "hello!"); 62 | ``` 63 | 64 | See [`wolfram-library-link`][wolfram-library-link] for 65 | [examples of using WSTP links][wstp-wll-example] to transfer expressions to and from 66 | LibraryLink functions. 67 | 68 | [wstp-wll-example]: https://github.com/WolframResearch/wolfram-library-link-rs/blob/master/wolfram-library-link/examples/wstp.rs 69 | 70 | [Link]: https://docs.rs/wstp/latest/wstp/struct.Link.html 71 | 72 | ## Building `wstp` 73 | 74 | The `wstp` crate uses [`wolfram-app-discovery`][wolfram-app-discovery] to locate a local 75 | installation of the Wolfram Language that contains a suitable copy of the WSTP SDK. If the 76 | WSTP SDK cannot be located, `wstp` will fail to build. 77 | 78 | If you have installed the Wolfram Language to a location unknown to `wolfram-app-discovery`, 79 | you may specify the installed location manually by setting the `WOLFRAM_APP_DISCOVERY` 80 | environment variable. See [Configuring wolfram-app-discovery][wad-configuration] for details. 81 | 82 | [wad-configuration]: https://github.com/WolframResearch/wolfram-app-discovery-rs#configuration 83 | 84 | ## Related Links 85 | 86 | #### Related crates 87 | 88 | * [`wolfram-library-link`][wolfram-library-link] — author libraries that can be 89 | dynamically loaded by the Wolfram Language 90 | * [`wolfram-expr`][wolfram-expr] — efficient and ergonomic representation of Wolfram 91 | expressions in Rust. 92 | * [`wolfram-app-discovery`][wolfram-app-discovery] — utility for locating local 93 | installations of Wolfram applications and the Wolfram Language. 94 | 95 | 96 | [wolfram-app-discovery]: https://crates.io/crates/wolfram-app-discovery 97 | [wolfram-library-link]: https://crates.io/crates/wolfram-library-link 98 | [wolfram-expr]: https://crates.io/crates/wolfram-expr 99 | 100 | #### Related documentation 101 | 102 | * [WSTP and External Program Communication](https://reference.wolfram.com/language/tutorial/WSTPAndExternalProgramCommunicationOverview.html) 103 | * [How WSTP Is Used](https://reference.wolfram.com/language/tutorial/HowWSTPIsUsed.html) 104 | 105 | ### Developer Notes 106 | 107 | See [**Development.md**](./docs/Development.md) for instructions on how to perform common 108 | development tasks when contributing to the `wstp` crate. 109 | 110 | See [**Maintenance.md**](./docs/Maintenance.md) for instructions on how to keep `wstp` 111 | up to date as new versions of the Wolfram Language are released. 112 | 113 | ## License 114 | 115 | Licensed under either of 116 | 117 | * Apache License, Version 2.0 118 | ([LICENSE-APACHE](LICENSE-APACHE) or ) 119 | * MIT license 120 | ([LICENSE-MIT](LICENSE-MIT) or ) 121 | 122 | at your option. 123 | 124 | Note: Licensing of the WSTP library linked by the [wstp](https://crates.io/crates/wstp) 125 | crate is covered by the terms of the 126 | [MathLink License Agreement](https://www.wolfram.com/legal/agreements/mathlink.html). 127 | 128 | ## Contribution 129 | 130 | Unless you explicitly state otherwise, any contribution intentionally submitted 131 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 132 | dual licensed as above, without any additional terms or conditions. 133 | 134 | See [CONTRIBUTING.md](./CONTRIBUTING.md) for more information. -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | 11 | ## [0.2.9] — 2023-10-07 12 | 13 | ### Fixed 14 | 15 | * Support NULL bytes in strings sent via `Link::put_str()`. ([#60]) 16 | 17 | ### Changed 18 | 19 | * Update minimum supported Rust version (MSRV) to **Rust 1.70**. Remove 20 | dependency on once_cell. ([#62]) 21 | 22 | 23 | 24 | ## [0.2.8] — 2023-08-28 25 | 26 | ### Changed 27 | 28 | * Change to always use pre-generated WSTP bindings. ([#54]) 29 | 30 | Previously, wstp-sys would use bindgen at build time to generate bindings to 31 | the WSTP library. However, this was somewhat fragile. For example, if libclang 32 | is not available on the build machine, building would fail even if WSTP was 33 | otherwise available to be linked to. 34 | 35 | Given that the wstp crate only exposes functionality from a minimum-targed 36 | WSTP version anyway, using pre-generated bindings for that specific version 37 | removes the need for bindgen at compile time (significantly reducing the 38 | dependency tree and compile times) while preserving the same functionality. 39 | 40 | [docs/Maintenance.md](./Maintenance.md) was updated with instructions on how 41 | the maintainer can manually generate bindings when wstp / wstp-sys need to be 42 | updated to support features available in newer WSTP releases. 43 | 44 | * Remove unused build dependency on `bindgen` ([#56]) 45 | 46 | ### Fixed 47 | 48 | * Fix issue with mismatched types causing build failures on Windows. ([#55]) 49 | 50 | This fixes [issue #51](https://github.com/WolframResearch/wstp-rs/issues/51). 51 | 52 | 53 | 54 | ## [0.2.7] — 2023-02-03 55 | 56 | ### Added 57 | 58 | * Add logging support to `wstp-sys/build.rs`. ([#49]) 59 | 60 | [wolfram-app-discovery v0.4.3](https://github.com/WolframResearch/wolfram-app-discovery-rs/blob/master/docs/CHANGELOG.md#043--2023-02-03) 61 | added support for logging via the Rust [`log`](https://crates.io/crates/log) 62 | logging facade library. `wstp-sys/build.rs` uses wolfram-app-discovery to find 63 | a copy of the WSTP SDK. 64 | 65 | Logging messages from `wstp-sys/build.rs` can now be enabled by setting the 66 | `RUST_LOG` environment to an appropriate value, as documented in the 67 | [`env_logger`](https://docs.rs/env_logger) crate documentation. This can help 68 | debug discovery errors that occur during a build. 69 | 70 | ### Changed 71 | 72 | * Increase `wolfram-expr` dependency version to v0.1.4. ([#49]) 73 | 74 | 75 | 76 | ## [0.2.6] — 2023-01-06 77 | 78 | ### Fixed 79 | 80 | This release fixes several causes of build failures on Linux. 81 | 82 | * Fix use of `i8` instead of `c_char` in variables bound to return values of 83 | `CStr::from_raw()` and `CString::into_raw()`. ([#45]) 84 | 85 | `c_char` is an alias for `i8` on macOS, but it is an alias for `u8` on Linux. 86 | 87 | * Fix linker errors by setting missing `-luuid` linker flag in `build.rs` 88 | on Linux. ([#46]) 89 | 90 | `libwstp` depends on the Linux `libuuid` library when targeting Linux. 91 | 92 | *On Ubuntu, `libuuid` is provided by the 93 | [`uuid-dev` package](https://packages.ubuntu.com/bionic/uuid-dev).* 94 | 95 | * Fix broken automatic discovery of `wstp.h` and `libwstp` on Linux by updating 96 | `wolfram-app-discovery` dependency version. ([#47]) 97 | 98 | 99 | 100 | ## [0.2.5] — 2023-01-03 101 | 102 | ### Added 103 | 104 | * Add new 105 | [`wstp::channel()`](https://docs.rs/wstp/0.2.5/wstp/fn.channel.html) 106 | function, for conveniently creating two connected `Link`s. ([#42]) 107 | 108 | * Added support for WSTP out-of-band urgent messages. ([#43]) 109 | 110 | Add new 111 | [`UrgentMessage`](https://docs.rs/wstp/0.2.5/wstp/struct.UrgentMessage.html) 112 | and 113 | [`UrgentMessageKind`](https://docs.rs/wstp/0.2.5/wstp/enum.UrgentMessageKind.html) 114 | types. 115 | 116 | Add new `Link` methods: 117 | 118 | - [`Link::is_message_ready()`](https://docs.rs/wstp/0.2.5/wstp/struct.Link.html#method.is_message_ready) 119 | - [`Link::put_message()`](https://docs.rs/wstp/0.2.5/wstp/struct.Link.html#method.put_message) 120 | - [`Link::get_message()`](https://docs.rs/wstp/0.2.5/wstp/struct.Link.html#method.get_message) 121 | 122 | ### Fixed 123 | 124 | * Fix issues with `WolframKernelProcess::launch()` ([#42]) 125 | 126 | - Fix use of hard-coded linkname. Now a unique linkname is generated automatically. 127 | 128 | - Remove unnecessary background thread, fixing race condition between 129 | `Link::listen()` in the background thread and the link connection in the 130 | spawned [`WolframKernel`](https://reference.wolfram.com/language/ref/program/WolframKernel) 131 | process. 132 | 133 | * Fix examples in README.md and the crate root doc comment that exhibit the 134 | same mistake as `WolframKernelProcess::launch()` bugs mentioned above. ([#42]) 135 | 136 | ### Changed 137 | 138 | * Remove redundant attrs on `Link::unchecked_ref_cast_mut()` ([#41]) 139 | 140 | *Contributed by dtolnay.* 141 | 142 | 143 | 144 | ## [0.2.4] – 2022-10-19 145 | 146 | ### Fixed 147 | 148 | * Fix `` could not find `private` in `ref_cast` `` compile errors that recently 149 | started occurring to due to changes to semver-exempt private items in the 150 | `ref-cast` dependency of `wstp`. ([#39]) 151 | 152 | Fortunately, the `ref-cast` crate recently gained a `#[ref_cast_custom]` 153 | macro, which is the missing feature that had originally required `wstp` to 154 | depend on private internal details of `ref-cast` as a workaround. 155 | 156 | 157 | 158 | ## [0.2.3] – 2022-09-19 159 | 160 | ### Changed 161 | 162 | * Mention `get_u8_array()` in the `Array` type doc comment. ([#36]) 163 | 164 | * Update `wolfram-app-discovery` dependency from 0.2.1 to v0.3.0, to take 165 | advantage of the improved flexiblity of new API functions tailored for use 166 | from build scripts. ([#37]) 167 | 168 | 169 | 170 | ## [0.2.2] – 2022-05-17 171 | 172 | ### Fixed 173 | 174 | * Fixed wstp-rs build linking issue on Apple Silicon. ([#34]) 175 | 176 | 177 | 178 | ## [0.2.1] – 2022-03-04 179 | 180 | ### Fixed 181 | 182 | * Fixed documentation build failure in the docs.rs build environment. ([#32]) 183 | 184 | 185 | 186 | ## [0.2.0] – 2022-03-03 187 | 188 | ### Added 189 | 190 | * Added Windows support for `wstp` and `wstp-sys`. ([#29]) 191 | - Add build script commands to link to WSTP interface libraries. 192 | - Use the [`link-cplusplus`](https://crates.io/crates/link-cplusplus) crate to link to 193 | the C++ standard library (required by the WSTP library) in a reliable cross-platform 194 | way. 195 | 196 | ### Changed 197 | 198 | * Changed `wstp-sys` to generate the Rust bindings to `wstp.h` at compile time. ([#30]) 199 | 200 | This ensures that the `wstp` and `wstp-sys` crates will compile with a wider range of 201 | Wolfram Language versions that provide a suitable version of the WSTP SDK. See the PR 202 | description for more info. 203 | 204 | 205 | 206 | ## [0.1.4] – 2022-02-19 207 | 208 | ### Added 209 | 210 | * Added [`WolframKernelProcess`](https://docs.rs/wstp/0.1.4/wstp/kernel/struct.WolframKernelProcess.html) 211 | struct, used to create and manage a WSTP connection to a Wolfram Kernel process. ([#24]) 212 | 213 | `WolframKernelProcess` can be combined with the 214 | [wolfram-app-discovery](https://crates.io/crates/wolfram-app-discovery) crate to easily 215 | launch a new Wolfram Kernel session with no manual configuration: 216 | 217 | ```rust 218 | use std::path::PathBuf; 219 | use wolfram_app_discovery::WolframApp; 220 | use wstp::kernel::WolframKernelProcess; 221 | 222 | // Automatically find a local Wolfram Language installation. 223 | let app = WolframApp::try_default() 224 | .expect("unable to find any Wolfram Language installations"); 225 | 226 | let exe: PathBuf = app.kernel_executable_path().unwrap(); 227 | 228 | // Create a new Wolfram Language session using this Kernel. 229 | let kernel = WolframKernelProcess::launch(&exe).unwrap(); 230 | ``` 231 | 232 | * Added [`Link::put_eval_packet()`](https://docs.rs/wstp/0.1.4/wstp/struct.Link.html#method.put_eval_packet) 233 | convenience method to perform evaluations using a connected Wolfram Kernel. ([#24]) 234 | 235 | * Added types and methods for ergonomic processing of WSTP tokens. ([#25]) 236 | 237 | A token is the basic unit of expression data that can be read from or written to a link. 238 | Use the new 239 | [`Link::get_token()`](https://docs.rs/wstp/0.1.4/wstp/struct.Link.html#method.get_token) 240 | method to ergonomically match over the 241 | [`Token`](https://docs.rs/wstp/0.1.4/wstp/enum.Token.html) 242 | that is readoff of the link: 243 | 244 | ```rust 245 | use wstp::{Link, Token}; 246 | 247 | match link.get_token()? { 248 | Token::Integer(int) => { 249 | // Do something with `int`. 250 | }, 251 | Token::Real(real) => { 252 | // Do something with `real`. 253 | }, 254 | ... 255 | } 256 | ``` 257 | 258 | * Added `Link::end_packet()` method. ([#23]) 259 | * Added `wstp::shutdown()`. ([#23]) 260 | 261 | ### Fixed 262 | 263 | * Fixed `Debug` formatting of `LinkStr` to include the string contents. ([#23]) 264 | * Upgrade `wolfram-app-discovery` dependency to v0.2.0 (adds support for app discovery on 265 | Windows). ([#25]) 266 | 267 | 268 | 269 | ## [0.1.3] – 2022-02-08 270 | 271 | ### Fixed 272 | 273 | * Fixed another `wstp-sys` build failure when built in the docs.rs environment. ([#19]) 274 | 275 | 276 | 277 | ## [0.1.2] – 2022-02-08 278 | 279 | ### Fixed 280 | 281 | * Fixed `wstp-sys` build failures when built in the docs.rs environment. ([#17]) 282 | 283 | 284 | 285 | ## [0.1.1] – 2022-02-08 286 | 287 | ### Fixed 288 | 289 | * Increase `wolfram-app-discovery` dependency version from v0.1.1 to v0.1.2 to get fix 290 | for [compilation error when compiling for non-macOS targets](https://github.com/WolframResearch/wolfram-app-discovery-rs/blob/master/docs/CHANGELOG.md#012--2022-02-08) 291 | ([#16]) 292 | 293 | 294 | 295 | ## [0.1.0] – 2022-02-08 296 | 297 | Initial release of the [`wstp`](https://crates.io/crates/wstp) crate. 298 | 299 | ### Added 300 | 301 | * [`Link`](https://docs.rs/wstp/0.1.3/wstp/struct.Link.html) struct that represents a 302 | WSTP link endpoint, and provides methods for reading and writing symbolic Wolfram 303 | Language expressions. 304 | 305 | * [`LinkServer`](https://docs.rs/wstp/0.1.3/wstp/struct.LinkServer.html) struct that 306 | represents a WSTP TCPIP link server, which binds to a port, listens for incoming 307 | connections, and creates a new `Link` for each connection. 308 | 309 | 310 | 311 | [wolfram-app-discovery]: https://crates.io/crates/wolfram-app-discovery 312 | 313 | 314 | [#16]: https://github.com/WolframResearch/wstp-rs/pull/16 315 | [#17]: https://github.com/WolframResearch/wstp-rs/pull/17 316 | [#19]: https://github.com/WolframResearch/wstp-rs/pull/19 317 | 318 | 319 | [#23]: https://github.com/WolframResearch/wstp-rs/pull/23 320 | [#24]: https://github.com/WolframResearch/wstp-rs/pull/24 321 | [#25]: https://github.com/WolframResearch/wstp-rs/pull/25 322 | 323 | 324 | [#29]: https://github.com/WolframResearch/wstp-rs/pull/29 325 | [#30]: https://github.com/WolframResearch/wstp-rs/pull/30 326 | 327 | 328 | [#32]: https://github.com/WolframResearch/wstp-rs/pull/32 329 | 330 | 331 | [#34]: https://github.com/WolframResearch/wstp-rs/pull/34 332 | 333 | 334 | [#36]: https://github.com/WolframResearch/wstp-rs/pull/36 335 | [#37]: https://github.com/WolframResearch/wstp-rs/pull/37 336 | 337 | 338 | [#39]: https://github.com/WolframResearch/wstp-rs/pull/39 339 | 340 | 341 | [#41]: https://github.com/WolframResearch/wstp-rs/pull/41 342 | [#42]: https://github.com/WolframResearch/wstp-rs/pull/42 343 | [#43]: https://github.com/WolframResearch/wstp-rs/pull/43 344 | 345 | 346 | [#45]: https://github.com/WolframResearch/wstp-rs/pull/45 347 | [#46]: https://github.com/WolframResearch/wstp-rs/pull/46 348 | [#47]: https://github.com/WolframResearch/wstp-rs/pull/47 349 | 350 | 351 | [#49]: https://github.com/WolframResearch/wstp-rs/pull/49 352 | 353 | 354 | [#54]: https://github.com/WolframResearch/wstp-rs/pull/54 355 | [#55]: https://github.com/WolframResearch/wstp-rs/pull/55 356 | [#56]: https://github.com/WolframResearch/wstp-rs/pull/56 357 | 358 | 359 | [#60]: https://github.com/WolframResearch/wstp-rs/pull/60 360 | [#62]: https://github.com/WolframResearch/wstp-rs/pull/62 361 | 362 | 363 | 364 | [Unreleased]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.9...HEAD 365 | 366 | [0.2.9]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.8...v0.2.9 367 | [0.2.8]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.7...v0.2.8 368 | [0.2.7]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.7...v0.2.7 369 | [0.2.6]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.5...v0.2.6 370 | [0.2.5]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.4...v0.2.5 371 | [0.2.4]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.3...v0.2.4 372 | [0.2.3]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.2...v0.2.3 373 | [0.2.2]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.1...v0.2.2 374 | [0.2.1]: https://github.com/WolframResearch/wstp-rs/compare/v0.2.0...v0.2.1 375 | [0.2.0]: https://github.com/WolframResearch/wstp-rs/compare/v0.1.4...v0.2.0 376 | [0.1.4]: https://github.com/WolframResearch/wstp-rs/compare/v0.1.3...v0.1.4 377 | [0.1.3]: https://github.com/WolframResearch/wstp-rs/compare/v0.1.2...v0.1.3 378 | [0.1.2]: https://github.com/WolframResearch/wstp-rs/compare/v0.1.1...v0.1.2 379 | [0.1.1]: https://github.com/WolframResearch/wstp-rs/compare/v0.1.0...v0.1.1 380 | [0.1.0]: https://github.com/WolframResearch/wstp-rs/releases/tag/v0.1.0 381 | -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Wolfram® 2 | 3 | Thank you for taking the time to contribute to the 4 | [Wolfram Research](https://github.com/wolframresearch) repositories on GitHub. 5 | 6 | ## Licensing of Contributions 7 | 8 | By contributing to Wolfram, you agree and affirm that: 9 | 10 | > Wolfram may release your contribution under the terms of the [MIT license](https://opensource.org/licenses/MIT) 11 | > AND the [Apache 2.0 license](https://opensource.org/licenses/Apache-2.0); and 12 | 13 | > You have read and agreed to the [Developer Certificate of Origin](http://developercertificate.org/), version 1.1 or later. 14 | 15 | Please see [LICENSE](LICENSE) for licensing conditions pertaining 16 | to individual repositories. 17 | 18 | 19 | ## Bug reports 20 | 21 | ### Security Bugs 22 | 23 | Please **DO NOT** file a public issue regarding a security issue. 24 | Rather, send your report privately to security@wolfram.com. Security 25 | reports are appreciated and we will credit you for it. We do not offer 26 | a security bounty, but the forecast in your neighborhood will be cloudy 27 | with a chance of Wolfram schwag! 28 | 29 | ### General Bugs 30 | 31 | Please use the repository issues page to submit general bug issues. 32 | 33 | Please do not duplicate issues. 34 | 35 | Please do send a complete and well-written report to us. Note: **the 36 | thoroughness of your report will positively correlate with our ability to address it**. 37 | 38 | When reporting issues, always include: 39 | 40 | * Your version of *Mathematica*® or the Wolfram Language. 41 | * Your operating system. 42 | -------------------------------------------------------------------------------- /docs/Development.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | This document describes information useful to anyone wishing to modify the `wstp` crate. 4 | 5 | ## Testing 6 | 7 | The `wstp` crate tests should be run using a single testing thread: 8 | 9 | ```$ shell 10 | cargo test -- --test-threads=1 11 | ``` 12 | 13 | This is necessary to prevent the `LinkServer` tests from all trying to bind to the 14 | same port from multiple threads. 15 | 16 | ## Override WSTP `CompilerAdditions` location 17 | 18 | By default, [build.rs](../build.rs) will use [`wolfram-app-discovery`][wolfram-app-discovery] 19 | to find a local installation of the Wolfram Language that contains a suitable copy of the WSTP 20 | SDK. If you wish to override the WSTP SDK `CompilerAdditions` directory that `wstp` is 21 | linked against, you may set either one of these two environment variables, depending 22 | on your use case: 23 | 24 | * `WOLFRAM_APP_DIRECTORY`. Overriding this will force `wolfram-app-discovery` to discover 25 | this application. 26 | * `WSTP_COMPILER_ADDITIONS`. Overriding this will not change the default app located by 27 | `wolfram-app-discovery`, but will change the directory linked against in 28 | [build.rs](../build.rs). This is useful if you have multiple Wolfram products installed, 29 | or if you are a developer of the WSTP C library. 30 | 31 | #### Override examples 32 | 33 | Override the `WSTP_COMPILER_ADDITIONS` location: 34 | 35 | ```shell 36 | $ export WSTP_COMPILER_ADDITIONS=/Applications/Mathematica.app/Contents/SystemFiles/Links/WSTP/DeveloperKit/MacOSX-x86-64/CompilerAdditions 37 | ``` 38 | 39 | 40 | 41 | [wolfram-app-discovery]: https://crates.io/crates/wolfram-app-discovery -------------------------------------------------------------------------------- /docs/Maintenance.md: -------------------------------------------------------------------------------- 1 | # Maintenance 2 | 3 | This document describes tasks necessary to maintain the `wstp` and `wstp-sys` crates over 4 | time. This document is informational and intended for the maintainer of these crates; 5 | users of these crates do not need to read this document. 6 | 7 | ## Generating `wstp-sys` bindings 8 | 9 | [`wstp-sys/generated/`](../wstp-sys/generated) contains pre-generated bindings to the 10 | WSTP library header file provided by a particular version of the Wolfram Language on a 11 | particular platform. Each time a new Wolfram Language version is released that makes 12 | changes to the WSTP API, the bindings stored in this crate should be regenerated. 13 | 14 | To regenerate the bindings, run the following sequence of commands on each platform that 15 | this crate targets: 16 | 17 | ```shell 18 | $ export WOLFRAM_APP_DIRECTORY=/Applications/Wolfram/Mathematica-12.3.0.app 19 | $ cargo +nightly xtask gen-bindings 20 | ``` 21 | 22 | using an appropriate path to the Wolfram product providing the new Wolfram Language 23 | version. 24 | 25 | ### Generating bindings from a particular SDK 26 | 27 | ```shell 28 | $ cargo +nightly xtask gen-bindings-from ~/Downloads/Linux-ARM64 --target aarch64-unknown-linux-gnu --wolfram-version=13.2.0 29 | ``` 30 | 31 | ## Updating build.rs bindings to use on docs.rs 32 | 33 | When `wstp-sys` is built in the environment, some special logic is required 34 | to work around the fact that no Wolfram applications are available to link to. 35 | 36 | At the moment, the [`wstp-sys/build.rs`](../wstp-sys/build.rs) file hard-codes a Wolfram 37 | version number and System ID to use as the bindings to display on docs.rs. That version 38 | number should be updated each time new `wstp-sys` bindings are generated. -------------------------------------------------------------------------------- /wstp-sys/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /wstp-sys/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wstp-sys" 3 | version = "0.2.9" 4 | authors = ["Connor Gray "] 5 | license = "MIT OR Apache-2.0" 6 | edition = "2021" 7 | readme = "README.md" 8 | repository = "https://github.com/WolframResearch/wstp-rs" 9 | description = "Low-level FFI bindings to the Wolfram Symbolic Transfer Protocol (WSTP) C API" 10 | keywords = ["wstp", "mathlink", "wolfram", "wolfram-language", "wolfram-engine"] 11 | categories = ["external-ffi-bindings", "development-tools::ffi", "encoding"] 12 | 13 | # TODO(!): Audit this. Is this the correct name? Will it always be correct? What is the 14 | # significance of the "i4" suffix -- is that a version number? 15 | links = "WSTPi4" 16 | 17 | [dependencies] 18 | link-cplusplus = "1.0.6" 19 | 20 | [build-dependencies] 21 | wolfram-app-discovery = "0.4.7" 22 | env_logger = { version = "0.10.0", default-features = false } -------------------------------------------------------------------------------- /wstp-sys/README.md: -------------------------------------------------------------------------------- 1 | # wstp-sys 2 | 3 | Low-level FFI bindings to the Wolfram Symbolic Transfer Protocol (WSTP) C API. 4 | 5 | The [`wstp`](https://crates.io/crates/wstp) crate provides efficient and idiomatic Rust 6 | bindings to WSTP based on these raw bindings. 7 | -------------------------------------------------------------------------------- /wstp-sys/build.rs: -------------------------------------------------------------------------------- 1 | //! This script links the Mathematica WSTPi4 library. 2 | //! 3 | //! It does this by finding the local Mathematica installation by using the users 4 | //! `wolframscript` to evaluate `$InstallationDirectory`. This script will fail if 5 | //! `wolframscript` is not on `$PATH`. 6 | 7 | 8 | use std::path::PathBuf; 9 | use std::process; 10 | 11 | use wolfram_app_discovery::{SystemID, WolframApp, WolframVersion}; 12 | 13 | /// Oldest Wolfram Version that wstp-rs aims to be compatible with. 14 | const WOLFRAM_VERSION: WolframVersion = WolframVersion::new(13, 0, 1); 15 | 16 | fn main() { 17 | env_logger::init(); 18 | 19 | // Ensure that changes to environment variables checked by wolfram-app-discovery will 20 | // cause cargo to rebuild the current crate. 21 | wolfram_app_discovery::config::set_print_cargo_build_script_directives(true); 22 | 23 | // This crate is being built by docs.rs. Skip trying to locate a WolframApp. 24 | // See: https://docs.rs/about/builds#detecting-docsrs 25 | if std::env::var("DOCS_RS").is_ok() { 26 | // Force docs.rs to use the bindings generated for this version / system. 27 | let bindings_path = make_bindings_path(&WOLFRAM_VERSION, SystemID::MacOSX_x86_64); 28 | 29 | // This environment variable is included using `env!()`. wstp-sys will fail to 30 | // build if it is not set correctly. 31 | println!( 32 | "cargo:rustc-env=CRATE_WSTP_SYS_BINDINGS={}", 33 | bindings_path.display() 34 | ); 35 | 36 | return; 37 | } 38 | 39 | // 40 | // Error if this is a cross compilation 41 | // 42 | 43 | let host = std::env::var("HOST").expect("expected 'HOST' env var to be set"); 44 | let target = std::env::var("TARGET").expect("expected 'TARGET' env var to be set"); 45 | 46 | // Note: `host == target` is required for the use of `cfg!(..)` in this 47 | // script to be valid. 48 | if host != target { 49 | panic!( 50 | "error: crate wstp-sys does not support cross compilation. (host: {}, target: {})", 51 | host, 52 | target 53 | ); 54 | } 55 | 56 | let app: Option = WolframApp::try_default().ok(); 57 | 58 | let target_system_id: SystemID = 59 | SystemID::try_from_rust_target(&std::env::var("TARGET").unwrap()) 60 | .expect("unable to get System ID for target system"); 61 | 62 | //------------- 63 | // Link to WSTP 64 | //------------- 65 | 66 | link_to_wstp(app.as_ref()); 67 | 68 | //---------------------------------------------------- 69 | // Generate or use pre-generated Rust bindings to WSTP 70 | //---------------------------------------------------- 71 | // See docs/Maintenance.md for instructions on how to pre-generate 72 | // bindings for new WL versions. 73 | 74 | // TODO: Update to a higher minimum WSTP version and remove this workaround. 75 | // NOTE: WSTP didn't support 64-bit ARM Linux in v13.0.1, so pre-generated 76 | // bindings aren't available. If starting Linux-ARM64, use bindings 77 | // from a newer version. (This mismatch is neglible since there were 78 | // no significant API changes to WSTP between these two versions anyway.) 79 | let wolfram_version = match target_system_id { 80 | SystemID::Linux_ARM64 => WolframVersion::new(13, 2, 0), 81 | _ => WOLFRAM_VERSION, 82 | }; 83 | 84 | // TODO: Make use of pre-generated bindings useable via a feature flag? 85 | // Using pre-generated bindings seems to currently only have a distinct 86 | // advantage over compile-time-generated bindings when building on 87 | // docs.rs, where the WSTP SDK is not available. 88 | // 89 | // In other situations, using pre-generated bindings doesn't offer the 90 | // advantage of not needing the WSTP SDK available locally, because you 91 | // still need to link against the WSTP static library. 92 | // 93 | // NOTE: Pre-generated bindings have the advantage of working when 94 | // libclang is not available (which bindgen requires), which 95 | // happens e.g. in Windows CI/CD builds. 96 | let bindings_path = use_pregenerated_bindings(wolfram_version, target_system_id); 97 | 98 | println!( 99 | "cargo:rustc-env=CRATE_WSTP_SYS_BINDINGS={}", 100 | bindings_path.display() 101 | ); 102 | } 103 | 104 | //======================================================================== 105 | // Tell `lib.rs` where to find the file containing the WSTP Rust bindings. 106 | //======================================================================== 107 | 108 | //----------------------- 109 | // Pre-generated bindings 110 | //----------------------- 111 | 112 | /// Use bindings that have been pre-generated. 113 | #[allow(dead_code)] 114 | fn use_pregenerated_bindings( 115 | wolfram_version: WolframVersion, 116 | target_system_id: SystemID, 117 | ) -> PathBuf { 118 | // FIXME: Check that this file actually exists, and generate a nicer error if it 119 | // doesn't. 120 | let bindings_path = make_bindings_path(&wolfram_version, target_system_id); 121 | 122 | println!("cargo:rerun-if-changed={}", bindings_path.display()); 123 | 124 | if !bindings_path.is_file() { 125 | println!( 126 | " 127 | ==== ERROR: wstp-sys ===== 128 | 129 | Rust bindings for Wolfram WSTP for target configuration: 130 | 131 | WolframVersion: {} 132 | SystemID: {} 133 | 134 | have not been pre-generated. 135 | 136 | See wstp-sys/generated/ for a listing of currently available targets. 137 | 138 | ========================================= 139 | ", 140 | wolfram_version, target_system_id 141 | ); 142 | panic!(""); 143 | } 144 | 145 | println!( 146 | "cargo:warning=info: using pre-generated bindings for WSTP ({wolfram_version}, {target_system_id}): {}", 147 | bindings_path.display() 148 | ); 149 | 150 | bindings_path 151 | } 152 | 153 | fn make_bindings_path(wolfram_version: &WolframVersion, system_id: SystemID) -> PathBuf { 154 | let bindings_path = PathBuf::from("generated") 155 | .join(&wolfram_version.to_string()) 156 | .join(system_id.as_str()) 157 | .join("WSTP_bindings.rs"); 158 | 159 | let absolute_bindings_path = 160 | PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join(&bindings_path); 161 | 162 | absolute_bindings_path 163 | } 164 | 165 | //====================================== 166 | // Link to WSTP 167 | //====================================== 168 | 169 | /// Emits the necessary `cargo` instructions to link to the WSTP static library, 170 | /// and also links the WSTP interface libraries (the libraries that WSTP itself 171 | /// depends on). 172 | fn link_to_wstp(app: Option<&WolframApp>) { 173 | // Path to the WSTP static library file. 174 | let static_lib = wolfram_app_discovery::build_scripts::wstp_static_library_path(app) 175 | .expect("unable to get WSTP static library path") 176 | .into_path_buf(); 177 | 178 | println!( 179 | "cargo:warning=info: linking to WSTP static lib from: {}", 180 | static_lib.display() 181 | ); 182 | 183 | link_wstp_statically(&static_lib); 184 | 185 | // 186 | // Link to the C++ standard library, required by WSTP 187 | // 188 | 189 | // Note: This is now handled by the `link-cplusplus` crate dependency. 190 | 191 | // Note: This blog post explained this, and that this might need to change on Linux. 192 | // https://flames-of-code.netlify.com/blog/rust-and-cmake-cplusplus/ 193 | // println!("cargo:rustc-link-lib=dylib=c++"); 194 | 195 | //----------------------------------- 196 | // Link to WSTP "interface" libraries 197 | //----------------------------------- 198 | 199 | // The CompilerAdditions/WSTP-targets.cmake file describes the dependencies 200 | // of the WSTP library that must be linked into the final artifact for any 201 | // code that depends on WSTP. (The contents of that file differ on each 202 | // platform). They are the `INTERFACE_LINK_LIBRARIES` of the 203 | // `WSTP::STATIC_LIBRARY` CMake target. 204 | // 205 | // On macOS, the Foundation framework is the only dependency. On Windows, 206 | // several system libraries must be linked. 207 | // 208 | // FIXME: Update this logic to cover the Linux interface libraries. 209 | 210 | // 211 | // macOS 212 | // 213 | 214 | // TODO: Look at the complete list of CMake libraries required by WSTP and update this 215 | // logic for Windows and Linux. 216 | if cfg!(target_os = "macos") { 217 | println!("cargo:rustc-link-lib=framework=Foundation"); 218 | } 219 | 220 | // 221 | // Windows 222 | // 223 | 224 | if cfg!(target_os = "windows") { 225 | println!("cargo:rustc-link-lib=dylib=kernel32"); 226 | println!("cargo:rustc-link-lib=dylib=user32"); 227 | println!("cargo:rustc-link-lib=dylib=advapi32"); 228 | println!("cargo:rustc-link-lib=dylib=comdlg32"); 229 | println!("cargo:rustc-link-lib=dylib=ws2_32"); 230 | println!("cargo:rustc-link-lib=dylib=wsock32"); 231 | println!("cargo:rustc-link-lib=dylib=rpcrt4"); 232 | } 233 | 234 | // 235 | // Linux 236 | // 237 | 238 | if cfg!(target_os = "linux") { 239 | println!("cargo:rustc-link-lib=uuid") 240 | } 241 | } 242 | 243 | fn link_wstp_statically(lib: &PathBuf) { 244 | let mut lib = lib.clone(); 245 | 246 | if cfg!(all(target_os = "macos", target_arch = "x86_64")) { 247 | lib = lipo_native_library(&lib, "x86_64"); 248 | } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) { 249 | lib = lipo_native_library(&lib, "arm64"); 250 | } 251 | 252 | link_library_file(lib); 253 | } 254 | 255 | /* NOTE: 256 | This code was necessary prior to 12.1, where the versions of WSTP in the 257 | Mathematica layout were univeral binaries containing 32-bit and 64-bit copies of 258 | the libary. However, it appears that starting with 12.1, the layout build of 259 | libWSTP is no longer a "fat" archive. (This is possibly due to the fact that macOS 260 | Catalina, released ~6 months prior, and dropped support for 32-bit applications on 261 | macOS.) 262 | 263 | I'm electing to leave this code around in the meantime, in case the situation 264 | changes, but it appears this `lipo` operation may no longer be necessary. 265 | 266 | Update: This code is still useful, because the advent of ARM macOS machines means 267 | that local development builds of WSTP will build universal x86_64 and 268 | arm64 binaries by default on macOS. 269 | */ 270 | /// Use the macOS `lipo` command to construct an x86_64 archive file from the WSTPi4.a 271 | /// file in the Mathematica layout. This is necessary as a workaround to a bug in the 272 | /// Rust compiler at the moment: https://github.com/rust-lang/rust/issues/50220. 273 | /// The problem is that WSTPi4.a is a so called "universal binary"; it's an archive 274 | /// file with multiple copies of the same library, each for a different target 275 | /// architecture. The `lipo -thin` command creates a new archive which contains just 276 | /// the library for the named architecture. 277 | fn lipo_native_library(wstp_lib: &PathBuf, lipo_arch: &str) -> PathBuf { 278 | let wstp_lib = wstp_lib 279 | .to_str() 280 | .expect("could not convert WSTP archive path to str"); 281 | 282 | // `lipo` will return an error if run on a non-universal binary, so avoid doing 283 | // that by using the `file` command to check the type of `wstp_lib`. 284 | let is_universal_binary = { 285 | let stdout = process::Command::new("file") 286 | .args(&[wstp_lib]) 287 | .output() 288 | .expect("failed to run `file` system utility") 289 | .stdout; 290 | let stdout = String::from_utf8(stdout).unwrap(); 291 | stdout.contains("Mach-O universal binary") 292 | }; 293 | 294 | if !is_universal_binary { 295 | return PathBuf::from(wstp_lib); 296 | } 297 | 298 | // Place the lipo'd library file in the system temporary directory. 299 | let output_lib = std::env::temp_dir().join("libWSTP-thin.a"); 300 | let output_lib = output_lib 301 | .to_str() 302 | .expect("could not convert WSTP archive path to str"); 303 | 304 | let output = process::Command::new("lipo") 305 | .args(&[wstp_lib, "-thin", lipo_arch, "-output", output_lib]) 306 | .output() 307 | .expect("failed to invoke macOS `lipo` command"); 308 | 309 | if !output.status.success() { 310 | panic!("unable to lipo WSTP library: {:#?}", output); 311 | } 312 | 313 | PathBuf::from(output_lib) 314 | } 315 | 316 | fn link_library_file(libfile: PathBuf) { 317 | let search_dir = libfile.parent().unwrap().display().to_string(); 318 | 319 | let libname = libfile 320 | .file_stem() 321 | .unwrap() 322 | .to_str() 323 | .unwrap() 324 | .trim_start_matches("lib"); 325 | println!("cargo:rustc-link-search={}", search_dir); 326 | println!("cargo:rustc-link-lib=static={}", libname); 327 | } 328 | -------------------------------------------------------------------------------- /wstp-sys/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow( 2 | non_snake_case, 3 | non_upper_case_globals, 4 | non_camel_case_types, 5 | improper_ctypes 6 | )] 7 | 8 | // Ensure that linker flags from link-cplusplus are used. 9 | extern crate link_cplusplus; 10 | 11 | 12 | // The name of this file comes from `build.rs`. 13 | include!(env!("CRATE_WSTP_SYS_BINDINGS")); 14 | -------------------------------------------------------------------------------- /wstp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wstp" 3 | version = "0.2.9" 4 | edition = "2021" 5 | rust-version = "1.70" # Update to 1.70 for OnceLock 6 | license = "MIT OR Apache-2.0" 7 | authors = ["Connor Gray "] 8 | readme = "../README.md" 9 | repository = "https://github.com/WolframResearch/wstp-rs" 10 | description = "Bindings to the Wolfram Symbolic Transfer Protocol (WSTP)" 11 | keywords = ["wstp", "mathlink", "wolfram", "wolfram-language", "wolfram-engine"] 12 | categories = ["external-ffi-bindings", "development-tools::ffi", "encoding"] 13 | 14 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 15 | 16 | [dependencies] 17 | wstp-sys = { version = "0.2.8", path = "../wstp-sys" } 18 | 19 | wolfram-expr = "0.1.4" 20 | 21 | ref-cast = "1.0.13" 22 | 23 | [dev-dependencies] 24 | rand = "0.8.3" 25 | wolfram-app-discovery = "0.4.1" 26 | -------------------------------------------------------------------------------- /wstp/examples/connect_to_link_server.rs: -------------------------------------------------------------------------------- 1 | //! Demonstrates making a connection to a [`LinkServer`] that is listening for incoming 2 | //! connections. 3 | //! 4 | //! See `examples/link_server.rs` for a demonstration of how to create a `LinkServer` that 5 | //! listens for incoming connections. 6 | 7 | use wstp::Link; 8 | 9 | const LOCATION: &str = "localhost:55655"; 10 | 11 | fn main() { 12 | println!("connecting..."); 13 | 14 | let mut conn = 15 | Link::connect_to_link_server(LOCATION).expect("failed to connect to LinkServer"); 16 | 17 | println!( 18 | "Was the {}(st|nd|rd|th) connection!", 19 | conn.get_i64().unwrap() 20 | ); 21 | 22 | conn.put_i64(std::process::id().into()) 23 | .expect("failed to write PID"); 24 | 25 | let _ = conn.raw_next_packet(); 26 | } 27 | -------------------------------------------------------------------------------- /wstp/examples/link_server.rs: -------------------------------------------------------------------------------- 1 | //! Demonstrates starting a [`LinkServer`] and listening for incoming connections made 2 | //! using [`Link::connect_to_link_server()`]. 3 | //! 4 | //! See `examples/connect_to_link_server.rs` for an example of making a connection to this 5 | //! link server. Run both examples in separate terminals to see connections being made. 6 | 7 | use wstp::{Link, LinkServer}; 8 | 9 | const LOCATION: &str = "localhost:55655"; 10 | 11 | fn main() { 12 | let server = LinkServer::bind(LOCATION).expect("failed to start LinkServer"); 13 | 14 | println!( 15 | "Started WSTP LinkServer at: {}:{}", 16 | server.interface(), 17 | server.port() 18 | ); 19 | println!("Process ID: {}", std::process::id()); 20 | 21 | let mut connection_count = 0; 22 | 23 | for conn in server.incoming() { 24 | let mut conn: Link = match conn { 25 | Ok(conn) => conn, 26 | Err(err) => { 27 | eprintln!("incoming connection error: {}", err); 28 | continue; 29 | }, 30 | }; 31 | 32 | connection_count += 1; 33 | println!("got connection #{}", connection_count); 34 | 35 | conn.put_i64(connection_count) 36 | .expect("failed to write to connection"); 37 | 38 | let pid = conn.get_i64().expect("expected link to send PID"); 39 | println!(" connected PID: {}", pid); 40 | 41 | conn.close(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /wstp/src/env.rs: -------------------------------------------------------------------------------- 1 | //! WSTP environment object management. 2 | //! 3 | //! It's necessary that a `WSENV` always outlive any links which are created in 4 | //! that environment. However, requiring that every [`Link`][crate::Link] be tied 5 | //! to the lifetime of a [`WstpEnv`] created by the user would make the `wstp` API 6 | //! unnecessarily burdensome. The easiest way to manage this is to have a single, 7 | //! global, shared environment instance, and use that internally in every `wstp` 8 | //! wrapper API. (This is what [`stdenv`](https://reference.wolfram.com/language/ref/c/stdenv.html) 9 | //! accomplishes for programs prepared with [`wsprep`](https://reference.wolfram.com/language/ref/program/wsprep.html)). 10 | //! 11 | //! In general, the existence of an explicit, shared WSTP environment object is a bit of 12 | //! an anachronism -- ideally it wouldn't exist at all. Much of what `WSENV` contains is 13 | //! effectively global state (e.g. signal handlers), which might better be represented as 14 | //! hidden global variables in the WSTP C library. Where possible, `wstp` should avoid 15 | //! exposing this detail of the WSTP C API. 16 | //! 17 | //! # Safety 18 | //! 19 | //! If the determination is made in the future to expose [`WstpEnv`] publically from `wstp`, 20 | //! some safety conditions will need to be satisfied: 21 | //! 22 | //! * A [`Link`][crate::Link] MUST NOT be able to outlive the `WstpEnv` that its 23 | //! creation was associated with. 24 | //! * All [`Link`][crate::Link]'s MUST be closed before the `WstpEnv` they are 25 | //! associated with is deinitialized (essentially a restatement of the first condition). 26 | 27 | use std::sync::Mutex; 28 | 29 | use crate::{sys, Error}; 30 | 31 | /// The standard WSTP environment object. 32 | /// 33 | /// *WSTP C API Documentation:* [`stdenv`](https://reference.wolfram.com/language/ref/c/stdenv.html) 34 | static STDENV: Mutex = Mutex::new(StdEnvState::Uninitialized); 35 | 36 | enum StdEnvState { 37 | /// No links have been created yet, so the lazily initialized STDENV is 38 | /// empty. 39 | Uninitialized, 40 | Initialized(WstpEnv), 41 | /// The WSTP library was shutdown so the STDENV was deinitialized and cannot 42 | /// be re-initialized. 43 | Shutdown, 44 | } 45 | 46 | /// Private. A WSTP library environment. 47 | /// 48 | /// NOTE: This function should remain private. See note on [`crate::env`]. 49 | /// 50 | /// See [`initialize()`]. 51 | /// 52 | /// *WSTP C API Documentation:* [`WSENV`](https://reference.wolfram.com/language/ref/c/WSENV.html). 53 | pub(crate) struct WstpEnv { 54 | pub raw_env: sys::WSENV, 55 | } 56 | 57 | /// FIXME: This is only valid for [`STDENV`] because we enforce exclusive access 58 | /// via [`with_raw_stdenv()`]. Other general instances of `WstpEnv` 59 | /// are not safe to send between threads. Use ForceSend? 60 | unsafe impl Send for WstpEnv {} 61 | 62 | /// Enforce unique access to the raw `STDENV` value. 63 | /// 64 | /// This prevents trying to create links stored on the same global `WSENV` 65 | /// instance in multiple threads at the same time. The `WSENV` type and WSTP API 66 | /// functions do not otherwise do synchronization when mutating `WSENV` instances. 67 | pub(crate) fn with_raw_stdenv T>( 68 | callback: F, 69 | ) -> Result { 70 | let mut guard = STDENV.lock().map_err(|err| { 71 | Error::custom(format!("Unable to acquire lock on STDENV: {}", err)) 72 | })?; 73 | 74 | if let StdEnvState::Uninitialized = *guard { 75 | *guard = StdEnvState::Initialized(WstpEnv::initialize().unwrap()) 76 | } 77 | 78 | let raw_env = match &*guard { 79 | StdEnvState::Uninitialized => unreachable!(), 80 | StdEnvState::Initialized(stdenv) => stdenv.raw_env, 81 | StdEnvState::Shutdown => { 82 | return Err(Error::custom( 83 | "wstp-rs: STDENV has been shutdown. No more links can be created." 84 | .to_owned(), 85 | )) 86 | }, 87 | }; 88 | 89 | // Call the callback during the period that we hold `guard`. 90 | let result = callback(raw_env); 91 | 92 | drop(guard); 93 | 94 | Ok(result) 95 | } 96 | 97 | 98 | /// Deinitialize the [`WSENV`] static maintained by this library. 99 | /// 100 | /// Ideally, this function would not be necessary. However, the WSTP C library internally 101 | /// launches several background threads necessary for its operation. If these threads are 102 | /// still running when the main() function returns, an ungraceful shutdown can occur, with 103 | /// error messages being printed. This function is an escape hatch to permit users of this 104 | /// library to ensure that all background thread shutdown before `main()` returns. 105 | /// 106 | /// TODO: Make this function obsolete, either by changing the WSTP C library 107 | /// implementation, or, perhaps easier, maintain a reference count of the number of 108 | /// [`Link`] objects that have been created, and (re-)initialize and deinitialize 109 | /// the `WSENV` static whenever that count rises from or falls to 0. 110 | /// 111 | /// # Safety 112 | /// 113 | /// All [`Link`] objects created by this library are associated with the global [`WSENV`] 114 | /// static used internally. Deinitializing the global `WSENV` before all [`Link`] objects 115 | /// have been dropped is not legal. Only call this function after ensuring that all 116 | /// [`Link`] objects created by your code have been dropped. 117 | #[doc(hidden)] 118 | pub unsafe fn shutdown() -> Result { 119 | let mut guard = STDENV.lock().map_err(|err| { 120 | Error::custom(format!("Unable to acquire lock on STDENV: {}", err)) 121 | })?; 122 | 123 | // Take the current state and set STDENV to Shutdown. 124 | let state = std::mem::replace(&mut *guard, StdEnvState::Shutdown); 125 | 126 | let was_initialized = match state { 127 | StdEnvState::Uninitialized => false, 128 | StdEnvState::Initialized(stdenv) => { 129 | stdenv.deinitialize(); 130 | true 131 | }, 132 | // TODO(cleanup): Should this panic instead? shutdown() shouldn't be 133 | // called more than once. 134 | StdEnvState::Shutdown => false, 135 | }; 136 | 137 | Ok(was_initialized) 138 | } 139 | 140 | impl WstpEnv { 141 | /// Private. 142 | /// 143 | /// NOTE: This function should remain private. See note on [`crate::env`]. 144 | /// 145 | /// *WSTP C API Documentation:* [`WSInitialize()`](https://reference.wolfram.com/language/ref/c/WSInitialize.html) 146 | pub(crate) fn initialize() -> Result { 147 | // TODO: Is this thread-safe? 148 | // Is it safe to call WSInitialize() multiple times in the same process? 149 | let raw_env: sys::WSENV = unsafe { sys::WSInitialize(std::ptr::null_mut()) }; 150 | 151 | if raw_env.is_null() { 152 | return Err(Error::custom( 153 | // TODO: Is there an internal error string which could be included here? 154 | format!("WSInitialize() failed"), 155 | )); 156 | } 157 | 158 | Ok(WstpEnv { raw_env }) 159 | } 160 | 161 | #[allow(dead_code)] 162 | pub(crate) fn raw_env(&self) -> sys::WSENV { 163 | let WstpEnv { raw_env } = *self; 164 | 165 | raw_env 166 | } 167 | 168 | fn deinitialize(self) { 169 | drop(self) 170 | } 171 | } 172 | 173 | impl Drop for WstpEnv { 174 | fn drop(&mut self) { 175 | let WstpEnv { raw_env } = *self; 176 | 177 | unsafe { 178 | sys::WSDeinitialize(raw_env); 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /wstp/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | ffi::CStr, 3 | fmt::{self, Debug, Display}, 4 | os::raw::c_char, 5 | }; 6 | 7 | /// WSTP link error. 8 | /// 9 | /// Use [`Error::code()`] to retrieve the WSTP error code, if applicable. 10 | #[derive(Clone, PartialEq)] 11 | pub struct Error { 12 | pub(crate) code: Option, 13 | pub(crate) message: String, 14 | } 15 | 16 | impl Error { 17 | /// Get the WSTP error code, if applicable. 18 | /// 19 | /// Possible error codes are listed in the [`WSError()`](https://reference.wolfram.com/language/ref/c/WSError.html) 20 | /// documentation. 21 | pub fn code(&self) -> Option { 22 | self.code 23 | } 24 | 25 | pub(crate) fn custom(message: String) -> Self { 26 | Error { 27 | code: None, 28 | message, 29 | } 30 | } 31 | 32 | pub(crate) fn from_code(code: i32) -> Self { 33 | // Lookup the error string describing this error code. 34 | let builtin_message: Result, Error> = 35 | crate::env::with_raw_stdenv(|stdenv| unsafe { 36 | let code_long = std::os::raw::c_long::try_from(code).unwrap(); 37 | 38 | // Note: We do not need to free this, because it's scoped to our eternal 39 | // STDENV instance. 40 | let message_cptr: *const c_char = 41 | crate::sys::WSErrorString(stdenv, code_long); 42 | 43 | if message_cptr.is_null() { 44 | return None; 45 | } 46 | 47 | let message_cstr = CStr::from_ptr(message_cptr); 48 | 49 | Some(message_cstr.to_str().ok()?.to_owned()) 50 | }); 51 | 52 | let message = match builtin_message { 53 | Ok(Some(message)) => message, 54 | Ok(None) | Err(_) => format!("WSTP error code {} occurred.", code), 55 | }; 56 | 57 | Error { 58 | code: Some(code), 59 | message, 60 | } 61 | } 62 | } 63 | 64 | impl Display for Error { 65 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 66 | let Error { code, message } = self; 67 | 68 | if let Some(code) = code { 69 | write!(f, "WSTP error (code {}): {}", code, message) 70 | } else { 71 | write!(f, "WSTP error: {}", message) 72 | } 73 | } 74 | } 75 | 76 | impl Debug for Error { 77 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 78 | // TODO: Any further information we could provide here? 79 | write!(f, "{}", self) 80 | } 81 | } 82 | 83 | impl std::error::Error for Error {} 84 | -------------------------------------------------------------------------------- /wstp/src/get.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{CStr, CString}; 2 | use std::iter::FromIterator; 3 | use std::{convert::TryFrom, fmt, os::raw::c_char}; 4 | 5 | use crate::{ 6 | sys::{ 7 | self, WSGetArgCount, WSGetInteger16, WSGetInteger32, WSGetInteger64, 8 | WSGetInteger8, WSGetReal32, WSGetReal64, WSGetUTF16String, WSGetUTF32String, 9 | WSGetUTF8String, WSReleaseUTF16String, WSReleaseUTF16Symbol, 10 | WSReleaseUTF32String, WSReleaseUTF32Symbol, WSReleaseUTF8String, 11 | WSReleaseUTF8Symbol, 12 | }, 13 | Error, Link, Utf16Str, Utf32Str, Utf8Str, 14 | }; 15 | 16 | /// Basic unit of expression data read from a [`Link`]. 17 | /// 18 | /// [`Link::get_token()`] is used to read the next available token from a [`Link`]. 19 | #[allow(missing_docs)] 20 | #[derive(Debug)] 21 | pub enum Token<'link> { 22 | Integer(i64), 23 | Real(f64), 24 | Symbol(LinkStr<'link>), 25 | String(LinkStr<'link>), 26 | 27 | /// A function expression with `length` elements. 28 | /// 29 | /// The next expression is the head of the function, followed by `length` number of 30 | /// expression elements. 31 | Function { 32 | length: usize, 33 | }, 34 | } 35 | 36 | /// The type of a token available to read from a [`Link`]. 37 | /// 38 | /// See also [`Token`]. 39 | /// 40 | /// See the [`WSGetType()`](https://reference.wolfram.com/language/ref/c/WSGetType.html) 41 | /// documentation for a listing of WSTP token types. 42 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] 43 | pub enum TokenType { 44 | /// [`WSTKINT`][sys::WSTKINT] 45 | Integer, 46 | /// [`WSTKREAL`][sys::WSTKREAL] 47 | Real, 48 | /// [`WSTKSYM`][sys::WSTKSYM] 49 | Symbol, 50 | /// [`WSTKSTR`][sys::WSTKSTR] 51 | String, 52 | /// [`WSTKFUNC`][sys::WSTKFUNC] 53 | Function, 54 | } 55 | 56 | /// String borrowed from a [`Link`]. 57 | /// 58 | /// `LinkStr` is returned from: 59 | /// 60 | /// * [`Link::get_string_ref()`] 61 | /// * [`Link::get_symbol_ref()`]. 62 | /// 63 | /// When `LinkStr` is dropped, the string is deallocated by the `Link`. 64 | /// 65 | /// # Example 66 | /// 67 | /// ``` 68 | /// use wstp::{Link, LinkStr}; 69 | /// 70 | /// let mut link = Link::new_loopback().unwrap(); 71 | /// 72 | /// link.put_str("hello world").unwrap(); 73 | /// 74 | /// // Read a string from the link 75 | /// let string: LinkStr = link.get_string_ref().unwrap(); 76 | /// 77 | /// // Get a `&str` from the `LinkStr` 78 | /// assert_eq!(string.as_str(), "hello world"); 79 | /// ``` 80 | pub struct LinkStr<'link, T: LinkStrType + ?Sized = str> { 81 | link: &'link Link, 82 | 83 | /// See [`LinkStr::get()`] for discussion of the safety reasons we *don't* store 84 | /// a `&[T::Element]` field. 85 | ptr: *const T::Element, 86 | length: usize, 87 | 88 | // Needed to control whether `WSReleaseString` or `WSReleaseSymbol` is called. 89 | is_symbol: bool, 90 | } 91 | 92 | pub unsafe trait LinkStrType: fmt::Debug { 93 | type Element; 94 | 95 | unsafe fn from_slice_unchecked<'s>(slice: &'s [Self::Element]) -> &'s Self; 96 | 97 | unsafe fn release( 98 | link: &Link, 99 | ptr: *const Self::Element, 100 | len: usize, 101 | is_symbol: bool, 102 | ); 103 | } 104 | 105 | //====================================== 106 | // Impls 107 | //====================================== 108 | 109 | impl Link { 110 | /// Get the type of the next token available to read on this link. 111 | /// 112 | /// See also [`Link::get_token()`]. 113 | pub fn get_type(&self) -> Result { 114 | use wstp_sys::{WSTKFUNC, WSTKINT, WSTKREAL, WSTKSTR, WSTKSYM}; 115 | 116 | let type_: i32 = self.get_raw_type()?; 117 | 118 | let token_type = match u8::try_from(type_).unwrap() { 119 | WSTKINT => TokenType::Integer, 120 | WSTKREAL => TokenType::Real, 121 | WSTKSTR => TokenType::String, 122 | WSTKSYM => TokenType::Symbol, 123 | WSTKFUNC => TokenType::Function, 124 | _ => return Err(Error::custom(format!("unknown WSLINK type: {}", type_))), 125 | }; 126 | 127 | Ok(token_type) 128 | } 129 | 130 | /// Read the next token from this link. 131 | /// 132 | /// See also [`Link::get_type()`]. 133 | /// 134 | /// # Example 135 | /// 136 | /// Read the expression `{5, "second", foo}` from a link one [`Token`] at a time: 137 | /// 138 | /// ``` 139 | /// use wstp::{Link, Token}; 140 | /// 141 | /// // Put {5, "second", foo} 142 | /// let mut link = Link::new_loopback().unwrap(); 143 | /// link.put_function("System`List", 3).unwrap(); 144 | /// link.put_i64(5).unwrap(); 145 | /// link.put_str("second").unwrap(); 146 | /// link.put_symbol("Global`foo").unwrap(); 147 | /// 148 | /// // Read it back 149 | /// assert!(matches!(link.get_token().unwrap(), Token::Function { length: 3 })); 150 | /// assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "System`List")); 151 | /// assert!(matches!(link.get_token().unwrap(), Token::Integer(5))); 152 | /// assert!(matches!(link.get_token().unwrap(), Token::String(s) if s.as_str() == "second")); 153 | /// assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "Global`foo")); 154 | /// ``` 155 | pub fn get_token(&mut self) -> Result { 156 | let token = match self.get_type()? { 157 | TokenType::Integer => Token::Integer(self.get_i64()?), 158 | TokenType::Real => Token::Real(self.get_f64()?), 159 | TokenType::String => Token::String(self.get_string_ref()?), 160 | TokenType::Symbol => Token::Symbol(self.get_symbol_ref()?), 161 | TokenType::Function => Token::Function { 162 | length: self.get_arg_count()?, 163 | }, 164 | }; 165 | 166 | Ok(token) 167 | } 168 | 169 | /// Get the raw type of the next token available to read on this link. 170 | /// 171 | /// If the returned type is [`WSTKERR`][sys::WSTKERR], an error is returned. 172 | /// 173 | /// See also [`Link::get_type()`]. 174 | /// 175 | /// *WSTP C API Documentation:* [`WSGetType()`](https://reference.wolfram.com/language/ref/c/WSGetType.html) 176 | pub fn get_raw_type(&self) -> Result { 177 | let type_ = unsafe { sys::WSGetType(self.raw_link) }; 178 | 179 | if type_ == sys::WSTKERR { 180 | return Err(self.error_or_unknown()); 181 | } 182 | 183 | Ok(type_) 184 | } 185 | 186 | //================================== 187 | // Atoms 188 | //================================== 189 | 190 | // TODO: 191 | // Reserving the name `get_str()` in case it's possible in the future to implement 192 | // implement a `Link::get_str() -> &str` method. It may be safe to do that if 193 | // we either: 194 | // 195 | // * Keep track of all the strings we need to call `WSReleaseString` on, and 196 | // then do so in `Link::drop()`. 197 | // * Verify that we don't need to explicitly deallocate the string data, because 198 | // they will be deallocated when the mempool is freed (presumably during 199 | // WSClose()?). 200 | 201 | /// *WSTP C API Documentation:* [`WSGetUTF8String()`](https://reference.wolfram.com/language/ref/c/WSGetUTF8String.html) 202 | pub fn get_string_ref<'link>(&'link mut self) -> Result, Error> { 203 | let mut c_string: *const u8 = std::ptr::null(); 204 | let mut num_bytes: i32 = 0; 205 | let mut num_chars = 0; 206 | 207 | if unsafe { 208 | WSGetUTF8String(self.raw_link, &mut c_string, &mut num_bytes, &mut num_chars) 209 | } == 0 210 | { 211 | // NOTE: According to the documentation, we do NOT have to release 212 | // `string` if the function returns an error. 213 | return Err(self.error_or_unknown()); 214 | } 215 | 216 | let num_bytes = usize::try_from(num_bytes).unwrap(); 217 | 218 | Ok(LinkStr { 219 | link: self, 220 | ptr: c_string, 221 | length: num_bytes, 222 | is_symbol: false, 223 | }) 224 | } 225 | 226 | /// Convenience wrapper around [`Link::get_string_ref()`]. 227 | pub fn get_string(&mut self) -> Result { 228 | Ok(self.get_string_ref()?.get().to_owned()) 229 | } 230 | 231 | /// *WSTP C API Documentation:* [`WSGetUTF8Symbol()`](https://reference.wolfram.com/language/ref/c/WSGetUTF8Symbol.html) 232 | pub fn get_symbol_ref<'link>(&'link mut self) -> Result, Error> { 233 | let mut c_string: *const u8 = std::ptr::null(); 234 | let mut num_bytes: i32 = 0; 235 | let mut num_chars = 0; 236 | 237 | if unsafe { 238 | sys::WSGetUTF8Symbol( 239 | self.raw_link, 240 | &mut c_string, 241 | &mut num_bytes, 242 | &mut num_chars, 243 | ) 244 | } == 0 245 | { 246 | // NOTE: According to the documentation, we do NOT have to release 247 | // `string` if the function returns an error. 248 | return Err(self.error_or_unknown()); 249 | } 250 | 251 | let num_bytes = usize::try_from(num_bytes).unwrap(); 252 | 253 | Ok(LinkStr { 254 | link: self, 255 | ptr: c_string, 256 | length: num_bytes, 257 | is_symbol: true, 258 | }) 259 | } 260 | 261 | //================================== 262 | // Strings 263 | //================================== 264 | 265 | /// *WSTP C API Documentation:* [`WSGetUTF8String()`](https://reference.wolfram.com/language/ref/c/WSGetUTF8String.html) 266 | pub fn get_utf8_str<'link>( 267 | &'link mut self, 268 | ) -> Result, Error> { 269 | let mut c_string: *const u8 = std::ptr::null(); 270 | let mut num_bytes: i32 = 0; 271 | let mut num_chars = 0; 272 | 273 | if unsafe { 274 | WSGetUTF8String(self.raw_link, &mut c_string, &mut num_bytes, &mut num_chars) 275 | } == 0 276 | { 277 | // NOTE: According to the documentation, we do NOT have to release 278 | // `string` if the function returns an error. 279 | return Err(self.error_or_unknown()); 280 | } 281 | 282 | let num_bytes = usize::try_from(num_bytes).unwrap(); 283 | 284 | Ok(LinkStr { 285 | link: self, 286 | 287 | ptr: c_string, 288 | length: num_bytes, 289 | 290 | is_symbol: false, 291 | }) 292 | } 293 | 294 | /// *WSTP C API Documentation:* [`WSGetUTF16String()`](https://reference.wolfram.com/language/ref/c/WSGetUTF16String.html) 295 | pub fn get_utf16_str<'link>( 296 | &'link mut self, 297 | ) -> Result, Error> { 298 | let mut c_string: *const u16 = std::ptr::null(); 299 | let mut num_elems: i32 = 0; 300 | let mut num_chars = 0; 301 | 302 | if unsafe { 303 | WSGetUTF16String(self.raw_link, &mut c_string, &mut num_elems, &mut num_chars) 304 | } == 0 305 | { 306 | // NOTE: According to the documentation, we do NOT have to release 307 | // `string` if the function returns an error. 308 | return Err(self.error_or_unknown()); 309 | } 310 | 311 | let num_elems = usize::try_from(num_elems).unwrap(); 312 | 313 | Ok(LinkStr { 314 | link: self, 315 | 316 | ptr: c_string, 317 | length: num_elems, 318 | 319 | is_symbol: false, 320 | }) 321 | } 322 | 323 | /// *WSTP C API Documentation:* [`WSGetUTF32String()`](https://reference.wolfram.com/language/ref/c/WSGetUTF32String.html) 324 | pub fn get_utf32_str<'link>( 325 | &'link mut self, 326 | ) -> Result, Error> { 327 | let mut c_string: *const u32 = std::ptr::null(); 328 | let mut num_elems: i32 = 0; 329 | 330 | if unsafe { WSGetUTF32String(self.raw_link, &mut c_string, &mut num_elems) } == 0 331 | { 332 | // NOTE: According to the documentation, we do NOT have to release 333 | // `string` if the function returns an error. 334 | return Err(self.error_or_unknown()); 335 | } 336 | 337 | let num_elems = usize::try_from(num_elems).unwrap(); 338 | 339 | Ok(LinkStr { 340 | link: self, 341 | 342 | ptr: c_string, 343 | length: num_elems, 344 | 345 | is_symbol: false, 346 | }) 347 | } 348 | 349 | //================================== 350 | // Functions 351 | //================================== 352 | 353 | /// Check that the incoming expression is a function with head `symbol`. 354 | /// 355 | /// If the check succeeds, the number of elements in the incoming expression is 356 | /// returned. Otherwise, an error is returned. 357 | /// 358 | /// # Example 359 | /// 360 | /// ``` 361 | /// use wstp::Link; 362 | /// 363 | /// #[derive(Debug, PartialEq)] 364 | /// struct Quantity { 365 | /// value: f64, 366 | /// unit: String, 367 | /// } 368 | /// 369 | /// fn get_quantity(link: &mut Link) -> Result { 370 | /// // Use test_head() to verify that the incoming expression has the expected 371 | /// // head. 372 | /// let argc = link.test_head("System`Quantity")?; 373 | /// 374 | /// assert!(argc == 2, "expected Quantity to have 2 arguments"); 375 | /// 376 | /// let value = link.get_f64()?; 377 | /// let unit = link.get_string()?; 378 | /// 379 | /// Ok(Quantity { value, unit }) 380 | /// } 381 | /// 382 | /// let mut link = Link::new_loopback().unwrap(); 383 | /// link.put_function("System`Quantity", 2).unwrap(); 384 | /// link.put_f64(5.0).unwrap(); 385 | /// link.put_str("Seconds").unwrap(); 386 | /// 387 | /// assert_eq!( 388 | /// get_quantity(&mut link), 389 | /// Ok(Quantity { value: 5.0, unit: "Seconds".into() }) 390 | /// ); 391 | /// ``` 392 | pub fn test_head(&mut self, symbol: &str) -> Result { 393 | let c_string = CString::new(symbol).unwrap(); 394 | 395 | self.test_head_cstr(c_string.as_c_str()) 396 | } 397 | 398 | /// Check that the incoming expression is a function with head `symbol`. 399 | /// 400 | /// This method is an optimized variant of [`Link::test_head()`]. 401 | pub fn test_head_cstr(&mut self, symbol: &CStr) -> Result { 402 | let mut len: std::os::raw::c_int = 0; 403 | 404 | if unsafe { sys::WSTestHead(self.raw_link, symbol.as_ptr(), &mut len) } == 0 { 405 | return Err(self.error_or_unknown()); 406 | } 407 | 408 | let len = usize::try_from(len).expect("c_int overflows usize"); 409 | 410 | Ok(len) 411 | } 412 | 413 | /// *WSTP C API Documentation:* [`WSGetArgCount()`](https://reference.wolfram.com/language/ref/c/WSGetArgCount.html) 414 | pub fn get_arg_count(&mut self) -> Result { 415 | let mut arg_count = 0; 416 | 417 | if unsafe { WSGetArgCount(self.raw_link, &mut arg_count) } == 0 { 418 | return Err(self.error_or_unknown()); 419 | } 420 | 421 | let arg_count = usize::try_from(arg_count) 422 | // This really shouldn't happen on any modern 32/64 bit OS. If this 423 | // condition *is* reached, it's more likely going to be do to an ABI or 424 | // numeric environment handling issue. 425 | .expect("WSTKFUNC argument count could not be converted to usize"); 426 | 427 | Ok(arg_count) 428 | } 429 | 430 | //================================== 431 | // Numerics 432 | //================================== 433 | 434 | /// *WSTP C API Documentation:* [`WSGetInteger64()`](https://reference.wolfram.com/language/ref/c/WSGetInteger64.html) 435 | pub fn get_i64(&mut self) -> Result { 436 | let mut int = 0; 437 | if unsafe { WSGetInteger64(self.raw_link, &mut int) } == 0 { 438 | return Err(self.error_or_unknown()); 439 | } 440 | Ok(int) 441 | } 442 | 443 | /// *WSTP C API Documentation:* [`WSGetInteger32()`](https://reference.wolfram.com/language/ref/c/WSGetInteger32.html) 444 | pub fn get_i32(&mut self) -> Result { 445 | let mut int = 0; 446 | if unsafe { WSGetInteger32(self.raw_link, &mut int) } == 0 { 447 | return Err(self.error_or_unknown()); 448 | } 449 | Ok(int) 450 | } 451 | 452 | /// *WSTP C API Documentation:* [`WSGetInteger16()`](https://reference.wolfram.com/language/ref/c/WSGetInteger16.html) 453 | pub fn get_i16(&mut self) -> Result { 454 | let mut int = 0; 455 | if unsafe { WSGetInteger16(self.raw_link, &mut int) } == 0 { 456 | return Err(self.error_or_unknown()); 457 | } 458 | Ok(int) 459 | } 460 | 461 | /// *WSTP C API Documentation:* [`WSGetInteger8()`](https://reference.wolfram.com/language/ref/c/WSGetInteger8.html) 462 | pub fn get_u8(&mut self) -> Result { 463 | let mut int = 0; 464 | if unsafe { WSGetInteger8(self.raw_link, &mut int) } == 0 { 465 | return Err(self.error_or_unknown()); 466 | } 467 | Ok(int) 468 | } 469 | 470 | /// *WSTP C API Documentation:* [`WSGetReal64()`](https://reference.wolfram.com/language/ref/c/WSGetReal64.html) 471 | pub fn get_f64(&mut self) -> Result { 472 | let mut real: f64 = 0.0; 473 | if unsafe { WSGetReal64(self.raw_link, &mut real) } == 0 { 474 | return Err(self.error_or_unknown()); 475 | } 476 | Ok(real) 477 | } 478 | 479 | /// *WSTP C API Documentation:* [`WSGetReal32()`](https://reference.wolfram.com/language/ref/c/WSGetReal32.html) 480 | pub fn get_f32(&mut self) -> Result { 481 | let mut real: f32 = 0.0; 482 | if unsafe { WSGetReal32(self.raw_link, &mut real) } == 0 { 483 | return Err(self.error_or_unknown()); 484 | } 485 | Ok(real) 486 | } 487 | 488 | //================================== 489 | // Integer numeric arrays 490 | //================================== 491 | 492 | /// Get a multidimensional array of [`i64`]. 493 | /// 494 | /// # Example 495 | /// 496 | /// ``` 497 | /// use wstp::Link; 498 | /// 499 | /// let mut link = Link::new_loopback().unwrap(); 500 | /// 501 | /// link.put_i64_array(&[1, 2, 3, 4], &[2, 2]).unwrap(); 502 | /// 503 | /// let out = link.get_i64_array().unwrap(); 504 | /// 505 | /// assert_eq!(out.data().len(), 4); 506 | /// assert_eq!(out.dimensions(), &[2, 2]); 507 | /// ``` 508 | /// 509 | /// *WSTP C API Documentation:* [`WSGetInteger64Array()`](https://reference.wolfram.com/language/ref/c/WSGetInteger64Array.html) 510 | pub fn get_i64_array(&mut self) -> Result, Error> { 511 | unsafe { self.get_array(sys::WSGetInteger64Array, sys::WSReleaseInteger64Array) } 512 | } 513 | 514 | /// *WSTP C API Documentation:* [`WSGetInteger32Array()`](https://reference.wolfram.com/language/ref/c/WSGetInteger32Array.html) 515 | pub fn get_i32_array(&mut self) -> Result, Error> { 516 | unsafe { self.get_array(sys::WSGetInteger32Array, sys::WSReleaseInteger32Array) } 517 | } 518 | 519 | /// *WSTP C API Documentation:* [`WSGetInteger16Array()`](https://reference.wolfram.com/language/ref/c/WSGetInteger16Array.html) 520 | pub fn get_i16_array(&mut self) -> Result, Error> { 521 | unsafe { self.get_array(sys::WSGetInteger16Array, sys::WSReleaseInteger16Array) } 522 | } 523 | 524 | /// *WSTP C API Documentation:* [`WSGetInteger8Array()`](https://reference.wolfram.com/language/ref/c/WSGetInteger8Array.html) 525 | pub fn get_u8_array(&mut self) -> Result, Error> { 526 | unsafe { self.get_array(sys::WSGetInteger8Array, sys::WSReleaseInteger8Array) } 527 | } 528 | 529 | //================================== 530 | // Floating-point numeric arrays 531 | //================================== 532 | 533 | /// Get a multidimensional array of [`f64`]. 534 | /// 535 | /// # Example 536 | /// 537 | /// ``` 538 | /// use wstp::Link; 539 | /// 540 | /// let mut link = Link::new_loopback().unwrap(); 541 | /// 542 | /// link.put_f64_array(&[3.141, 1.618, 2.718], &[3]).unwrap(); 543 | /// 544 | /// let out = link.get_f64_array().unwrap(); 545 | /// 546 | /// assert_eq!(out.data().len(), 3); 547 | /// assert_eq!(out.data(), &[3.141, 1.618, 2.718]); 548 | /// assert_eq!(out.dimensions(), &[3]); 549 | /// ``` 550 | /// 551 | /// *WSTP C API Documentation:* [`WSGetReal64Array()`](https://reference.wolfram.com/language/ref/c/WSGetReal64Array.html) 552 | pub fn get_f64_array(&mut self) -> Result, Error> { 553 | unsafe { self.get_array(sys::WSGetReal64Array, sys::WSReleaseReal64Array) } 554 | } 555 | 556 | /// *WSTP C API Documentation:* [`WSGetReal32Array()`](https://reference.wolfram.com/language/ref/c/WSGetReal32Array.html) 557 | pub fn get_f32_array(&mut self) -> Result, Error> { 558 | unsafe { self.get_array(sys::WSGetReal32Array, sys::WSReleaseReal32Array) } 559 | } 560 | 561 | #[allow(non_snake_case)] 562 | unsafe fn get_array( 563 | &mut self, 564 | WSGetTArray: unsafe extern "C" fn( 565 | sys::WSLINK, 566 | *mut *mut T, 567 | *mut *mut i32, 568 | *mut *mut *mut c_char, 569 | *mut i32, 570 | ) -> i32, 571 | WSReleaseTArray: unsafe extern "C" fn( 572 | sys::WSLINK, 573 | *mut T, 574 | *mut i32, 575 | *mut *mut c_char, 576 | i32, 577 | ), 578 | ) -> Result, Error> { 579 | let Link { raw_link } = *self; 580 | 581 | let mut data_ptr: *mut T = std::ptr::null_mut(); 582 | let mut dims_ptr: *mut i32 = std::ptr::null_mut(); 583 | let mut heads_ptr: *mut *mut c_char = std::ptr::null_mut(); 584 | let mut depth: i32 = 0; 585 | 586 | let result: i32 = { 587 | WSGetTArray( 588 | raw_link, 589 | &mut data_ptr, 590 | &mut dims_ptr, 591 | &mut heads_ptr, 592 | &mut depth, 593 | ) 594 | }; 595 | 596 | if result == 0 { 597 | return Err(self.error_or_unknown()); 598 | } 599 | 600 | let depth: usize = 601 | usize::try_from(depth).expect("WSGet*Array depth overflows usize"); 602 | 603 | let dims: &[i32] = { std::slice::from_raw_parts(dims_ptr, depth) }; 604 | let dims: Vec = Vec::from_iter(dims.iter().map(|&val| { 605 | usize::try_from(val) 606 | .expect("WSGetInteger64Array dimension size overflows usize") 607 | })); 608 | 609 | Ok(Array { 610 | link: self, 611 | data_ptr, 612 | release_callback: Box::new(move |link: &Link| { 613 | WSReleaseTArray( 614 | link.raw_link, 615 | data_ptr, 616 | dims_ptr, 617 | heads_ptr, 618 | depth as i32, 619 | ); 620 | }), 621 | dimensions: dims, 622 | }) 623 | } 624 | } 625 | 626 | impl<'link, T: LinkStrType + ?Sized> LinkStr<'link, T> { 627 | /// Get the string contained by this `LinkStr`. 628 | pub fn get<'this>(&'this self) -> &'this T { 629 | let LinkStr { 630 | link: _, 631 | ptr, 632 | length, 633 | is_symbol: _, 634 | } = *self; 635 | 636 | unsafe { 637 | // SAFETY: 638 | // It is important that the lifetime of `slice` is tied to `self` and NOT 639 | // to 'link. A `&'link str` could outlive the `LinkStr` object, which 640 | // would lead to a a use-after-free bug because the string data is 641 | // deallocated when `LinkStr` is dropped. 642 | let slice: &'this [T::Element] = std::slice::from_raw_parts(ptr, length); 643 | 644 | // SAFETY: 645 | // This depends on the assumption that WSTP always returns correctly 646 | // encoded UTF-8/UTF-16/UTF-32/UCS-2. We do not do any validation of 647 | // the encoding here. 648 | // 649 | // TODO: Do we trust WSTP enough to always produce valid UTF-8 to 650 | // use `str::from_utf8_unchecked()` here? If a client writes malformed 651 | // data with WSPutUTF8String, does WSTP validate it and return an error, 652 | // or would it be passed through to unsuspecting us? 653 | T::from_slice_unchecked(slice) 654 | } 655 | } 656 | } 657 | 658 | impl<'link> LinkStr<'link, str> { 659 | /// Get the UTF-8 string data. 660 | pub fn as_str<'s>(&'s self) -> &'s str { 661 | self.get() 662 | } 663 | 664 | /// Get the UTF-8 string data. 665 | #[deprecated(note = "Use LinkStr::as_str() instead")] 666 | pub fn to_str<'s>(&'s self) -> &'s str { 667 | self.get() 668 | } 669 | } 670 | 671 | impl<'link, T: ?Sized + LinkStrType> Drop for LinkStr<'link, T> { 672 | fn drop(&mut self) { 673 | let LinkStr { 674 | link, 675 | ptr, 676 | length, 677 | is_symbol, 678 | } = *self; 679 | 680 | let () = unsafe { T::release(link, ptr, length, is_symbol) }; 681 | } 682 | } 683 | 684 | //====================================== 685 | // LinkStrType impls 686 | //====================================== 687 | 688 | unsafe impl LinkStrType for str { 689 | type Element = u8; 690 | 691 | unsafe fn from_slice_unchecked<'s>(slice: &'s [Self::Element]) -> &'s Self { 692 | let str: &'s str = std::str::from_utf8_unchecked(slice); 693 | str 694 | } 695 | 696 | unsafe fn release( 697 | link: &Link, 698 | ptr: *const Self::Element, 699 | len: usize, 700 | is_symbol: bool, 701 | ) { 702 | let len = i32::try_from(len).expect("LinkStr usize length overflows i32"); 703 | 704 | // Deallocate the string data. 705 | match is_symbol { 706 | true => WSReleaseUTF8Symbol(link.raw_link, ptr, len), 707 | false => WSReleaseUTF8String(link.raw_link, ptr, len), 708 | } 709 | } 710 | } 711 | 712 | unsafe impl LinkStrType for Utf8Str { 713 | type Element = u8; 714 | 715 | // unsafe fn from_raw_parts_unchecked<'s>(ptr: *const u8, len: usize) -> &'s Self { 716 | unsafe fn from_slice_unchecked<'s>(slice: &'s [Self::Element]) -> &'s Self { 717 | let str: &'s Utf8Str = Utf8Str::from_utf8_unchecked(slice); 718 | str 719 | } 720 | 721 | unsafe fn release( 722 | link: &Link, 723 | ptr: *const Self::Element, 724 | len: usize, 725 | is_symbol: bool, 726 | ) { 727 | let len = i32::try_from(len).expect("LinkStr usize length overflows i32"); 728 | 729 | // Deallocate the string data. 730 | match is_symbol { 731 | true => WSReleaseUTF8Symbol(link.raw_link, ptr, len), 732 | false => WSReleaseUTF8String(link.raw_link, ptr, len), 733 | } 734 | } 735 | } 736 | 737 | unsafe impl LinkStrType for Utf16Str { 738 | type Element = u16; 739 | 740 | // unsafe fn from_raw_parts_unchecked<'s>(ptr: *const u8, len: usize) -> &'s Self { 741 | unsafe fn from_slice_unchecked<'s>(slice: &'s [Self::Element]) -> &'s Self { 742 | let str: &'s Utf16Str = Utf16Str::from_utf16_unchecked(slice); 743 | str 744 | } 745 | 746 | unsafe fn release( 747 | link: &Link, 748 | ptr: *const Self::Element, 749 | len: usize, 750 | is_symbol: bool, 751 | ) { 752 | let len = i32::try_from(len).expect("LinkStr usize length overflows i32"); 753 | 754 | // Deallocate the string data. 755 | match is_symbol { 756 | true => WSReleaseUTF16Symbol(link.raw_link, ptr, len), 757 | false => WSReleaseUTF16String(link.raw_link, ptr, len), 758 | } 759 | } 760 | } 761 | 762 | unsafe impl LinkStrType for Utf32Str { 763 | type Element = u32; 764 | 765 | // unsafe fn from_raw_parts_unchecked<'s>(ptr: *const u8, len: usize) -> &'s Self { 766 | unsafe fn from_slice_unchecked<'s>(slice: &'s [Self::Element]) -> &'s Self { 767 | let str: &'s Utf32Str = Utf32Str::from_utf32_unchecked(slice); 768 | str 769 | } 770 | 771 | unsafe fn release( 772 | link: &Link, 773 | ptr: *const Self::Element, 774 | len: usize, 775 | is_symbol: bool, 776 | ) { 777 | let len = i32::try_from(len).expect("LinkStr usize length overflows i32"); 778 | 779 | // Deallocate the string data. 780 | match is_symbol { 781 | true => WSReleaseUTF32Symbol(link.raw_link, ptr, len), 782 | false => WSReleaseUTF32String(link.raw_link, ptr, len), 783 | } 784 | } 785 | } 786 | 787 | 788 | /// Reference to a multidimensional rectangular array borrowed from a [`Link`]. 789 | /// 790 | /// [`Array`] is returned from: 791 | /// 792 | /// * [`Link::get_i64_array()`] 793 | /// * [`Link::get_i32_array()`] 794 | /// * [`Link::get_i16_array()`] 795 | /// * [`Link::get_u8_array()`] 796 | /// * [`Link::get_f64_array()`] 797 | /// * [`Link::get_f32_array()`] 798 | pub struct Array<'link, T> { 799 | link: &'link Link, 800 | 801 | data_ptr: *mut T, 802 | release_callback: Box, 803 | 804 | dimensions: Vec, 805 | } 806 | 807 | impl<'link, T> Array<'link, T> { 808 | /// Access the elements stored in this [`Array`] as a flat buffer. 809 | pub fn data<'s>(&'s self) -> &'s [T] { 810 | let data_len: usize = self.dimensions.iter().product(); 811 | 812 | // SAFETY: 813 | // It is important that the lifetime of `data` is tied to `self` and NOT to 814 | // 'link. A `&'link Array` could outlive the `Array` object, which would lead 815 | // to a a use-after-free bug because the string data is deallocated when 816 | // `Array` is dropped. 817 | let data: &'s [T] = 818 | unsafe { std::slice::from_raw_parts(self.data_ptr, data_len) }; 819 | 820 | data 821 | } 822 | 823 | /// Get the number of dimensions in this array. 824 | pub fn rank(&self) -> usize { 825 | self.dimensions.len() 826 | } 827 | 828 | /// Get the dimensions of this array. 829 | pub fn dimensions(&self) -> &[usize] { 830 | self.dimensions.as_slice() 831 | } 832 | 833 | /// Length of the first dimension of this array. 834 | pub fn length(&self) -> usize { 835 | self.dimensions[0] 836 | } 837 | } 838 | 839 | impl<'link, T> Drop for Array<'link, T> { 840 | fn drop(&mut self) { 841 | let Array { 842 | link, 843 | ref mut release_callback, 844 | data_ptr: _, 845 | dimensions: _, 846 | } = *self; 847 | 848 | release_callback(link) 849 | } 850 | } 851 | 852 | //====================================== 853 | // Formatting impls 854 | //====================================== 855 | 856 | impl<'link, T: LinkStrType + fmt::Debug + ?Sized> fmt::Debug for LinkStr<'link, T> { 857 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 858 | let LinkStr { 859 | link, 860 | ptr, 861 | length, 862 | is_symbol, 863 | } = self; 864 | 865 | let value = format!("{:?}", self.get()); 866 | 867 | f.debug_struct("LinkStr") 868 | .field("", &value) 869 | .field("link", link) 870 | .field("ptr", ptr) 871 | .field("length", length) 872 | .field("is_symbol", is_symbol) 873 | .finish() 874 | } 875 | } 876 | 877 | impl<'link, T> fmt::Debug for Array<'link, T> { 878 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 879 | let Array { 880 | link, 881 | data_ptr, 882 | release_callback: _, 883 | dimensions, 884 | } = self; 885 | 886 | f.debug_struct("Array") 887 | .field("link", link) 888 | .field("dimensions", dimensions) 889 | .field("data_ptr", data_ptr) 890 | .finish() 891 | } 892 | } 893 | -------------------------------------------------------------------------------- /wstp/src/kernel/mod.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for interacting with a Wolfram Kernel process via WSTP. 2 | //! 3 | //! # Example 4 | //! 5 | //! Launch a new Wolfram Kernel process from the file path to a 6 | //! [`WolframKernel`][WolframKernel] executable: 7 | //! 8 | //! ```no_run 9 | //! use std::path::PathBuf; 10 | //! use wstp::kernel::WolframKernelProcess; 11 | //! 12 | //! let exe = PathBuf::from( 13 | //! "/Applications/Mathematica.app/Contents/MacOS/WolframKernel" 14 | //! ); 15 | //! 16 | //! let kernel = WolframKernelProcess::launch(&exe).unwrap(); 17 | //! ``` 18 | //! 19 | //! ### Automatic Wolfram Kernel discovery 20 | //! 21 | //! Use the [wolfram-app-discovery] crate to automatically discover a suitable 22 | //! `WolframKernel`: 23 | //! 24 | //! ```no_run 25 | //! use std::path::PathBuf; 26 | //! use wolfram_app_discovery::WolframApp; 27 | //! use wstp::kernel::WolframKernelProcess; 28 | //! 29 | //! let app = WolframApp::try_default() 30 | //! .expect("unable to find any Wolfram Language installations"); 31 | //! 32 | //! let exe: PathBuf = app.kernel_executable_path().unwrap(); 33 | //! 34 | //! let kernel = WolframKernelProcess::launch(&exe).unwrap(); 35 | //! ``` 36 | //! 37 | //! Using automatic discovery makes it easy to write programs that are portable to 38 | //! different computers, without relying on end-user configuration to specify the location 39 | //! of the local Wolfram Language installation. 40 | //! 41 | //! 42 | //! [WolframKernel]: https://reference.wolfram.com/language/ref/program/WolframKernel.html 43 | //! [wolfram-app-discovery]: https://crates.io/crates/wolfram-app-discovery 44 | //! 45 | //! 46 | //! # Related Links 47 | //! 48 | //! #### Wolfram Language documentation 49 | //! 50 | //! These resources describe the packet expression interface used by the Wolfram Kernel. 51 | //! 52 | //! * [WSTP Packets](https://reference.wolfram.com/language/guide/WSTPPackets.html) 53 | //! * [Running the Wolfram System from within an External Program](https://reference.wolfram.com/language/tutorial/RunningTheWolframSystemFromWithinAnExternalProgram.html) 54 | //! 55 | //! #### Link packet methods 56 | //! 57 | //! * [`Link::put_eval_packet()`] 58 | 59 | use std::{path::PathBuf, process}; 60 | 61 | use wolfram_expr::Expr; 62 | 63 | use crate::{Error as WstpError, Link, Protocol}; 64 | 65 | /// Handle to a Wolfram Kernel process connected via WSTP. 66 | /// 67 | /// Use [`WolframKernelProcess::launch()`] to launch a new Wolfram Kernel process. 68 | /// 69 | /// Use [`WolframKernelProcess::link()`] to access the WSTP [`Link`] used to communicate with 70 | /// this kernel. 71 | #[derive(Debug)] 72 | pub struct WolframKernelProcess { 73 | #[allow(dead_code)] 74 | process: process::Child, 75 | link: Link, 76 | } 77 | 78 | /// Wolfram Kernel process error. 79 | #[derive(Debug)] 80 | pub struct Error(String); 81 | 82 | impl From for Error { 83 | fn from(err: WstpError) -> Error { 84 | Error(format!("WSTP error: {err}")) 85 | } 86 | } 87 | 88 | impl From for Error { 89 | fn from(err: std::io::Error) -> Error { 90 | Error(format!("IO error: {err}")) 91 | } 92 | } 93 | 94 | impl WolframKernelProcess { 95 | /// Launch a new Wolfram Kernel child process and establish a WSTP connection with it. 96 | /// 97 | /// See also the [wolfram-app-discovery](https://crates.io/crates/wolfram-app-discovery) 98 | /// crate, whose 99 | /// [`WolframApp::kernel_executable_path()`](https://docs.rs/wolfram-app-discovery/0.2.0/wolfram_app_discovery/struct.WolframApp.html#method.kernel_executable_path) 100 | /// method can be used to get the location of a [`WolframKernel`][WolframKernel] 101 | /// executable suitable for use with this function. 102 | /// 103 | /// [WolframKernel]: https://reference.wolfram.com/language/ref/program/WolframKernel.html 104 | // 105 | // TODO: Would it be correct to describe this as essentially `LinkLaunch`? Also note 106 | // that this doesn't actually use `-linkmode launch`. 107 | pub fn launch(path: &PathBuf) -> Result { 108 | let mut link = Link::listen(Protocol::SharedMemory, "")?; 109 | 110 | let name = link.link_name(); 111 | assert!(!name.is_empty()); 112 | 113 | let kernel_process = process::Command::new(path) 114 | .arg("-wstp") 115 | .arg("-linkprotocol") 116 | .arg("SharedMemory") 117 | .arg("-linkconnect") 118 | .arg("-linkname") 119 | .arg(&name) 120 | .spawn()?; 121 | 122 | // Wait for an incoming connection to be made to the listening link. 123 | // This will block until a connection is made. 124 | // 125 | // FIXME: This currently has an infinite timeout. If the spawned 126 | // process fails to connect for some reason (e.g. a launched 127 | // Kernel doesn't start due to a licensing error), this will 128 | // just wait forever, hanging the current program. 129 | // 130 | // TODO: Set a yield function that will abort if a timeout 131 | // duration is reached. 132 | let () = link.activate()?; 133 | 134 | Ok(WolframKernelProcess { 135 | process: kernel_process, 136 | link, 137 | }) 138 | } 139 | 140 | /// Get the WSTP [`Link`] connection used to communicate with this Wolfram Kernel 141 | /// process. 142 | pub fn link(&mut self) -> &mut Link { 143 | let WolframKernelProcess { process: _, link } = self; 144 | link 145 | } 146 | } 147 | 148 | impl Link { 149 | /// Put an [`EvaluatePacket[expr]`][EvaluatePacket] onto the link. 150 | /// 151 | /// [EvaluatePacket]: https://reference.wolfram.com/language/ref/EvaluatePacket.html 152 | pub fn put_eval_packet(&mut self, expr: &Expr) -> Result<(), Error> { 153 | self.put_function("System`EvaluatePacket", 1)?; 154 | self.put_expr(expr)?; 155 | self.end_packet()?; 156 | 157 | Ok(()) 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /wstp/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Bindings to the [Wolfram Symbolic Transfer Protocol (WSTP)](https://www.wolfram.com/wstp/). 2 | //! 3 | //! This crate provides a set of safe and ergonomic bindings to the WSTP library, used to 4 | //! transfer Wolfram Language expressions between programs. 5 | //! 6 | //! # Quick Examples 7 | //! 8 | //! ### Loopback links 9 | //! 10 | //! Write an expression to a loopback [`Link`], and then read it back from the same link 11 | //! object: 12 | //! 13 | //! ``` 14 | //! use wstp::Link; 15 | //! 16 | //! # fn example() -> Result<(), wstp::Error> { 17 | //! let mut link = Link::new_loopback()?; 18 | //! 19 | //! // Write the expression {"a", "b", "c"} 20 | //! link.put_function("System`List", 3)?; 21 | //! link.put_str("a")?; 22 | //! link.put_str("b")?; 23 | //! link.put_str("c")?; 24 | //! 25 | //! // Read back the expression, concatenating the elements as we go: 26 | //! let mut buffer = String::new(); 27 | //! 28 | //! for _ in 0 .. link.test_head("System`List")? { 29 | //! buffer.push_str(link.get_string_ref()?.as_str()) 30 | //! } 31 | //! 32 | //! assert_eq!(buffer, "abc"); 33 | //! # Ok(()) 34 | //! # } 35 | //! # 36 | //! # example(); 37 | //! ``` 38 | //! 39 | //! ### Full-duplex links 40 | //! 41 | //! Transfer the expression `"hello!"` from one [`Link`] endpoint to another: 42 | //! 43 | //! ``` 44 | //! use std::thread; 45 | //! use wstp::{Link, Protocol}; 46 | //! 47 | //! let mut link_a = Link::listen(Protocol::SharedMemory, "").unwrap(); 48 | //! let name = link_a.link_name(); 49 | //! 50 | //! // Start a background thread with the listen()'ing link. 51 | //! let listening_thread = thread::spawn(move || { 52 | //! // This will block until connect() is called. 53 | //! link_a.activate().unwrap(); 54 | //! 55 | //! link_a.put_str("hello!").unwrap(); 56 | //! }); 57 | //! 58 | //! // Connect to the listening link and read data from it. 59 | //! let mut link_b = Link::connect(Protocol::SharedMemory, &name).unwrap(); 60 | //! assert_eq!(link_b.get_string().unwrap(), "hello!"); 61 | //! ``` 62 | //! 63 | //! See also: [`channel()`] 64 | //! 65 | //! # What is WSTP? 66 | //! 67 | //! The name Wolfram Symbolic Transfer Protocol (WSTP) refers to two interrelated things: 68 | //! 69 | //! * The WSTP *protocol* 70 | //! * The WSTP *library*, which provides the canonical implementation of the protocol via 71 | //! a C API. 72 | //TODO: * The WSTP *command-line parameters* convention. 73 | //! 74 | //! ### The protocol 75 | //! 76 | //! At a high level, the WSTP defines a full-duplex communication channel optimized for 77 | //! the transfer of Wolfram Language expressions between two endpoints. A WSTP 78 | //! connection typically has exactly two [`Link`] endpoints 79 | //! ([loopback links][Link::new_loopback] are the only exception). A connection between two 80 | //! endpoints is established when one endpoint is created using [`Link::listen()`], and 81 | //! another endpoint is created using [`Link::connect()`]. 82 | //! 83 | //! At a lower level, WSTP is actually three protocols: 84 | //! 85 | //! * [`IntraProcess`][Protocol::IntraProcess] 86 | //! * [`SharedMemory`][Protocol::SharedMemory] 87 | //! * [`TCPIP`][Protocol::TCPIP] 88 | //! 89 | //! which are represented by the [`Protocol`] enum. Each lower-level protocol is optimized 90 | //! for usage within a particular domain. For example, `IntraProcess` is the best link 91 | //! type to use when both [`Link`] endpoints reside within the same OS process, and 92 | //! `TCPIP` links can be used when the [`Link`] endpoints reside on different 93 | //! computers that are reachable across the network. 94 | //! 95 | //! Given that the different [`Protocol`] types use different mechanisms to transfer data, 96 | //! it is not possible to create a connection between links of different types. E.g. a 97 | //! `TCPIP` type link cannot connect to a `SharedMemory` link, even if both endpoints were 98 | //! created on the same computer and in the same process. 99 | //! 100 | // TODO: The packet protocol. 101 | //! 102 | //! ### The library 103 | //! 104 | //! The WSTP library is distributed as part the Wolfram Language as both a static and 105 | //! dynamic library. The WSTP SDK is present in the file system layout of the Mathematica, 106 | //! Wolfram Desktop, and [Wolfram Engine][WolframEngine] applications. The `wstp` crate 107 | //! is built on top of the [WSTP C API][CFunctions]. 108 | //! 109 | //! When using the `wstp` crate as a dependency, the `wstp` crate's cargo build script 110 | //! will use [`wolfram-app-discovery`][wolfram-app-discovery] to automatically find any 111 | //! local installations of the Wolfram Language, and will link against the WSTP static 112 | //! library located within. 113 | //! 114 | //! The [Wolfram Engine][WolframEngine] can be downloaded and used for free for 115 | //! non-commercial or pre-production uses. A license must be purchased when used as part 116 | //! of a commercial or production-level product. See the *Licensing and Terms of 117 | //! Use* section in the [Wolfram Engine FAQ][WE-FAQ] for details. 118 | //! 119 | // TODO: Mention package manager downloads of WolframEngine. 120 | //! 121 | //! 122 | //! # Related Links 123 | //! 124 | //! * [WSTP and External Program Communication](https://reference.wolfram.com/language/tutorial/WSTPAndExternalProgramCommunicationOverview.html) 125 | //! * [How WSTP Is Used](https://reference.wolfram.com/language/tutorial/HowWSTPIsUsed.html) 126 | //! * [Alphabetical Listing of WSTP C Functions][CFunctions] 127 | //! 128 | //! ### Licensing 129 | //! 130 | //! Usage of the WSTP library is subject to the terms of the 131 | //! [MathLink License Agreement](https://www.wolfram.com/legal/agreements/mathlink.html). 132 | //! 133 | //! 134 | //! [WolframEngine]: https://www.wolfram.com/engine/ 135 | //! [WE-FAQ]: https://www.wolfram.com/engine/faq/ 136 | //! [CFunctions]: https://reference.wolfram.com/language/guide/AlphabeticalListingOfWSTPCFunctions.html 137 | //! 138 | //! [wolfram-app-discovery]: https://crates.io/crates/wolfram-app-discovery 139 | 140 | #![warn(missing_docs)] 141 | 142 | 143 | mod env; 144 | mod error; 145 | mod link_server; 146 | mod wait; 147 | 148 | mod get; 149 | mod put; 150 | 151 | mod strx; 152 | 153 | pub mod kernel; 154 | 155 | /// Ensure that doc tests in the README.md file get run. 156 | #[cfg(doctest)] 157 | #[doc(hidden)] 158 | mod test_readme { 159 | #![doc = include_str!("../../README.md")] 160 | } 161 | 162 | 163 | use std::convert::TryFrom; 164 | use std::ffi::{c_char, CStr, CString}; 165 | use std::fmt::{self, Display}; 166 | use std::net; 167 | 168 | use wolfram_expr::{Expr, ExprKind, Number, Symbol}; 169 | use wstp_sys::{WSErrorMessage, WSReady, WSReleaseErrorMessage, WSLINK}; 170 | 171 | //----------------------------------- 172 | // Public re-exports and type aliases 173 | //----------------------------------- 174 | 175 | /// Raw bindings to the [WSTP C API][CFunctions]. 176 | /// 177 | /// [CFunctions]: https://reference.wolfram.com/language/guide/AlphabeticalListingOfWSTPCFunctions.html 178 | #[doc(inline)] 179 | pub use wstp_sys as sys; 180 | 181 | pub use crate::{ 182 | env::shutdown, 183 | error::Error, 184 | get::{Array, LinkStr, Token, TokenType}, 185 | link_server::LinkServer, 186 | strx::{Ucs2Str, Utf16Str, Utf32Str, Utf8Str}, 187 | }; 188 | 189 | // TODO: Make this function public from `wstp`? 190 | pub(crate) use env::with_raw_stdenv; 191 | 192 | 193 | //====================================== 194 | // Source 195 | //====================================== 196 | 197 | /// WSTP link endpoint. 198 | /// 199 | /// [`WSClose()`][sys::WSClose] is called on the underlying [`WSLINK`] when 200 | /// [`Drop::drop()`][Link::drop] is called for a value of this type. 201 | /// 202 | /// *WSTP C API Documentation:* [`WSLINK`](https://reference.wolfram.com/language/ref/c/WSLINK.html) 203 | /// 204 | /// *Wolfram Language Documentation:* [`LinkObject`](https://reference.wolfram.com/language/ref/LinkObject.html) 205 | #[derive(Debug)] 206 | #[derive(ref_cast::RefCastCustom)] 207 | #[repr(transparent)] 208 | pub struct Link { 209 | raw_link: WSLINK, 210 | } 211 | 212 | impl Link { 213 | /// Transmute a `&mut WSLINK` into a `&mut Link`. 214 | /// 215 | /// This operation enables usage of the safe [`Link`] wrapper type without assuming 216 | /// ownership over the underying raw `WSLINK`. 217 | /// 218 | /// Use this function to construct a [`Link`] from a borrowed 219 | /// [`WSLINK`][crate::sys::WSLINK]. This function should be used in LibraryLink 220 | /// functions loaded via [`LibraryFunctionLoad`][LibraryFunctionLoad] instead of 221 | /// [`Link::unchecked_new()`]. 222 | /// 223 | /// [LibraryFunctionLoad]: https://reference.wolfram.com/language/ref/LibraryFunctionLoad.html 224 | /// 225 | /// # Safety 226 | /// 227 | /// For this operation to be safe, the caller must ensure: 228 | /// 229 | /// * the `WSLINK` is validly initialized. 230 | /// * they have unique ownership of the `WSLINK` value; no aliasing is possible. 231 | /// 232 | /// and the maintainer of this functionality must ensure: 233 | /// 234 | /// * The [`Link`] type is a `#[repr(transparent)]` wrapper around around a 235 | /// single field of type [`WSLINK`][crate::sys::WSLINK]. 236 | #[ref_cast::ref_cast_custom] 237 | pub unsafe fn unchecked_ref_cast_mut(from: &mut WSLINK) -> &mut Self; 238 | } 239 | 240 | /// # Safety 241 | /// 242 | /// [`Link`]s can be sent between threads, but they cannot be used from multiple 243 | /// threads at once (unless `WSEnableLinkLock()` has been called on the link). So [`Link`] 244 | /// satisfies [`Send`] but not [`Sync`]. 245 | /// 246 | /// **TODO:** 247 | /// Add a wrapper type for [`Link`] which enforces that `WSEnableLinkLock()` 248 | /// has been called, and implements [`Sync`]. 249 | unsafe impl Send for Link {} 250 | 251 | /// Transport protocol used to communicate between two [`Link`] end points. 252 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 253 | pub enum Protocol { 254 | /// Protocol type optimized for communication between two [`Link`] end points 255 | /// from within the same OS process. 256 | IntraProcess, 257 | /// Protocol type optimized for communication between two [`Link`] end points 258 | /// from the same machine — but not necessarily in the same OS process — using [shared 259 | /// memory](https://en.wikipedia.org/wiki/Shared_memory). 260 | SharedMemory, 261 | /// Protocol type for communication between two [`Link`] end points reachable 262 | /// across a network connection. 263 | TCPIP, 264 | } 265 | 266 | //====================================== 267 | // Urgent message types 268 | //====================================== 269 | 270 | /// A WSTP out-of-band urgent message. 271 | /// 272 | /// See also: 273 | /// 274 | /// * [`Link::is_message_ready()`] 275 | /// * [`Link::put_message()`] 276 | /// * [`Link::get_message()`] 277 | #[derive(Debug, Clone, PartialEq)] 278 | pub struct UrgentMessage { 279 | /// The urgent message code. 280 | pub code: u32, 281 | 282 | /// The urgent message parameter value. 283 | /// 284 | /// This defaults to 0 if no other value was specified by the message sender. 285 | pub param: u32, 286 | } 287 | 288 | /// A reserved WSTP urgent message code value. 289 | /// 290 | /// See the details section of 291 | /// [`WSGetMessage()`](https://reference.wolfram.com/language/ref/c/WSGetMessage) 292 | /// for more information on WSTP urgent message types. 293 | #[derive(Debug, Clone, PartialEq)] 294 | #[non_exhaustive] 295 | pub enum UrgentMessageKind { 296 | /// [`sys::WSTerminateMessage`] 297 | Terminate, 298 | /// [`sys::WSInterruptMessage`] 299 | Interrupt, 300 | /// [`sys::WSAbortMessage`] 301 | Abort, 302 | } 303 | 304 | impl UrgentMessage { 305 | /// [`sys::WSTerminateMessage`] 306 | pub const TERMINATE: UrgentMessage = UrgentMessage { 307 | code: sys::WSTerminateMessage as u32, 308 | param: 0, 309 | }; 310 | 311 | /// [`sys::WSInterruptMessage`] 312 | pub const INTERRUPT: UrgentMessage = UrgentMessage { 313 | code: sys::WSInterruptMessage as u32, 314 | param: 0, 315 | }; 316 | 317 | /// [`sys::WSAbortMessage`] 318 | pub const ABORT: UrgentMessage = UrgentMessage { 319 | code: sys::WSAbortMessage as u32, 320 | param: 0, 321 | }; 322 | 323 | /// Construct a new `UrgentMessage` with the specified code. 324 | /// 325 | /// The default `param` value is 0. 326 | pub fn new(code: u32) -> Self { 327 | UrgentMessage { code, param: 0 } 328 | } 329 | 330 | /// Construct a new `UrgentMessage` with the specified code and paramater 331 | /// value. 332 | pub fn new_with_param(code: u32, param: u32) -> Self { 333 | UrgentMessage { code, param } 334 | } 335 | 336 | /// Check if this urgent message is one of the reserved message codes. 337 | /// 338 | /// If this message code is one of the known reserved WSTP message codes, 339 | /// `Ok(UrgentMessageKind)` will be returned. Otherwise `Err(code)` will 340 | /// be returned. 341 | pub fn kind(&self) -> Result { 342 | let UrgentMessage { code, param: _ } = *self; 343 | 344 | let kind = if code == sys::WSTerminateMessage as u32 { 345 | UrgentMessageKind::Terminate 346 | } else if code == sys::WSInterruptMessage as u32 { 347 | UrgentMessageKind::Interrupt 348 | } else if code == sys::WSAbortMessage as u32 { 349 | UrgentMessageKind::Abort 350 | } else { 351 | return Err(code as u32); 352 | }; 353 | 354 | Ok(kind) 355 | } 356 | } 357 | 358 | impl UrgentMessageKind { 359 | /// Returns the raw message code of this message kind. 360 | pub fn code(&self) -> u32 { 361 | match self { 362 | UrgentMessageKind::Terminate => sys::WSTerminateMessage as u32, 363 | UrgentMessageKind::Interrupt => sys::WSInterruptMessage as u32, 364 | UrgentMessageKind::Abort => sys::WSAbortMessage as u32, 365 | } 366 | } 367 | } 368 | 369 | //====================================== 370 | // Impls 371 | //====================================== 372 | 373 | /// # Creating WSTP link objects 374 | impl Link { 375 | /// Create a new Loopback type link. 376 | /// 377 | /// *WSTP C API Documentation:* [`WSLoopbackOpen()`](https://reference.wolfram.com/language/ref/c/WSLoopbackOpen.html) 378 | pub fn new_loopback() -> Result { 379 | unsafe { 380 | let mut err: std::os::raw::c_int = sys::MLEOK; 381 | let raw_link = 382 | with_raw_stdenv(|raw_stdenv| sys::WSLoopbackOpen(raw_stdenv, &mut err))?; 383 | 384 | if raw_link.is_null() || err != sys::MLEOK { 385 | return Err(Error::from_code(err)); 386 | } 387 | 388 | Ok(Link::unchecked_new(raw_link)) 389 | } 390 | } 391 | 392 | /// Create a new named WSTP link using `protocol`. 393 | pub fn listen(protocol: Protocol, name: &str) -> Result { 394 | let protocol_string = protocol.to_string(); 395 | 396 | let strings: &[&str] = &[ 397 | "-wstp", 398 | "-linkmode", 399 | "listen", 400 | "-linkprotocol", 401 | protocol_string.as_str(), 402 | "-linkname", 403 | name, 404 | // Prevent "Link created on: .." message from being printed. 405 | "-linkoptions", 406 | "MLDontInteract", 407 | ]; 408 | 409 | Link::open_with_args(strings) 410 | } 411 | 412 | /// Connect to an existing named WSTP link. 413 | pub fn connect(protocol: Protocol, name: &str) -> Result { 414 | Link::connect_with_options(protocol, name, &[]) 415 | } 416 | 417 | /// Create a new WSTP [`TCPIP`][Protocol::TCPIP] link bound to `addr`. 418 | /// 419 | /// If `addr` yields multiple addresses, listening will be attempted with each of the 420 | /// addresses until one succeeds and returns the listener. If none of the addresses 421 | /// succeed in creating a listener, the error returned from the last attempt 422 | /// (the last address) is returned. 423 | pub fn tcpip_listen(addr: A) -> Result { 424 | let addrs = addr.to_socket_addrs().map_err(|err| { 425 | Error::custom(format!("error connecting to TCPIP Link address: {}", err)) 426 | })?; 427 | 428 | // Try each address, returning the first one which binds for listening successfully. 429 | for_each_addr(addrs.collect(), |addr| { 430 | Link::listen(Protocol::TCPIP, &tcpip_link_name(&addr)) 431 | }) 432 | } 433 | 434 | /// Connect to an existing WSTP [`TCPIP`][Protocol::TCPIP] link listening at `addr`. 435 | /// 436 | /// If `addr` yields multiple addresses, a connection will be attempted with each of 437 | /// the addresses until a connection is successful. If none of the addresses result 438 | /// in a successful connection, the error returned from the last connection attempt 439 | /// (the last address) is returned. 440 | pub fn tcpip_connect(addr: A) -> Result { 441 | let addrs = addr.to_socket_addrs().map_err(|err| { 442 | Error::custom(format!("error connecting to TCPIP Link address: {}", err)) 443 | })?; 444 | 445 | // Try each address, returning the first one which connects successfully. 446 | for_each_addr(addrs.collect(), |addr| { 447 | Link::connect(Protocol::TCPIP, &tcpip_link_name(&addr)) 448 | }) 449 | } 450 | 451 | /// Open a WSTP [`Protocol::TCPIP`] connection to a [`LinkServer`]. 452 | /// 453 | /// If `addrs` yields multiple addresses, a connection will be attempted with each of 454 | /// the addresses until a connection is successful. If none of the addresses result 455 | /// in a successful connection, the error returned from the last connection attempt 456 | /// (the last address) is returned. 457 | pub fn connect_to_link_server( 458 | addrs: A, 459 | ) -> Result { 460 | let addrs = addrs.to_socket_addrs().map_err(|err| { 461 | Error::custom(format!("error connecting to LinkServer address: {}", err)) 462 | })?; 463 | 464 | // Try each address, returning the first one which connects successfully. 465 | for_each_addr(addrs.collect(), |addr| { 466 | let mut link = Link::connect_with_options( 467 | Protocol::TCPIP, 468 | &tcpip_link_name(&addr), 469 | // Pass the magic option which signals that we're connecting to a 470 | // LinkServer, not just a normal Link. 471 | &["MLUseUUIDTCPIPConnection"], 472 | )?; 473 | 474 | // TODO: Should we activate here, or let the caller do this? 475 | let () = link.activate()?; 476 | 477 | return Ok(link); 478 | }) 479 | } 480 | 481 | #[allow(missing_docs)] 482 | pub fn connect_with_options( 483 | protocol: Protocol, 484 | name: &str, 485 | options: &[&str], 486 | ) -> Result { 487 | let protocol_string = protocol.to_string(); 488 | 489 | let mut strings: Vec<&str> = vec![ 490 | "-wstp", 491 | // "-linkconnect", 492 | "-linkmode", 493 | "connect", 494 | "-linkprotocol", 495 | protocol_string.as_str(), 496 | "-linkname", 497 | name, 498 | ]; 499 | 500 | if !options.is_empty() { 501 | strings.push("-linkoptions"); 502 | strings.extend(options); 503 | } 504 | 505 | Link::open_with_args(&strings) 506 | } 507 | 508 | /// *WSTP C API Documentation:* [`WSOpenArgcArgv()`](https://reference.wolfram.com/language/ref/c/WSOpenArgcArgv.html) 509 | /// 510 | /// This function can be used to create a [`Link`] of any protocol and mode. Prefer 511 | /// to use one of the constructor methods listed below when you know the type of link 512 | /// to be created. 513 | /// 514 | /// * [`Link::listen()`] 515 | /// * [`Link::connect()`] 516 | /// * [`Link::tcpip_listen()`] 517 | /// * [`Link::tcpip_connect()`] 518 | /// * [`Link::connect_to_link_server()`] 519 | // * [`Link::launch()`] 520 | // * [`Link::parent_connect()`] 521 | pub fn open_with_args(args: &[&str]) -> Result { 522 | // NOTE: Before returning, we must convert these back into CString's to 523 | // deallocate them. 524 | let mut c_strings: Vec<*mut c_char> = args 525 | .into_iter() 526 | .map(|&str| { 527 | CString::new(str) 528 | .expect("failed to create CString from WSTP link open argument") 529 | .into_raw() 530 | }) 531 | .collect(); 532 | 533 | let mut err: std::os::raw::c_int = sys::MLEOK; 534 | 535 | let raw_link = with_raw_stdenv(|raw_stdenv| unsafe { 536 | sys::WSOpenArgcArgv( 537 | raw_stdenv, 538 | i32::try_from(c_strings.len()).unwrap(), 539 | c_strings.as_mut_ptr(), 540 | &mut err, 541 | ) 542 | })?; 543 | 544 | // Convert the `*mut i8` C strings back into owned CString's, so that they are 545 | // deallocated. 546 | for c_string in c_strings { 547 | unsafe { 548 | let _ = CString::from_raw(c_string); 549 | } 550 | } 551 | 552 | if raw_link.is_null() || err != sys::MLEOK { 553 | return Err(Error::from_code(err)); 554 | } 555 | 556 | Ok(Link { raw_link }) 557 | } 558 | 559 | /// Construct a [`Link`] from a raw [`WSLINK`] pointer. 560 | pub unsafe fn unchecked_new(raw_link: WSLINK) -> Self { 561 | Link { raw_link } 562 | } 563 | 564 | /// *WSTP C API Documentation:* [`WSActivate()`](https://reference.wolfram.com/language/ref/c/WSActivate.html) 565 | pub fn activate(&mut self) -> Result<(), Error> { 566 | // Note: WSActivate() returns 0 in the event of an error, and sets an error 567 | // code retrievable by WSError(). 568 | if unsafe { sys::WSActivate(self.raw_link) } == 0 { 569 | return Err(self.error_or_unknown()); 570 | } 571 | 572 | Ok(()) 573 | } 574 | 575 | /// Close this end of the link. 576 | /// 577 | /// *WSTP C API Documentation:* [`WSClose()`](https://reference.wolfram.com/language/ref/c/WSClose.html) 578 | pub fn close(self) { 579 | // Note: The link is closed when `self` is dropped. 580 | } 581 | } 582 | 583 | /// Create a full-duplex WSTP communication channel with two [`Link`] endpoints. 584 | /// 585 | /// This function is a convenient alternative to manually using 586 | /// [`Link::listen()`] and [`Link::connect()`] to create a channel. 587 | /// 588 | /// # Example 589 | /// 590 | /// Construct a channel, and send data in both directions: 591 | /// 592 | /// ``` 593 | /// use wstp::Protocol; 594 | /// 595 | /// let (mut a, mut b) = wstp::channel(Protocol::SharedMemory).unwrap(); 596 | /// 597 | /// a.put_str("from a to b").unwrap(); 598 | /// a.flush().unwrap(); 599 | /// 600 | /// b.put_str("from b to a").unwrap(); 601 | /// b.flush().unwrap(); 602 | /// 603 | /// assert_eq!(a.get_string().unwrap(), "from b to a"); 604 | /// assert_eq!(b.get_string().unwrap(), "from a to b"); 605 | /// ``` 606 | pub fn channel(protocol: Protocol) -> Result<(Link, Link), Error> { 607 | let mut listener = Link::listen(protocol.clone(), "")?; 608 | let mut connecter = Link::connect(protocol, &listener.link_name())?; 609 | 610 | let listener = std::thread::spawn(move || { 611 | let () = listener.activate()?; 612 | Ok(listener) 613 | }); 614 | 615 | let () = connecter.activate()?; 616 | 617 | let listener = listener.join().expect("listener thread panicked")?; 618 | 619 | Ok((listener, connecter)) 620 | } 621 | 622 | /// # Link properties 623 | impl Link { 624 | /// Get the name of this link. 625 | /// 626 | /// *WSTP C API Documentation:* [`WSLinkName()`](https://reference.wolfram.com/language/ref/c/WSLinkName.html) 627 | pub fn link_name(&self) -> String { 628 | let Link { raw_link } = *self; 629 | 630 | unsafe { 631 | let name: *const c_char = self::sys::WSName(raw_link as *mut _); 632 | CStr::from_ptr(name).to_str().unwrap().to_owned() 633 | } 634 | } 635 | 636 | /// Check if there is data ready to be read from this link. 637 | /// 638 | /// *WSTP C API Documentation:* [`WSReady()`](https://reference.wolfram.com/language/ref/c/WSReady.html) 639 | pub fn is_ready(&self) -> bool { 640 | let Link { raw_link } = *self; 641 | 642 | unsafe { WSReady(raw_link) != 0 } 643 | } 644 | 645 | /// *WSTP C API Documentation:* [`WSIsLinkLoopback()`](https://reference.wolfram.com/language/ref/c/WSIsLinkLoopback.html) 646 | pub fn is_loopback(&self) -> bool { 647 | let Link { raw_link } = *self; 648 | 649 | 1 == unsafe { sys::WSIsLinkLoopback(raw_link) } 650 | } 651 | 652 | /// Returns an [`Error`] describing the last error to occur on this link. 653 | /// 654 | /// # Examples 655 | /// 656 | /// **TODO:** Example of getting an error code. 657 | pub fn error(&self) -> Option { 658 | let Link { raw_link } = *self; 659 | 660 | let (code, message): (i32, *const c_char) = 661 | unsafe { (sys::WSError(raw_link), WSErrorMessage(raw_link)) }; 662 | 663 | if code == sys::MLEOK || message.is_null() { 664 | return None; 665 | } 666 | 667 | let string: String = unsafe { 668 | let cstr = CStr::from_ptr(message); 669 | let string = cstr.to_str().unwrap().to_owned(); 670 | 671 | WSReleaseErrorMessage(raw_link, message); 672 | // TODO: Should this method clear the error? If it does, it should at least be 673 | // '&mut self'. 674 | // WSClearError(link); 675 | 676 | string 677 | }; 678 | 679 | return Some(Error { 680 | code: Some(code), 681 | message: string, 682 | }); 683 | } 684 | 685 | /// Returns a string describing the last error to occur on this link. 686 | /// 687 | /// TODO: If the most recent operation was successful, does the error message get 688 | /// cleared? 689 | /// 690 | /// *WSTP C API Documentation:* [`WSErrorMessage()`](https://reference.wolfram.com/language/ref/c/WSErrorMessage.html) 691 | pub fn error_message(&self) -> Option { 692 | self.error().map(|Error { message, code: _ }| message) 693 | } 694 | 695 | /// Helper to create an [`Error`] instance even if the underlying link does not have 696 | /// an error code set. 697 | pub(crate) fn error_or_unknown(&self) -> Error { 698 | self.error() 699 | .unwrap_or_else(|| Error::custom("unknown error occurred on WSLINK".into())) 700 | } 701 | 702 | /// Clear errors on this link. 703 | /// 704 | /// *WSTP C API Documentation:* [`WSClearError()`](https://reference.wolfram.com/language/ref/c/WSClearError.html) 705 | pub fn clear_error(&mut self) { 706 | let Link { raw_link } = *self; 707 | 708 | unsafe { 709 | sys::WSClearError(raw_link); 710 | } 711 | } 712 | 713 | /// *WSTP C API Documentation:* [`WSLINK`](https://reference.wolfram.com/language/ref/c/WSLINK.html) 714 | pub unsafe fn raw_link(&self) -> WSLINK { 715 | let Link { raw_link } = *self; 716 | raw_link 717 | } 718 | 719 | /// *WSTP C API Documentation:* [`WSUserData`](https://reference.wolfram.com/language/ref/c/WSUserData.html) 720 | pub unsafe fn user_data(&self) -> (*mut std::ffi::c_void, sys::WSUserFunction) { 721 | let Link { raw_link } = *self; 722 | 723 | let mut user_func: sys::WSUserFunction = None; 724 | 725 | let data_obj: *mut std::ffi::c_void = sys::WSUserData(raw_link, &mut user_func); 726 | 727 | (data_obj, user_func) 728 | } 729 | 730 | /// *WSTP C API Documentation:* [`WSSetUserData`](https://reference.wolfram.com/language/ref/c/WSSetUserData.html) 731 | pub unsafe fn set_user_data( 732 | &mut self, 733 | data_obj: *mut std::ffi::c_void, 734 | user_func: sys::WSUserFunction, 735 | ) { 736 | let Link { raw_link } = *self; 737 | 738 | sys::WSSetUserData(raw_link, data_obj, user_func); 739 | } 740 | } 741 | 742 | /// # Urgent messages 743 | impl Link { 744 | /// Returns `true` if there is an out-of-band urgent message available to read. 745 | /// 746 | /// *WSTP C API Documentation:* [`WSMessageReady()`](https://reference.wolfram.com/language/ref/c/WSMessageReady.html) 747 | pub fn is_message_ready(&self) -> bool { 748 | let Link { raw_link } = *self; 749 | 750 | unsafe { sys::WSMessageReady(raw_link) != 0 } 751 | } 752 | 753 | /// Send an out-of-band message. 754 | /// 755 | /// *WSTP C API Documentation:* [`WSPutMessage()`](https://reference.wolfram.com/language/ref/c/WSPutMessage.html) 756 | /// 757 | /// ``` 758 | /// use wstp::{Protocol, UrgentMessage}; 759 | /// 760 | /// let (mut a, mut b) = wstp::channel(Protocol::SharedMemory).unwrap(); 761 | /// 762 | /// a.put_message(UrgentMessage::ABORT).unwrap(); 763 | /// 764 | /// assert_eq!(b.get_message(), Some(UrgentMessage::ABORT)); 765 | /// ``` 766 | pub fn put_message(&mut self, message: UrgentMessage) -> Result<(), Error> { 767 | let Link { raw_link } = *self; 768 | 769 | let UrgentMessage { code, param } = message; 770 | 771 | let code = i32::try_from(code).expect("WSTP urgent message code overflows i32"); 772 | 773 | let param = 774 | i32::try_from(param).expect("WSTP urgent message param overflows i32"); 775 | 776 | let result = unsafe { sys::WSPutMessageWithArg(raw_link, code, param) }; 777 | 778 | if result == 0 { 779 | return Err(self.error_or_unknown()); 780 | } 781 | 782 | Ok(()) 783 | } 784 | 785 | /// This function does not block if no urgent message is available. 786 | /// 787 | /// *WSTP C API Documentation:* [`WSGetMessage()`](https://reference.wolfram.com/language/ref/c/WSGetMessage.html) 788 | pub fn get_message(&mut self) -> Option { 789 | let Link { raw_link } = *self; 790 | 791 | let mut code: i32 = 0; 792 | let mut param: i32 = 0; 793 | 794 | let result = unsafe { sys::WSGetMessage(raw_link, &mut code, &mut param) }; 795 | 796 | let code = 797 | u32::try_from(code).expect("WSTP urgent message code doesn't fit into u32"); 798 | let param = 799 | u32::try_from(param).expect("WSTP urgent message param doesn't fit into u32"); 800 | 801 | if result != 0 { 802 | Some(UrgentMessage { code, param }) 803 | } else { 804 | None 805 | } 806 | } 807 | } 808 | 809 | /// # Reading and writing expressions 810 | impl Link { 811 | /// Flush out any buffers containing data waiting to be sent on this link. 812 | /// 813 | /// *WSTP C API Documentation:* [`WSFlush()`](https://reference.wolfram.com/language/ref/c/WSFlush.html) 814 | pub fn flush(&mut self) -> Result<(), Error> { 815 | if unsafe { sys::WSFlush(self.raw_link) } == 0 { 816 | return Err(self.error_or_unknown()); 817 | } 818 | 819 | Ok(()) 820 | } 821 | 822 | /// *WSTP C API Documentation:* [`WSGetNext()`](https://reference.wolfram.com/language/ref/c/WSGetNext.html) 823 | pub fn raw_get_next(&mut self) -> Result { 824 | let type_ = unsafe { sys::WSGetNext(self.raw_link) }; 825 | 826 | if type_ == sys::WSTKERR { 827 | return Err(self.error_or_unknown()); 828 | } 829 | 830 | Ok(type_) 831 | } 832 | 833 | /// *WSTP C API Documentation:* [`WSNextPacket()`](https://reference.wolfram.com/language/ref/c/WSNextPacket.html) 834 | pub fn raw_next_packet(&mut self) -> Result { 835 | let type_ = unsafe { sys::WSNextPacket(self.raw_link) }; 836 | 837 | if type_ == sys::ILLEGALPKT { 838 | return Err(self.error_or_unknown()); 839 | } 840 | 841 | Ok(type_) 842 | } 843 | 844 | /// *WSTP C API Documentation:* [`WSNewPacket()`](https://reference.wolfram.com/language/ref/c/WSNewPacket.html) 845 | pub fn new_packet(&mut self) -> Result<(), Error> { 846 | if unsafe { sys::WSNewPacket(self.raw_link) } == 0 { 847 | return Err(self.error_or_unknown()); 848 | } 849 | 850 | Ok(()) 851 | } 852 | 853 | /// Read an expression off of this link. 854 | pub fn get_expr(&mut self) -> Result { 855 | self.get_expr_with_resolver(&mut |_| None) 856 | } 857 | 858 | // TODO: This needs a bit more design work before being made public. For starters, 859 | // you have to pass a closure to it using `get_expr_with_resolver(&mut |_| ...)` 860 | // which looks out of place. Using `dyn FnMut()` is to avoid having to 861 | // monomorphize different copies of `get_expr_with_resolver()` 862 | #[doc(hidden)] 863 | pub fn get_expr_with_resolver( 864 | &mut self, 865 | mut resolver: &mut dyn FnMut(&str) -> Option, 866 | ) -> Result { 867 | let value = self.get_token()?; 868 | 869 | let expr: Expr = match value { 870 | Token::Integer(value) => Expr::from(value), 871 | Token::Real(value) => { 872 | let real: wolfram_expr::F64 = match wolfram_expr::F64::new(value) { 873 | Ok(real) => real, 874 | // TODO: Try passing a NaN value or a BigReal value through WSLINK. 875 | Err(_is_nan) => { 876 | return Err(Error::custom(format!( 877 | "NaN value passed on WSLINK cannot be used to construct an Expr" 878 | ))) 879 | }, 880 | }; 881 | Expr::number(Number::Real(real)) 882 | }, 883 | Token::String(value) => Expr::string(value.as_str()), 884 | Token::Symbol(value) => { 885 | let symbol_str: &str = value.as_str(); 886 | 887 | // If `symbol_str` is not an absolute symbol, use the provided `resolver` 888 | // to attempt to resolve it into a concrete Symbol. 889 | let symbol = Symbol::try_new(symbol_str).or_else(|| resolver(symbol_str)); 890 | 891 | let symbol: Symbol = match symbol { 892 | Some(sym) => sym, 893 | None => { 894 | return Err(Error::custom(format!( 895 | "symbol name '{}' has no context", 896 | symbol_str 897 | ))) 898 | }, 899 | }; 900 | 901 | Expr::symbol(symbol) 902 | }, 903 | Token::Function { length: arg_count } => { 904 | drop(value); 905 | 906 | let head = self.get_expr_with_resolver(&mut resolver)?; 907 | 908 | let mut contents = Vec::with_capacity(arg_count); 909 | for _ in 0..arg_count { 910 | contents.push(self.get_expr_with_resolver(&mut resolver)?); 911 | } 912 | 913 | Expr::normal(head, contents) 914 | }, 915 | }; 916 | 917 | Ok(expr) 918 | } 919 | 920 | /// Write an expression to this link. 921 | pub fn put_expr(&mut self, expr: &Expr) -> Result<(), Error> { 922 | match expr.kind() { 923 | ExprKind::Normal(normal) => { 924 | self.put_raw_type(i32::from(sys::WSTKFUNC))?; 925 | self.put_arg_count(normal.elements().len())?; 926 | 927 | let _: () = self.put_expr(normal.head())?; 928 | 929 | for elem in normal.elements() { 930 | let _: () = self.put_expr(elem)?; 931 | } 932 | }, 933 | ExprKind::Symbol(symbol) => { 934 | self.put_symbol(symbol.as_str())?; 935 | }, 936 | ExprKind::String(string) => { 937 | self.put_str(string.as_str())?; 938 | }, 939 | ExprKind::Integer(int) => { 940 | self.put_i64(*int)?; 941 | }, 942 | ExprKind::Real(real) => { 943 | self.put_f64(**real)?; 944 | }, 945 | } 946 | 947 | Ok(()) 948 | } 949 | 950 | /// Transfer an expression from this link to another. 951 | /// 952 | /// # Example 953 | /// 954 | /// Transfer an expression between two loopback links: 955 | /// 956 | /// ``` 957 | /// use wstp::Link; 958 | /// 959 | /// let mut a = Link::new_loopback().unwrap(); 960 | /// let mut b = Link::new_loopback().unwrap(); 961 | /// 962 | /// // Put an expression into `a` 963 | /// a.put_i64(5).unwrap(); 964 | /// 965 | /// // Transfer it to `b` 966 | /// a.transfer_expr_to(&mut b).unwrap(); 967 | /// 968 | /// assert_eq!(b.get_i64().unwrap(), 5); 969 | /// ``` 970 | /// 971 | /// *WSTP C API Documentation:* [`WSTransferExpression()`](https://reference.wolfram.com/language/ref/c/WSTransferExpression.html) 972 | pub fn transfer_expr_to(&mut self, dest: &mut Link) -> Result<(), Error> { 973 | let result = unsafe { sys::WSTransferExpression(dest.raw_link, self.raw_link) }; 974 | 975 | if result == 0 { 976 | return Err(self.error_or_unknown()); 977 | } 978 | 979 | Ok(()) 980 | } 981 | 982 | /// Transfer the full contents of this loopback link to `dest`. 983 | /// 984 | /// *WSTP C API Documentation:* [`WSTransferToEndOfLoopbackLink()`](https://reference.wolfram.com/language/ref/c/WSTransferToEndOfLoopbackLink.html) 985 | /// 986 | /// # Panics 987 | /// 988 | /// This function will panic if `!self.is_loopback()`. 989 | pub fn transfer_to_end_of_loopback_link( 990 | &mut self, 991 | dest: &mut Link, 992 | ) -> Result<(), Error> { 993 | if !self.is_loopback() { 994 | panic!("transfer_to_end_of_loopback_link(): self must be a loopback link"); 995 | } 996 | 997 | let result = 998 | unsafe { sys::WSTransferToEndOfLoopbackLink(dest.raw_link, self.raw_link) }; 999 | 1000 | if result == 0 { 1001 | return if let Some(err) = self.error() { 1002 | Err(err) 1003 | } else if let Some(err) = dest.error() { 1004 | Err(err) 1005 | } else { 1006 | Err(Error::custom("unknown error occurred on WSLINK".into())) 1007 | }; 1008 | } 1009 | 1010 | Ok(()) 1011 | } 1012 | } 1013 | 1014 | //====================================== 1015 | // Utilities 1016 | //====================================== 1017 | 1018 | fn for_each_addr(addrs: Vec, mut func: F) -> Result 1019 | where 1020 | F: FnMut(net::SocketAddr) -> Result, 1021 | { 1022 | let mut last_error = None; 1023 | 1024 | for addr in addrs { 1025 | match func(addr) { 1026 | Ok(result) => return Ok(result), 1027 | Err(err) => last_error = Some(err), 1028 | } 1029 | } 1030 | 1031 | Err(last_error 1032 | .unwrap_or_else(|| Error::custom(format!("socket address list is empty")))) 1033 | } 1034 | 1035 | /// Construct an address string in the special syntax used by WSTP. 1036 | fn tcpip_link_name(addr: &net::SocketAddr) -> String { 1037 | format!("{}@{}", addr.port(), addr.ip()) 1038 | } 1039 | 1040 | //====================================== 1041 | // Formatting impls 1042 | //====================================== 1043 | 1044 | impl Display for Protocol { 1045 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1046 | let str = match self { 1047 | Protocol::IntraProcess => "IntraProcess", 1048 | Protocol::SharedMemory => "SharedMemory", 1049 | Protocol::TCPIP => "TCPIP", 1050 | }; 1051 | 1052 | write!(f, "{}", str) 1053 | } 1054 | } 1055 | 1056 | //====================================== 1057 | // Drop impls 1058 | //====================================== 1059 | 1060 | impl Drop for Link { 1061 | fn drop(&mut self) { 1062 | let Link { raw_link } = *self; 1063 | 1064 | unsafe { 1065 | sys::WSClose(raw_link); 1066 | } 1067 | } 1068 | } 1069 | -------------------------------------------------------------------------------- /wstp/src/link_server.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{CStr, CString}; 2 | use std::fmt; 3 | use std::os::raw::c_int; 4 | use std::str::FromStr; 5 | 6 | use crate::env::with_raw_stdenv; 7 | use crate::{sys, Error, Link}; 8 | 9 | /// WSTP link server. 10 | /// 11 | /// This is a wrapper around the 12 | /// [`WSLinkServer`](https://reference.wolfram.com/language/ref/c/WSLinkServer.html) 13 | /// C type. 14 | /// 15 | /// # Usage 16 | /// 17 | /// **TODO:** Document the two different methods for accepting new [`Link`] connections 18 | /// from this type (waiting and an async callback). 19 | pub struct LinkServer { 20 | raw_link_server: sys::WSLinkServer, 21 | } 22 | 23 | /// An iterator that infinitely [`accept`]s connections on a [`LinkServer`]. 24 | /// 25 | /// This `struct` is created by the [`LinkServer::incoming`] method. 26 | /// 27 | /// [`accept`]: LinkServer::accept 28 | pub struct Incoming<'a> { 29 | server: &'a LinkServer, 30 | } 31 | 32 | impl LinkServer { 33 | /// Create a new `LinkServer` bound to the specified address. 34 | /// 35 | /// Use [`Link::connect_to_link_server`] to connect to a `LinkServer`. 36 | /// 37 | /// # Examples 38 | /// 39 | /// ``` 40 | /// use wstp::LinkServer; 41 | /// 42 | /// let server = LinkServer::bind("127.0.0.1:8080").unwrap(); 43 | /// ``` 44 | pub fn bind(addrs: A) -> Result { 45 | let addrs = addrs.to_socket_addrs().map_err(|err| { 46 | Error::custom(format!("error binding LinkServer to address: {}", err)) 47 | })?; 48 | 49 | // Try each address, returning the first one which binds successfully. 50 | crate::for_each_addr(addrs.collect(), |addr| { 51 | let mut err: std::os::raw::c_int = sys::MLEOK; 52 | 53 | let iface = CString::new(addr.ip().to_string()) 54 | .expect("failed to create CString from LinkServer interface"); 55 | 56 | let raw_link_server: sys::WSLinkServer = 57 | with_raw_stdenv(|raw_stdenv| unsafe { 58 | sys::WSNewLinkServerWithPortAndInterface( 59 | raw_stdenv, 60 | addr.port(), 61 | iface.as_ptr(), 62 | std::ptr::null_mut(), 63 | &mut err, 64 | ) 65 | })?; 66 | 67 | if raw_link_server.is_null() || err != sys::MLEOK { 68 | return Err(Error::from_code(err)); 69 | } 70 | 71 | return Ok(LinkServer { raw_link_server }); 72 | }) 73 | } 74 | 75 | /// Create a new link server. 76 | /// 77 | /// It is not possible to register a callback function to accept new link connections 78 | /// after the link server has been created. Use [`LinkServer::new_with_callback()`] if 79 | /// that functionality is desired. 80 | /// 81 | /// Use [`LinkServer::accept()`] to accept new connections to the link server. 82 | pub fn new(port: u16) -> Result { 83 | let mut err: std::os::raw::c_int = sys::MLEOK; 84 | 85 | let raw_server: sys::WSLinkServer = with_raw_stdenv(|raw_stdenv| unsafe { 86 | sys::WSNewLinkServerWithPort(raw_stdenv, port, std::ptr::null_mut(), &mut err) 87 | })?; 88 | 89 | if raw_server.is_null() || err != sys::MLEOK { 90 | return Err(Error::from_code(err)); 91 | } 92 | 93 | Ok(LinkServer { 94 | raw_link_server: raw_server, 95 | }) 96 | } 97 | 98 | /// The callback is required to be [`Send`] so that it can be called from the link 99 | /// server's background thread, which accepts incoming connections. 100 | /// 101 | /// # `'static` bound 102 | /// 103 | /// The `'static` bound is required to prevent the callback closure from capturing a 104 | /// reference to non-static data that it might outlive, for example a local variable: 105 | /// 106 | // Note: This example acts as a test that the below code is not possible to write. Do 107 | // not remove this example without replacing it with another test. 108 | /// ```compile_fail 109 | /// use std::sync::Mutex; 110 | /// use wstp::LinkServer; 111 | /// 112 | /// let mut counter = Mutex::new(0); 113 | /// 114 | /// let server = LinkServer::new_with_callback( 115 | /// 11235, 116 | /// // Error: the closure may outlive borrowed value `counter` 117 | /// |_| *counter.lock().unwrap() += 1 118 | /// ); 119 | /// 120 | /// println!("counter: {}", counter.lock().unwrap()); 121 | /// ``` 122 | /// 123 | /// Note that the reasoning for the `Send` and `'static` constraints is similiar to 124 | /// that for [`std::thread::spawn()`], whose documentation may be a useful 125 | /// additional reference. 126 | pub fn new_with_callback(port: u16, callback: F) -> Result 127 | where 128 | F: FnMut(Link) + Send + Sync + 'static, 129 | { 130 | let mut err: std::os::raw::c_int = sys::MLEOK; 131 | 132 | let raw_server: sys::WSLinkServer = with_raw_stdenv(|raw_stdenv| unsafe { 133 | sys::WSNewLinkServerWithPort( 134 | raw_stdenv, 135 | port, 136 | Box::into_raw(Box::new(callback)) as *mut std::ffi::c_void, 137 | &mut err, 138 | ) 139 | })?; 140 | 141 | if raw_server.is_null() || err != sys::MLEOK { 142 | return Err(Error::from_code(err)); 143 | } 144 | 145 | unsafe { 146 | sys::WSRegisterCallbackFunctionWithLinkServer( 147 | raw_server, 148 | Some(callback_trampoline::), 149 | ) 150 | } 151 | 152 | Ok(LinkServer { 153 | raw_link_server: raw_server, 154 | }) 155 | } 156 | 157 | /// Returns the TCPIP port number used by this link server. 158 | /// 159 | /// *WSTP C API Documentation:* [WSPortFromLinkServer](https://reference.wolfram.com/language/ref/c/WSPortFromLinkServer.html) 160 | pub fn port(&self) -> u16 { 161 | self.try_port() 162 | .unwrap_or_else(|err| panic!("WSPortFromLinkServer failed: {}", err)) 163 | } 164 | 165 | /// Fallible variant of [LinkServer::port()]. 166 | pub fn try_port(&self) -> Result { 167 | let mut err: std::os::raw::c_int = sys::MLEOK; 168 | 169 | let port: u16 = 170 | unsafe { sys::WSPortFromLinkServer(self.raw_link_server, &mut err) }; 171 | 172 | if err != sys::MLEOK { 173 | return Err(Error::from_code(err)); 174 | } 175 | 176 | Ok(port) 177 | } 178 | 179 | /// Returns the IP address of the interface used by this link server. 180 | /// 181 | /// *WSTP C API Documentation:* [WSInterfaceFromLinkServer](https://reference.wolfram.com/language/ref/c/WSInterfaceFromLinkServer.html) 182 | pub fn interface(&self) -> std::net::IpAddr { 183 | self.try_interface() 184 | .unwrap_or_else(|err| panic!("WSInterfaceFromLinkServer failed: {}", err)) 185 | } 186 | 187 | /// Fallible variant of [LinkServer::interface()]. 188 | // TODO(breaking): Make this return something other than an IpAddr, since 189 | // WSInterfaceFromLinkServer(..) isn't actually guaranteed 190 | // to return a IP address--it can also return a domain name 191 | // (commonly a local domain name). 192 | pub fn try_interface(&self) -> Result { 193 | let mut err: c_int = sys::MLEOK; 194 | 195 | let iface_cstr = 196 | unsafe { sys::WSInterfaceFromLinkServer(self.raw_link_server, &mut err) }; 197 | 198 | if iface_cstr.is_null() || err != sys::MLEOK { 199 | return Err(Error::from_code(err)); 200 | } 201 | 202 | let iface: String = unsafe { 203 | let iface = CStr::from_ptr(iface_cstr); 204 | 205 | match iface.to_str() { 206 | Ok(str) => str.to_string(), 207 | Err(utf8_error) => { 208 | sys::WSReleaseInterfaceFromLinkServer( 209 | self.raw_link_server, 210 | iface_cstr, 211 | ); 212 | return Err(Error::custom(format!( 213 | "LinkServer interface could not be converted to UTF-8 string (error: {}, lossy: '{}')", 214 | utf8_error, 215 | iface.to_string_lossy() 216 | ))); 217 | }, 218 | } 219 | }; 220 | 221 | unsafe { 222 | sys::WSReleaseInterfaceFromLinkServer(self.raw_link_server, iface_cstr); 223 | }; 224 | 225 | match std::net::IpAddr::from_str(iface.as_str()) { 226 | Ok(ip) => Ok(ip), 227 | Err(err) => Err(Error::custom(format!( 228 | "unable to parse LinkServer interface ({}) as IpAddr: {}", 229 | iface, err 230 | ))), 231 | } 232 | } 233 | 234 | /// Close this link server. 235 | /// 236 | /// This link server will stop accepting new connections, and unbind from the network 237 | /// port it is attached to. 238 | /// 239 | /// *WSTP C API Documentation:* [`WSShutdownLinkServer`](https://reference.wolfram.com/language/ref/c/WSShutdownLinkServer.html) 240 | pub fn close(self) { 241 | // Note: The link server is closed when `self` is dropped. 242 | } 243 | 244 | /// Accept a new incoming connection to this link server. 245 | /// 246 | /// This method blocks the current thread indefinitely until a connection is made to 247 | /// the port this link server is bound to. 248 | /// 249 | /// Use [`LinkServer::new_with_callback()`] to create a link server which accepts 250 | /// connections asyncronously via a callback function. 251 | /// 252 | /// *WSTP C API Documentation:* [`WSWaitForNewLinkFromLinkServer`](https://reference.wolfram.com/language/ref/c/WSWaitForNewLinkFromLinkServer.html) 253 | pub fn accept(&self) -> Result { 254 | let mut err: c_int = sys::MLEOK; 255 | 256 | let raw_link = unsafe { 257 | sys::WSWaitForNewLinkFromLinkServer(self.raw_link_server, &mut err) 258 | }; 259 | 260 | if raw_link.is_null() || err != sys::MLEOK { 261 | return Err(Error::from_code(err)); 262 | } 263 | 264 | let link = unsafe { Link::unchecked_new(raw_link) }; 265 | 266 | Ok(link) 267 | } 268 | 269 | /// Returns an iterator over the connections being received on this server. 270 | /// 271 | /// The returned iterator will never return None. Iterating over it is equivalent to 272 | /// calling [`LinkServer::accept`] in a loop. 273 | pub fn incoming(&self) -> Incoming { 274 | Incoming { server: self } 275 | } 276 | 277 | /// Returns the raw [`WSLinkServer`](https://reference.wolfram.com/language/ref/c/WSLinkServer.html) 278 | /// C type wrapped by this [`LinkServer`]. 279 | pub fn raw_link_server(&self) -> sys::WSLinkServer { 280 | self.raw_link_server 281 | } 282 | } 283 | 284 | extern "C" fn callback_trampoline( 285 | raw_link_server: sys::WSLinkServer, 286 | raw_link: sys::WSLINK, 287 | ) { 288 | let mut err: std::os::raw::c_int = sys::MLEOK; 289 | 290 | let user_closure: &mut F; 291 | let link: Link; 292 | 293 | unsafe { 294 | let raw_user_closure: *mut std::ffi::c_void = 295 | sys::WSContextFromLinkServer(raw_link_server, &mut err); 296 | 297 | user_closure = &mut *(raw_user_closure as *mut F); 298 | 299 | // SAFETY: This is safe because `raw_link` is an entirely new link which we have 300 | // ownership over. 301 | link = Link::unchecked_new(raw_link); 302 | } 303 | 304 | // Call the closure provided by the user 305 | // FIXME: Catch panic's in the user's code to prevent unwinding over C stack frames. 306 | user_closure(link); 307 | } 308 | 309 | impl Drop for LinkServer { 310 | fn drop(&mut self) { 311 | let LinkServer { raw_link_server } = *self; 312 | 313 | unsafe { 314 | sys::WSShutdownLinkServer(raw_link_server); 315 | } 316 | } 317 | } 318 | 319 | impl fmt::Debug for LinkServer { 320 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 321 | write!( 322 | f, 323 | "LinkServer(Port: {}, Interface: {})", 324 | self.port(), 325 | self.interface() 326 | ) 327 | } 328 | } 329 | 330 | impl<'a> Iterator for Incoming<'a> { 331 | type Item = Result; 332 | 333 | fn next(&mut self) -> Option { 334 | Some(self.server.accept()) 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /wstp/src/put.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryFrom; 2 | use std::ffi::CString; 3 | 4 | use crate::{ 5 | sys::{ 6 | self, WSPutArgCount, WSPutInteger16, WSPutInteger32, WSPutInteger64, 7 | WSPutInteger8, WSPutReal32, WSPutReal64, WSPutUTF16String, WSPutUTF32String, 8 | WSPutUTF8String, WSPutUTF8Symbol, 9 | }, 10 | Error, Link, 11 | }; 12 | 13 | impl Link { 14 | /// TODO: Augment this function with a `put_type()` method which takes a 15 | /// (non-exhaustive) enum value. 16 | /// 17 | /// *WSTP C API Documentation:* [`WSPutType()`](https://reference.wolfram.com/language/ref/c/WSPutType.html) 18 | pub fn put_raw_type(&mut self, type_: i32) -> Result<(), Error> { 19 | if unsafe { sys::WSPutType(self.raw_link, type_) } == 0 { 20 | return Err(self.error_or_unknown()); 21 | } 22 | 23 | Ok(()) 24 | } 25 | 26 | /// *WSTP C API Documentation:* [`WSEndPacket()`](https://reference.wolfram.com/language/ref/c/WSEndPacket.html) 27 | pub fn end_packet(&mut self) -> Result<(), Error> { 28 | if unsafe { sys::WSEndPacket(self.raw_link) } == 0 { 29 | return Err(self.error_or_unknown()); 30 | } 31 | 32 | Ok(()) 33 | } 34 | 35 | //================================== 36 | // Atoms 37 | //================================== 38 | 39 | /// *WSTP C API Documentation:* [`WSPutUTF8String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF8String.html) 40 | pub fn put_str(&mut self, string: &str) -> Result<(), Error> { 41 | let len = i32::try_from(string.as_bytes().len()).expect("usize overflows i32"); 42 | let ptr = string.as_ptr() as *const u8; 43 | 44 | if unsafe { WSPutUTF8String(self.raw_link, ptr, len) } == 0 { 45 | return Err(self.error_or_unknown()); 46 | } 47 | 48 | Ok(()) 49 | } 50 | 51 | /// *WSTP C API Documentation:* [`WSPutUTF8Symbol()`](https://reference.wolfram.com/language/ref/c/WSPutUTF8Symbol.html) 52 | pub fn put_symbol(&mut self, symbol: &str) -> Result<(), Error> { 53 | // FIXME: 54 | // Is this extra allocation necessary?WSPutUTF8Symbol doesn't seem to require 55 | // that the data contains a NULL terminator, so we should be able to just 56 | // pass a pointer to `symbol`'s data. 57 | let c_string = CString::new(symbol).unwrap(); 58 | 59 | let len = i32::try_from(c_string.as_bytes().len()).expect("usize overflows i32"); 60 | let ptr = c_string.as_ptr() as *const u8; 61 | 62 | if unsafe { WSPutUTF8Symbol(self.raw_link, ptr, len) } == 0 { 63 | return Err(self.error_or_unknown()); 64 | } 65 | 66 | Ok(()) 67 | } 68 | 69 | //================================== 70 | // Strings 71 | //================================== 72 | 73 | /// *WSTP C API Documentation:* [`WSPutUTF8String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF8String.html) 74 | /// 75 | /// This function will return a WSTP error if `utf8` is not a valid UTF-8 encoded 76 | /// string. 77 | pub fn put_utf8_str(&mut self, utf8: &[u8]) -> Result<(), Error> { 78 | let len = i32::try_from(utf8.len()).expect("usize overflows i32"); 79 | 80 | if unsafe { WSPutUTF8String(self.raw_link, utf8.as_ptr(), len) } == 0 { 81 | return Err(self.error_or_unknown()); 82 | } 83 | Ok(()) 84 | } 85 | 86 | /// Put a UTF-16 encoded string. 87 | /// 88 | /// This function will return a WSTP error if `utf16` is not a valid UTF-16 encoded 89 | /// string. 90 | /// 91 | /// *WSTP C API Documentation:* [`WSPutUTF16String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF16String.html) 92 | /// 93 | pub fn put_utf16_str(&mut self, utf16: &[u16]) -> Result<(), Error> { 94 | let len = i32::try_from(utf16.len()).expect("usize overflows i32"); 95 | 96 | if unsafe { WSPutUTF16String(self.raw_link, utf16.as_ptr(), len) } == 0 { 97 | return Err(self.error_or_unknown()); 98 | } 99 | Ok(()) 100 | } 101 | 102 | /// Put a UTF-32 encoded string. 103 | /// 104 | /// This function will return a WSTP error if `utf32` is not a valid UTF-32 encoded 105 | /// string. 106 | /// 107 | /// *WSTP C API Documentation:* [`WSPutUTF32String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF32String.html) 108 | pub fn put_utf32_str(&mut self, utf32: &[u32]) -> Result<(), Error> { 109 | let len = i32::try_from(utf32.len()).expect("usize overflows i32"); 110 | 111 | if unsafe { WSPutUTF32String(self.raw_link, utf32.as_ptr(), len) } == 0 { 112 | return Err(self.error_or_unknown()); 113 | } 114 | Ok(()) 115 | } 116 | 117 | //================================== 118 | // Functions 119 | //================================== 120 | 121 | /// Begin putting a function onto this link. 122 | /// 123 | /// # Examples 124 | /// 125 | /// Put the expression `{1, 2, 3}` on the link: 126 | /// 127 | /// ``` 128 | /// # use wstp::Link; 129 | /// # fn test() -> Result<(), wstp::Error> { 130 | /// let mut link = Link::new_loopback()?; 131 | /// 132 | /// link.put_function("System`List", 3)?; 133 | /// link.put_i64(1)?; 134 | /// link.put_i64(2)?; 135 | /// link.put_i64(3)?; 136 | /// # Ok(()) 137 | /// # } 138 | /// ``` 139 | /// 140 | /// Put the expression `foo["a"]["b"]` on the link: 141 | /// 142 | /// ``` 143 | /// # use wstp::Link; 144 | /// # fn test() -> Result { 145 | /// let mut link = Link::new_loopback()?; 146 | /// 147 | /// link.put_function(None, 1)?; 148 | /// link.put_function("Global`foo", 1)?; 149 | /// link.put_str("a")?; 150 | /// link.put_str("b")?; 151 | /// # link.get_expr() 152 | /// # } 153 | /// 154 | /// # use wolfram_expr::{Expr, Symbol}; 155 | /// # assert_eq!(test().unwrap(), Expr::normal( 156 | /// # Expr::normal(Symbol::new("Global`foo"), vec![Expr::string("a")]), 157 | /// # vec![Expr::string("b")] 158 | /// # )) 159 | /// ``` 160 | pub fn put_function<'h, H: Into>>( 161 | &mut self, 162 | head: H, 163 | count: usize, 164 | ) -> Result<(), Error> { 165 | self.put_raw_type(i32::from(sys::WSTKFUNC))?; 166 | self.put_arg_count(count)?; 167 | 168 | if let Some(head) = head.into() { 169 | self.put_symbol(head)?; 170 | } 171 | 172 | Ok(()) 173 | } 174 | 175 | /// *WSTP C API Documentation:* [`WSPutArgCount()`](https://reference.wolfram.com/language/ref/c/WSPutArgCount.html) 176 | pub fn put_arg_count(&mut self, count: usize) -> Result<(), Error> { 177 | let count: i32 = i32::try_from(count).map_err(|err| { 178 | Error::custom(format!( 179 | "put_arg_count: Error converting usize to i32: {}", 180 | err 181 | )) 182 | })?; 183 | 184 | if unsafe { WSPutArgCount(self.raw_link, count) } == 0 { 185 | return Err(self.error_or_unknown()); 186 | } 187 | 188 | Ok(()) 189 | } 190 | 191 | //================================== 192 | // Numerics 193 | //================================== 194 | 195 | /// *WSTP C API Documentation:* [`WSPutInteger64()`](https://reference.wolfram.com/language/ref/c/WSPutInteger64.html) 196 | pub fn put_i64(&mut self, value: i64) -> Result<(), Error> { 197 | if unsafe { WSPutInteger64(self.raw_link, value) } == 0 { 198 | return Err(self.error_or_unknown()); 199 | } 200 | Ok(()) 201 | } 202 | 203 | /// *WSTP C API Documentation:* [`WSPutInteger32()`](https://reference.wolfram.com/language/ref/c/WSPutInteger32.html) 204 | pub fn put_i32(&mut self, value: i32) -> Result<(), Error> { 205 | if unsafe { WSPutInteger32(self.raw_link, value) } == 0 { 206 | return Err(self.error_or_unknown()); 207 | } 208 | Ok(()) 209 | } 210 | 211 | /// *WSTP C API Documentation:* [`WSPutInteger16()`](https://reference.wolfram.com/language/ref/c/WSPutInteger16.html) 212 | pub fn put_i16(&mut self, value: i16) -> Result<(), Error> { 213 | // Note: This conversion is necessary due to the declaration of WSPutInteger16, 214 | // which takes an int for legacy reasons. 215 | let value = i32::from(value); 216 | 217 | if unsafe { WSPutInteger16(self.raw_link, value) } == 0 { 218 | return Err(self.error_or_unknown()); 219 | } 220 | Ok(()) 221 | } 222 | 223 | /// *WSTP C API Documentation:* [`WSPutInteger8()`](https://reference.wolfram.com/language/ref/c/WSPutInteger8.html) 224 | pub fn put_u8(&mut self, value: u8) -> Result<(), Error> { 225 | if unsafe { WSPutInteger8(self.raw_link, value) } == 0 { 226 | return Err(self.error_or_unknown()); 227 | } 228 | Ok(()) 229 | } 230 | 231 | /// *WSTP C API Documentation:* [`WSPutReal64()`](https://reference.wolfram.com/language/ref/c/WSPutReal64.html) 232 | pub fn put_f64(&mut self, value: f64) -> Result<(), Error> { 233 | if unsafe { WSPutReal64(self.raw_link, value) } == 0 { 234 | return Err(self.error_or_unknown()); 235 | } 236 | Ok(()) 237 | } 238 | 239 | /// *WSTP C API Documentation:* [`WSPutReal32()`](https://reference.wolfram.com/language/ref/c/WSPutReal32.html) 240 | pub fn put_f32(&mut self, value: f32) -> Result<(), Error> { 241 | // Note: This conversion is necessary due to the declaration of WSPutReal32, 242 | // which takes a double for legacy reasons. 243 | let value = f64::from(value); 244 | 245 | if unsafe { WSPutReal32(self.raw_link, value) } == 0 { 246 | return Err(self.error_or_unknown()); 247 | } 248 | Ok(()) 249 | } 250 | 251 | //================================== 252 | // Integer numeric arrays 253 | //================================== 254 | 255 | /// Put a multidimensional array of [`i64`]. 256 | /// 257 | /// # Panics 258 | /// 259 | /// This function will panic if the product of `dimensions` is not equal to `data.len()`. 260 | /// 261 | /// *WSTP C API Documentation:* [`WSPutInteger64Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger64Array.html) 262 | pub fn put_i64_array( 263 | &mut self, 264 | data: &[i64], 265 | dimensions: &[usize], 266 | ) -> Result<(), Error> { 267 | assert_eq!( 268 | data.len(), 269 | dimensions.iter().product(), 270 | "data length does not equal product of dimensions" 271 | ); 272 | 273 | let dimensions: Vec = abi_array_dimensions(dimensions)?; 274 | 275 | let result = unsafe { 276 | sys::WSPutInteger64Array( 277 | self.raw_link, 278 | data.as_ptr(), 279 | dimensions.as_ptr(), 280 | std::ptr::null_mut(), 281 | dimensions.len() as i32, 282 | ) 283 | }; 284 | 285 | if result == 0 { 286 | return Err(self.error_or_unknown()); 287 | } 288 | 289 | Ok(()) 290 | } 291 | 292 | /// Put a multidimensional array of [`i32`]. 293 | /// 294 | /// # Panics 295 | /// 296 | /// This function will panic if the product of `dimensions` is not equal to `data.len()`. 297 | /// 298 | /// *WSTP C API Documentation:* [`WSPutInteger32Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger32Array.html) 299 | pub fn put_i32_array( 300 | &mut self, 301 | data: &[i32], 302 | dimensions: &[usize], 303 | ) -> Result<(), Error> { 304 | assert_eq!( 305 | data.len(), 306 | dimensions.iter().product(), 307 | "data length does not equal product of dimensions" 308 | ); 309 | 310 | let dimensions: Vec = abi_array_dimensions(dimensions)?; 311 | 312 | let result = unsafe { 313 | sys::WSPutInteger32Array( 314 | self.raw_link, 315 | data.as_ptr(), 316 | dimensions.as_ptr(), 317 | std::ptr::null_mut(), 318 | dimensions.len() as i32, 319 | ) 320 | }; 321 | 322 | if result == 0 { 323 | return Err(self.error_or_unknown()); 324 | } 325 | 326 | Ok(()) 327 | } 328 | 329 | /// Put a multidimensional array of [`i16`]. 330 | /// 331 | /// # Panics 332 | /// 333 | /// This function will panic if the product of `dimensions` is not equal to `data.len()`. 334 | /// 335 | /// *WSTP C API Documentation:* [`WSPutInteger16Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger16Array.html) 336 | pub fn put_i16_array( 337 | &mut self, 338 | data: &[i16], 339 | dimensions: &[usize], 340 | ) -> Result<(), Error> { 341 | assert_eq!( 342 | data.len(), 343 | dimensions.iter().product(), 344 | "data length does not equal product of dimensions" 345 | ); 346 | 347 | let dimensions: Vec = abi_array_dimensions(dimensions)?; 348 | 349 | let result = unsafe { 350 | sys::WSPutInteger16Array( 351 | self.raw_link, 352 | data.as_ptr(), 353 | dimensions.as_ptr(), 354 | std::ptr::null_mut(), 355 | dimensions.len() as i32, 356 | ) 357 | }; 358 | 359 | if result == 0 { 360 | return Err(self.error_or_unknown()); 361 | } 362 | 363 | Ok(()) 364 | } 365 | 366 | /// *WSTP C API Documentation:* [`WSPutInteger8Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger8Array.html) 367 | pub fn put_u8_array( 368 | &mut self, 369 | data: &[u8], 370 | dimensions: &[usize], 371 | ) -> Result<(), Error> { 372 | assert_eq!( 373 | data.len(), 374 | dimensions.iter().product(), 375 | "data length does not equal product of dimensions" 376 | ); 377 | 378 | let dimensions: Vec = abi_array_dimensions(dimensions)?; 379 | 380 | let result = unsafe { 381 | sys::WSPutInteger8Array( 382 | self.raw_link, 383 | data.as_ptr(), 384 | dimensions.as_ptr(), 385 | std::ptr::null_mut(), 386 | dimensions.len() as i32, 387 | ) 388 | }; 389 | 390 | if result == 0 { 391 | return Err(self.error_or_unknown()); 392 | } 393 | 394 | Ok(()) 395 | } 396 | 397 | //================================== 398 | // Floating-point numeric arrays 399 | //================================== 400 | 401 | /// Put a multidimensional array of [`f64`]. 402 | /// 403 | /// # Panics 404 | /// 405 | /// This function will panic if the product of `dimensions` is not equal to `data.len()`. 406 | /// 407 | /// *WSTP C API Documentation:* [`WSPutReal64Array()`](https://reference.wolfram.com/language/ref/c/WSPutReal64Array.html) 408 | pub fn put_f64_array( 409 | &mut self, 410 | data: &[f64], 411 | dimensions: &[usize], 412 | ) -> Result<(), Error> { 413 | assert_eq!( 414 | data.len(), 415 | dimensions.iter().product(), 416 | "data length does not equal product of dimensions" 417 | ); 418 | 419 | let dimensions: Vec = abi_array_dimensions(dimensions)?; 420 | 421 | let result = unsafe { 422 | sys::WSPutReal64Array( 423 | self.raw_link, 424 | data.as_ptr(), 425 | dimensions.as_ptr(), 426 | std::ptr::null_mut(), 427 | dimensions.len() as i32, 428 | ) 429 | }; 430 | 431 | if result == 0 { 432 | return Err(self.error_or_unknown()); 433 | } 434 | 435 | Ok(()) 436 | } 437 | 438 | /// Put a multidimensional array of [`f32`]. 439 | /// 440 | /// # Panics 441 | /// 442 | /// This function will panic if the product of `dimensions` is not equal to `data.len()`. 443 | /// 444 | /// *WSTP C API Documentation:* [`WSPutReal32Array()`](https://reference.wolfram.com/language/ref/c/WSPutReal32Array.html) 445 | pub fn put_f32_array( 446 | &mut self, 447 | data: &[f32], 448 | dimensions: &[usize], 449 | ) -> Result<(), Error> { 450 | assert_eq!( 451 | data.len(), 452 | dimensions.iter().product(), 453 | "data length does not equal product of dimensions" 454 | ); 455 | 456 | let dimensions: Vec = abi_array_dimensions(dimensions)?; 457 | 458 | let result = unsafe { 459 | sys::WSPutReal32Array( 460 | self.raw_link, 461 | data.as_ptr(), 462 | dimensions.as_ptr(), 463 | std::ptr::null_mut(), 464 | dimensions.len() as i32, 465 | ) 466 | }; 467 | 468 | if result == 0 { 469 | return Err(self.error_or_unknown()); 470 | } 471 | 472 | Ok(()) 473 | } 474 | } 475 | 476 | /// Convert `dimensions` to a `Vec`, which can further be converted to a 477 | /// *const i32, which is needed when calling the low-level WSTP API functions. 478 | fn abi_array_dimensions(dimensions: &[usize]) -> Result, Error> { 479 | let mut i32_dimensions = Vec::with_capacity(dimensions.len()); 480 | 481 | for (index, dim) in dimensions.iter().copied().enumerate() { 482 | match i32::try_from(dim) { 483 | Ok(val) => i32_dimensions.push(val), 484 | Err(err) => { 485 | // Overflowing the array dimension size should probably never happen in 486 | // well-behaved code, but if it does happen, there is probably some subtle 487 | // bug, so we should try to emit an error message that is as specific as 488 | // possible. 489 | return Err(Error::custom(format!( 490 | "in dimensions list {dimensions:?}, the dimension at index {index} \ 491 | (value: {dim}) overflows i32: {}; during WSTP array operation.", 492 | err 493 | ))); 494 | }, 495 | } 496 | } 497 | 498 | Ok(i32_dimensions) 499 | } 500 | -------------------------------------------------------------------------------- /wstp/src/strx.rs: -------------------------------------------------------------------------------- 1 | //! Unsized types representing encoded string data. 2 | 3 | // Note: This file is designed to be separate from the `wstp` crate. In theory, it could 4 | // (and perhaps should) be an independent crate. 5 | 6 | use std::{ 7 | char::DecodeUtf16Error, 8 | fmt::{self, Display}, 9 | mem, 10 | }; 11 | 12 | /// UTF-8 string slice. 13 | /// 14 | /// This type supports efficient conversion to and from the [`str`] type. It is provided 15 | /// primarily for consistency with the other string types. 16 | #[derive(Debug)] 17 | #[repr(transparent)] 18 | pub struct Utf8Str([u8]); 19 | 20 | /// UTF-16 string slice. 21 | #[derive(Debug)] 22 | #[repr(transparent)] 23 | pub struct Utf16Str([u16]); 24 | 25 | /// UTF-32 string slice. 26 | #[derive(Debug)] 27 | #[repr(transparent)] 28 | pub struct Utf32Str([u32]); 29 | 30 | /// UCS-2 string slice. 31 | #[derive(Debug)] 32 | #[repr(transparent)] 33 | pub struct Ucs2Str([u16]); 34 | 35 | //====================================== 36 | // Impls 37 | //====================================== 38 | 39 | //-------------------------------------- 40 | // Utf8 41 | //-------------------------------------- 42 | 43 | impl Utf8Str { 44 | /// Convert a string slice to a `Utf8`. 45 | pub fn from_str(str: &str) -> &Utf8Str { 46 | const _: () = assert!(mem::size_of::<&[u8]>() == mem::size_of::<&str>()); 47 | const _: () = assert!(mem::align_of::<&[u8]>() == mem::align_of::<&str>()); 48 | 49 | // SAFETY: Relies on representation of references to unsized data being the same 50 | // between types. 51 | unsafe { Utf8Str::from_utf8_unchecked(str.as_bytes()) } 52 | } 53 | 54 | /// Convert a slice of bytes to a `Utf8`. 55 | pub fn from_utf8(utf8: &[u8]) -> Result<&Utf8Str, ()> { 56 | let str: &str = std::str::from_utf8(utf8).map_err(|_| ())?; 57 | 58 | Ok(Utf8Str::from_str(str)) 59 | } 60 | 61 | /// Access this data as a `str`. 62 | /// 63 | /// This view is possible because the [`str`] type represents a UTF-8 encoded 64 | /// sequence of bytes, just as `Utf8` does. 65 | pub fn as_str(&self) -> &str { 66 | let Utf8Str(slice) = self; 67 | 68 | unsafe { std::str::from_utf8_unchecked(slice) } 69 | } 70 | 71 | /// Converts a slice of bytes to a `Utf8` without validating that the slice 72 | /// contains valid UTF-8 encoded data. 73 | pub unsafe fn from_utf8_unchecked(utf8: &[u8]) -> &Utf8Str { 74 | const _: () = assert!(mem::size_of::<&Utf8Str>() == mem::size_of::<&[u8]>()); 75 | const _: () = assert!(mem::align_of::<&Utf8Str>() == mem::align_of::<&[u8]>()); 76 | 77 | 78 | // SAFETY: Relies on representation of references to unsized data being the same 79 | // between types. 80 | std::mem::transmute::<&[u8], &Utf8Str>(utf8) 81 | } 82 | 83 | /// Access the elements of this UTF-8 string as a slice of `u8` elements. 84 | pub fn as_slice(&self) -> &[u8] { 85 | let Utf8Str(slice) = self; 86 | slice 87 | } 88 | } 89 | 90 | //-------------------------------------- 91 | // Utf16 92 | //-------------------------------------- 93 | 94 | impl Utf16Str { 95 | /// Convert a slice of [`u16`] to a UTF-16 string slice. 96 | pub fn from_utf16(utf16: &[u16]) -> Result<&Utf16Str, DecodeUtf16Error> { 97 | // Verify that `utf16` succcessfully decodes as valid UTF-16. 98 | for result in char::decode_utf16(utf16.iter().copied()) { 99 | let _: char = result?; 100 | } 101 | 102 | Ok(unsafe { Utf16Str::from_utf16_unchecked(utf16) }) 103 | } 104 | 105 | /// Converts a slice of bytes to a [`Utf16Str`] without validating that the slice 106 | /// contains valid UTF-16 encoded data. 107 | pub unsafe fn from_utf16_unchecked(utf16: &[u16]) -> &Utf16Str { 108 | const _: () = assert!(mem::size_of::<&Utf16Str>() == mem::size_of::<&[u16]>()); 109 | const _: () = assert!(mem::align_of::<&Utf16Str>() == mem::align_of::<&[u16]>()); 110 | 111 | // SAFETY: Relies on representation of references to unsized data being the same 112 | // between types. 113 | std::mem::transmute::<&[u16], &Utf16Str>(utf16) 114 | } 115 | 116 | /// Access the elements of this UTF-16 string as a slice of `u16` elements. 117 | pub fn as_slice(&self) -> &[u16] { 118 | let Utf16Str(slice) = self; 119 | slice 120 | } 121 | } 122 | 123 | //-------------------------------------- 124 | // Utf32 125 | //-------------------------------------- 126 | 127 | impl Utf32Str { 128 | /// Converts a slice of bytes to a [`Utf32Str`] without validating that the slice 129 | /// contains valid UTF-32 encoded data. 130 | pub unsafe fn from_utf32_unchecked(utf32: &[u32]) -> &Utf32Str { 131 | const _: () = assert!(mem::size_of::<&Utf32Str>() == mem::size_of::<&[u32]>()); 132 | const _: () = assert!(mem::align_of::<&Utf32Str>() == mem::align_of::<&[u32]>()); 133 | 134 | // SAFETY: Relies on representation of references to unsized data being the same 135 | // between types. 136 | std::mem::transmute::<&[u32], &Utf32Str>(utf32) 137 | } 138 | 139 | /// Access the elements of this UTF-32 string as a slice of `u32` elements. 140 | pub fn as_slice(&self) -> &[u32] { 141 | let Utf32Str(slice) = self; 142 | slice 143 | } 144 | } 145 | 146 | //====================================== 147 | // Display Impls 148 | //====================================== 149 | 150 | impl Display for Utf8Str { 151 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 152 | Display::fmt(self.as_str(), f) 153 | } 154 | } 155 | 156 | impl Display for Utf16Str { 157 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 158 | let Utf16Str(slice) = self; 159 | 160 | for char in char::decode_utf16(slice.into_iter().copied()) { 161 | let char: char = match char { 162 | Ok(char) => char, 163 | Err(err) => panic!("Utf16Str could not be decoded: {err}"), 164 | }; 165 | let () = Display::fmt(&char, f)?; 166 | } 167 | 168 | Ok(()) 169 | } 170 | } 171 | 172 | impl Display for Utf32Str { 173 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 174 | let Utf32Str(slice) = self; 175 | 176 | for char_u32 in slice.into_iter().copied() { 177 | let char: char = match char::from_u32(char_u32) { 178 | Some(char) => char, 179 | None => panic!("Utf32Str code point is not a valid `char`: {char_u32}"), 180 | }; 181 | let () = Display::fmt(&char, f)?; 182 | } 183 | 184 | Ok(()) 185 | } 186 | } 187 | 188 | //------------------ 189 | // Display tests 190 | //------------------ 191 | 192 | #[test] 193 | fn test_utf8_str_display() { 194 | assert_eq!( 195 | format!("{}", Utf8Str::from_str("hello 👋")), 196 | String::from("hello 👋") 197 | ); 198 | } 199 | 200 | 201 | #[test] 202 | fn test_utf16_str_display() { 203 | let utf16: Vec = "hello 👋".encode_utf16().collect(); 204 | let utf16: &Utf16Str = Utf16Str::from_utf16(&utf16).unwrap(); 205 | 206 | assert_eq!(format!("{}", utf16), String::from("hello 👋")); 207 | } 208 | 209 | #[test] 210 | fn test_utf32_str_display() { 211 | let utf32: Vec = "hello 👋" 212 | .chars() 213 | .map(|char: char| u32::from(char)) 214 | .collect(); 215 | let utf32: &Utf32Str = unsafe { Utf32Str::from_utf32_unchecked(&utf32) }; 216 | 217 | assert_eq!(format!("{}", utf32), String::from("hello 👋")); 218 | } 219 | -------------------------------------------------------------------------------- /wstp/src/wait.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | sys::{self, WSLINK}, 3 | Error, Link, 4 | }; 5 | 6 | use std::{ 7 | collections::HashMap, 8 | sync::{Mutex, OnceLock}, 9 | }; 10 | 11 | //====================================== 12 | // Wait Callbacks Global 13 | //====================================== 14 | 15 | struct ForceSend(T); 16 | 17 | unsafe impl Send for ForceSend {} 18 | 19 | type WaitCallbacksHashMap = ForceSend>; 20 | 21 | /// Hash map used to store the closure passed to [`Link::wait_with_callback()`]. 22 | /// 23 | /// This is a workaround for the fact that [WSWaitForLinkActivityWithCallback][sys::WSWaitForLinkActivityWithCallback] 24 | /// takes a function pointer as an argument, but provides no way to provide a piece of 25 | /// data to that function pointer. Both pieces of data are required to pass a Rust 26 | /// closure across the FFI boundry. Instead, we store the closure in this global static 27 | /// hash map, and look it up inside the callback trampoline function. 28 | static WAIT_CALLBACKS: OnceLock> = OnceLock::new(); 29 | 30 | fn get_wait_callbacks_lock() -> std::sync::MutexGuard<'static, WaitCallbacksHashMap> { 31 | let mutex = WAIT_CALLBACKS.get_or_init(|| Mutex::new(ForceSend(HashMap::new()))); 32 | 33 | let lock = mutex 34 | .lock() 35 | .expect("failed to acquire lock on WAIT_CALLBACKS"); 36 | 37 | lock 38 | } 39 | 40 | //====================================== 41 | // Link Implementation 42 | //====================================== 43 | 44 | impl Link { 45 | /// *WSTP C API Documentation:* [`WSWaitForLinkActivity`](https://reference.wolfram.com/language/ref/c/WSWaitForLinkActivity.html) 46 | pub fn wait(&mut self) -> Result<(), Error> { 47 | let Link { raw_link } = *self; 48 | 49 | let result: i32 = unsafe { sys::WSWaitForLinkActivity(raw_link) }; 50 | 51 | match result { 52 | sys::WSWAITSUCCESS => Ok(()), 53 | sys::WSWAITERROR => Err(self.error_or_unknown()), 54 | _ => Err(Error::custom(format!( 55 | "WSWaitForLinkActivity returned unexpected value: {}", 56 | result 57 | ))), 58 | } 59 | } 60 | 61 | /// Wait for data to become available, periodically calling a callback. 62 | /// 63 | /// `true` will be returned if data is available. `false` will be returned if the 64 | /// callback returns [`Break`][std::ops::ControlFlow::Break]. 65 | /// 66 | /// # Example 67 | /// 68 | /// ``` 69 | /// use wstp::{Link, Protocol}; 70 | /// 71 | /// let mut listener = Link::listen(Protocol::IntraProcess, "").unwrap(); 72 | /// 73 | /// let mut counter = 0; 74 | /// 75 | /// listener 76 | /// .wait_with_callback(|_: &mut Link| { 77 | /// use std::ops::ControlFlow; 78 | /// 79 | /// counter += 1; 80 | /// 81 | /// if counter < 5 { 82 | /// ControlFlow::Continue(()) 83 | /// } else { 84 | /// ControlFlow::Break(()) 85 | /// } 86 | /// }) 87 | /// .unwrap(); 88 | /// ``` 89 | /// 90 | /// # User data fields 91 | /// 92 | /// This function will temporarily replace any user data values (set using 93 | /// [Link::set_user_data]) which are associated with the current link. The user 94 | /// data values on the `&mut Link` parameter inside the callback are 95 | /// an implementation detail of this function and must not be modified. 96 | /// 97 | /// *WSTP C API Documentation:* [`WSWaitForLinkActivityWithCallback`](https://reference.wolfram.com/language/ref/c/WSWaitForLinkActivityWithCallback.html) 98 | pub fn wait_with_callback(&mut self, callback: F) -> Result 99 | where 100 | F: FnMut(&mut Link) -> std::ops::ControlFlow<()> + Send + Sync, 101 | { 102 | let Link { raw_link } = *self; 103 | 104 | let result: i32; 105 | 106 | unsafe { 107 | let boxed_closure_ptr = Box::into_raw(Box::new(callback)); 108 | 109 | { 110 | let mut lock = get_wait_callbacks_lock(); 111 | 112 | let callbacks = &mut lock.0; 113 | 114 | if callbacks.contains_key(&raw_link) { 115 | // Drop `lock` so we don't poisen it by panicking here. 116 | drop(lock); 117 | panic!("wait_with_callback: link is already being waited on with a callback"); 118 | } 119 | 120 | callbacks.insert(raw_link, boxed_closure_ptr as *mut std::ffi::c_void); 121 | } 122 | 123 | result = sys::WSWaitForLinkActivityWithCallback( 124 | raw_link, 125 | Some(link_wait_callback_trampoline::), 126 | ); 127 | 128 | { 129 | let mut lock = get_wait_callbacks_lock(); 130 | 131 | let callbacks = &mut lock.0; 132 | 133 | callbacks.remove(&raw_link); 134 | } 135 | 136 | // Drop the closure value. 137 | drop(Box::from_raw(boxed_closure_ptr)); 138 | }; 139 | 140 | match result { 141 | sys::WSWAITSUCCESS => Ok(true), 142 | sys::WSWAITCALLBACKABORTED => Ok(false), 143 | sys::WSWAITERROR => Err(self.error_or_unknown()), 144 | _ => Err(Error::custom(format!( 145 | "WSWaitForLinkActivity returned unexpected value: {}", 146 | result 147 | ))), 148 | } 149 | } 150 | } 151 | 152 | unsafe extern "C" fn link_wait_callback_trampoline( 153 | mut raw_link: sys::WSLINK, 154 | _unused_void: *mut std::ffi::c_void, 155 | ) -> i32 156 | where 157 | F: FnMut(&mut Link) -> std::ops::ControlFlow<()> + Send + Sync, 158 | { 159 | // Catch any panics which result from `expect()` or `user_closure()` to prevent 160 | // unwinding over C stack frames. 161 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { 162 | // let (raw_user_closure, _) = link.user_data(); 163 | let raw_user_closure: *mut std::ffi::c_void = { 164 | let lock = get_wait_callbacks_lock(); 165 | 166 | *lock 167 | .0 168 | .get(&raw_link) 169 | .expect("link has no associated wait closure in WAIT_CALLBACKS") 170 | }; 171 | 172 | let link: &mut Link = Link::unchecked_ref_cast_mut(&mut raw_link); 173 | 174 | let user_closure: &mut F = (raw_user_closure as *mut F) 175 | .as_mut() 176 | .expect("link wait callback is unexpectedly NULL"); 177 | 178 | user_closure(link) 179 | })); 180 | 181 | match result { 182 | Ok(std::ops::ControlFlow::Break(())) => 1, 183 | Ok(std::ops::ControlFlow::Continue(())) => 0, 184 | // If a panic occurs, stop waiting. 185 | Err(_) => 1, 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /wstp/tests/test_link_server.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | sync::Mutex, 3 | time::{Duration, Instant}, 4 | }; 5 | 6 | use wstp::{sys, Link, LinkServer, Protocol}; 7 | 8 | const PORT: u16 = 11235; 9 | 10 | /// Guard used to ensure the [`LinkServer`] tests are run sequentially, so that the 11 | /// [`PORT`] is free for each test. 12 | static MUTEX: Mutex<()> = Mutex::new(()); 13 | 14 | #[test] 15 | fn test_link_server_using_accept() { 16 | let _guard = MUTEX.lock().unwrap(); 17 | 18 | // 19 | // In a separate thread, spawn a link server to recieve connections. 20 | // 21 | 22 | let thread = std::thread::spawn(move || { 23 | let server = LinkServer::new(PORT).unwrap(); 24 | 25 | assert_eq!(server.try_port(), Ok(PORT)); 26 | // server.try_interface().unwrap(); 27 | 28 | let mut conn: Link = server 29 | .accept() 30 | .expect("failed to wait for link server connection"); 31 | 32 | conn.put_i64(0).unwrap(); 33 | conn.flush().unwrap(); 34 | 35 | assert_eq!(conn.get_string(), Ok("Done.".to_owned())); 36 | 37 | let before = Instant::now(); 38 | drop(server); 39 | let after = Instant::now(); 40 | 41 | // TODO: Reduce this value the link server close code has been improved to 42 | // cancel without a blocking wait. 43 | assert!(after.duration_since(before) < Duration::from_millis(220)); 44 | }); 45 | 46 | // Give the link server time to start listening for connections. 47 | std::thread::sleep(std::time::Duration::from_millis(100)); 48 | 49 | // 50 | // Create new UUID-based TCPIP connection to the LinkServer connection. 51 | // 52 | 53 | // Create a connection to the LinkServer, and exchange some data. 54 | let mut link = Link::connect_with_options( 55 | Protocol::TCPIP, 56 | &PORT.to_string(), 57 | &["MLUseUUIDTCPIPConnection"], 58 | ) 59 | .unwrap(); 60 | 61 | assert_eq!(link.get_i64(), Ok(0)); 62 | link.put_str("Done.").unwrap(); 63 | link.flush().unwrap(); 64 | 65 | // Stop the link server. 66 | thread.join().unwrap(); 67 | } 68 | 69 | #[test] 70 | fn test_link_server_bind_and_accept() { 71 | let _guard = MUTEX.lock().unwrap(); 72 | 73 | // 74 | // In a separate thread, spawn a link server to recieve connections. 75 | // 76 | 77 | let thread = std::thread::spawn(move || { 78 | let server = LinkServer::bind(("127.0.0.1", PORT)).unwrap(); 79 | 80 | assert_eq!(server.try_port(), Ok(PORT)); 81 | // server.try_interface().unwrap(); 82 | 83 | let mut conn: Link = server 84 | .accept() 85 | .expect("failed to wait for link server connection"); 86 | 87 | conn.put_i64(0).unwrap(); 88 | conn.flush().unwrap(); 89 | 90 | assert_eq!(conn.get_string(), Ok("Done.".to_owned())); 91 | 92 | let before = Instant::now(); 93 | drop(server); 94 | let after = Instant::now(); 95 | 96 | // TODO: Reduce this value the link server close code has been improved to 97 | // cancel without a blocking wait. 98 | assert!(after.duration_since(before) < Duration::from_millis(220)); 99 | }); 100 | 101 | // // Give the link server time to start listening for connections. 102 | std::thread::sleep(std::time::Duration::from_millis(100)); 103 | 104 | // 105 | // Create new UUID-based TCPIP connection to the LinkServer connection. 106 | // 107 | 108 | // Create a connection to the LinkServer, and exchange some data. 109 | let mut link = Link::connect_to_link_server(("127.0.0.1", PORT)).unwrap(); 110 | 111 | assert_eq!(link.activate(), Ok(())); 112 | 113 | assert_eq!(link.get_i64(), Ok(0)); 114 | link.put_str("Done.").unwrap(); 115 | link.flush().unwrap(); 116 | 117 | // Stop the link server. 118 | thread.join().unwrap(); 119 | } 120 | 121 | #[test] 122 | fn test_link_server_bind_and_incoming() { 123 | let _guard = MUTEX.lock().unwrap(); 124 | 125 | // 126 | // In a separate thread, spawn a link server to recieve connections. 127 | // 128 | 129 | let thread = std::thread::spawn(move || { 130 | let server = LinkServer::bind(("127.0.0.1", PORT)).unwrap(); 131 | 132 | assert_eq!(server.try_port(), Ok(PORT)); 133 | // server.try_interface().unwrap(); 134 | 135 | for conn in server.incoming() { 136 | let mut conn = conn.unwrap(); 137 | 138 | conn.put_i64(0).unwrap(); 139 | conn.flush().unwrap(); 140 | 141 | assert_eq!(conn.get_string(), Ok("Done.".to_owned())); 142 | 143 | // Only handle one connection. 144 | break; 145 | } 146 | }); 147 | 148 | // Give the link server time to start listening for connections. 149 | std::thread::sleep(std::time::Duration::from_millis(100)); 150 | 151 | // 152 | // Create new UUID-based TCPIP connection to the LinkServer connection. 153 | // 154 | 155 | // Create a connection to the LinkServer, and exchange some data. 156 | let mut link = Link::connect_to_link_server(("127.0.0.1", PORT)).unwrap(); 157 | 158 | assert_eq!(link.get_i64(), Ok(0)); 159 | link.put_str("Done.").unwrap(); 160 | link.flush().unwrap(); 161 | 162 | // Stop the link server. 163 | thread.join().unwrap(); 164 | } 165 | 166 | #[test] 167 | fn test_link_server_using_callback() { 168 | let _guard = MUTEX.lock().unwrap(); 169 | 170 | let server = LinkServer::new_with_callback(PORT, |link| { 171 | println!("Got link: {:?}", link); 172 | }) 173 | .unwrap(); 174 | 175 | // Test that the port and interface getters work as expected. 176 | assert_eq!(server.try_port(), Ok(PORT)); 177 | // server.try_interface().unwrap(); 178 | } 179 | 180 | #[test] 181 | fn test_name_taken_error() { 182 | let _guard = MUTEX.lock().unwrap(); 183 | 184 | let _a = LinkServer::new_with_callback(PORT, |_| {}).unwrap(); 185 | let b = LinkServer::new_with_callback(PORT, |_| {}) 186 | .expect_err("multiple link servers bound to same port??"); 187 | 188 | assert_eq!(b.code(), Some(sys::MLENAMETAKEN)); 189 | } 190 | -------------------------------------------------------------------------------- /wstp/tests/test_links.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Mutex; 2 | 3 | use wstp::{sys, Link, Protocol, UrgentMessage}; 4 | 5 | /// Guard used to ensure the tests which bind to a port are run sequentially, so that 6 | /// port is free for each test. 7 | static MUTEX: Mutex<()> = Mutex::new(()); 8 | 9 | fn random_link_name() -> String { 10 | use rand::{distributions::Alphanumeric, Rng}; 11 | 12 | rand::thread_rng() 13 | .sample_iter(&Alphanumeric) 14 | .take(7) 15 | .map(char::from) 16 | .collect() 17 | } 18 | 19 | // Helper method to check that data can successfully be sent from `link_a` to `link_b`. 20 | // 21 | // This tests reading and writing from both ends of the link. 22 | fn check_send_data_across_link(mut link_a: Link, mut link_b: Link) { 23 | let thread_a = std::thread::spawn(move || { 24 | link_a.activate().expect("failed to activate Listener side"); 25 | 26 | // Write an integer. 27 | link_a.put_i64(5).unwrap(); 28 | link_a.flush().unwrap(); 29 | 30 | // Read a f64 written by the other side. 31 | let got = link_a.get_f64().unwrap(); 32 | assert_eq!(got, 3.1415); 33 | 34 | { 35 | link_a.put_raw_type(i32::from(sys::WSTKFUNC)).unwrap(); 36 | link_a.put_arg_count(2).unwrap(); 37 | link_a.put_symbol("Sin").unwrap(); 38 | link_a.put_f64(1.0).unwrap(); 39 | 40 | link_a.flush().unwrap() 41 | } 42 | 43 | link_a 44 | }); 45 | 46 | let thread_b = std::thread::spawn(move || { 47 | link_b 48 | .activate() 49 | .expect("failed to activate Connector side"); 50 | 51 | let got = link_b.get_i64().unwrap(); 52 | assert_eq!(got, 5); 53 | 54 | link_b.put_f64(3.1415).unwrap(); 55 | link_b.flush().unwrap(); 56 | 57 | { 58 | assert_eq!(link_b.get_raw_type(), Ok(i32::from(sys::WSTKFUNC))); 59 | assert_eq!(link_b.get_arg_count(), Ok(2)); 60 | assert!(link_b.get_symbol_ref().unwrap().as_str() == "Sin"); 61 | assert_eq!(link_b.get_f64(), Ok(1.0)) 62 | } 63 | 64 | link_b 65 | }); 66 | 67 | let _link_a = thread_a.join().unwrap(); 68 | let _link_b = thread_b.join().unwrap(); 69 | } 70 | 71 | //====================================== 72 | // IntraProcess 73 | //====================================== 74 | 75 | #[test] 76 | fn test_intra_process_links() { 77 | // let name: String = dbg!(random_link_name()); 78 | 79 | let listener = Link::listen(Protocol::IntraProcess, "").unwrap(); 80 | 81 | // FIXME: IntraProcess-mode links ignore the `-linkname` device parameter and instead 82 | // generate their own random string to use as a name. So we have to create the 83 | // listener device first and then ask for it's name. 84 | let name = listener.link_name(); 85 | 86 | let connector = Link::connect(Protocol::IntraProcess, &name).unwrap(); 87 | 88 | check_send_data_across_link(listener, connector); 89 | } 90 | 91 | /// FIXME: IntraProcess-mode links ignore the `-linkname` device parameter and instead 92 | /// generate their own random string to use as a name. So we have to create the 93 | /// listener device first and then ask for it's name. 94 | #[test] 95 | fn test_bug_intra_process_device_ignored_linkname() { 96 | let name: String = random_link_name(); 97 | let listener = Link::listen(Protocol::IntraProcess, &name).unwrap(); 98 | assert!(name != listener.link_name()) 99 | } 100 | 101 | //====================================== 102 | // SharedMemory 103 | //====================================== 104 | 105 | /// Test the error code returned by the `SharedMemory` protocol implementation when sync 106 | /// objects with a particular name already exist. 107 | #[test] 108 | fn test_shared_memory_name_taken_error() { 109 | const NAME: &str = "should-be-taken-2"; 110 | 111 | let _a = Link::listen(Protocol::SharedMemory, NAME.into()).unwrap(); 112 | let b = Link::listen(Protocol::SharedMemory, NAME.into()); 113 | 114 | assert_eq!(b.unwrap_err().code().unwrap(), sys::MLENAMETAKEN); 115 | } 116 | 117 | #[test] 118 | fn test_link_listen_does_not_block_for_connection() { 119 | // This test is successful by not hanging. 120 | let _link = Link::listen(Protocol::SharedMemory, "".into()).unwrap(); 121 | 122 | // This *would* hang unless and until a Link::connect(..) is done: 123 | // link.activate() 124 | } 125 | 126 | // Test that two SharedMemory links can get and put between each other on a 127 | // single thread. 128 | #[test] 129 | fn test_single_thread_duplex_links() { 130 | let mut a = Link::listen(Protocol::SharedMemory, "").unwrap(); 131 | let mut b = Link::connect(Protocol::SharedMemory, &a.link_name()).unwrap(); 132 | 133 | // Activation still requires a second thread. 134 | let a = std::thread::spawn(move || { 135 | a.activate().unwrap(); 136 | a 137 | }); 138 | 139 | let () = b.activate().unwrap(); 140 | 141 | let mut a = a.join().unwrap(); 142 | 143 | a.put_str("from a to b").unwrap(); 144 | a.flush().unwrap(); 145 | 146 | b.put_str("from b to a").unwrap(); 147 | b.flush().unwrap(); 148 | 149 | assert_eq!(a.get_string().unwrap(), "from b to a"); 150 | assert_eq!(b.get_string().unwrap(), "from a to b"); 151 | } 152 | 153 | //====================================== 154 | // TCPIP 155 | //====================================== 156 | 157 | #[test] 158 | fn test_tcpip_links() { 159 | let _guard = MUTEX.lock().unwrap(); 160 | 161 | let listener = Link::listen(Protocol::TCPIP, "8080").unwrap(); 162 | let connector = Link::connect(Protocol::TCPIP, "8080").unwrap(); 163 | 164 | check_send_data_across_link(listener, connector); 165 | } 166 | 167 | /// Test using the '@' character in the link name, which is parsed specially by the TCPIP 168 | /// protocol. 169 | #[test] 170 | fn test_tcpip_links_host_syntax() { 171 | let _guard = MUTEX.lock().unwrap(); 172 | 173 | { 174 | let listener = Link::listen(Protocol::TCPIP, "8080@localhost").unwrap(); 175 | let connector = Link::connect(Protocol::TCPIP, "8080@localhost").unwrap(); 176 | 177 | check_send_data_across_link(listener, connector); 178 | } 179 | 180 | // IPv4 localhost address 181 | { 182 | let listener = Link::listen(Protocol::TCPIP, "8080@127.0.0.1").unwrap(); 183 | let connector = Link::connect(Protocol::TCPIP, "8080@127.0.0.1").unwrap(); 184 | 185 | check_send_data_across_link(listener, connector); 186 | } 187 | 188 | // IPv6 localhost address 189 | { 190 | let listener = Link::listen(Protocol::TCPIP, "8080@::1").unwrap(); 191 | let connector = Link::connect(Protocol::TCPIP, "8080@::1").unwrap(); 192 | 193 | check_send_data_across_link(listener, connector); 194 | } 195 | } 196 | 197 | #[test] 198 | fn test_tcpip_specific_link_creation_methods() { 199 | let _guard = MUTEX.lock().unwrap(); 200 | 201 | let listener = Link::tcpip_listen("localhost:8080").unwrap(); 202 | let connector = Link::tcpip_connect("localhost:8080").unwrap(); 203 | 204 | check_send_data_across_link(listener, connector); 205 | } 206 | 207 | #[test] 208 | fn test_bug_tcpip_listen_returns_unknown() { 209 | assert_eq!( 210 | Link::listen(Protocol::TCPIP, "8080@badhost") 211 | .unwrap_err() 212 | .code(), 213 | Some(sys::WSEUNKNOWN) 214 | ); 215 | } 216 | 217 | //====================================== 218 | // Misc. 219 | //====================================== 220 | 221 | //------------------------------------- 222 | // Test wait() and wait_with_callback() 223 | //------------------------------------- 224 | 225 | #[test] 226 | fn test_link_wait_with_callback() { 227 | let mut listener = Link::listen(Protocol::IntraProcess, "").unwrap(); 228 | 229 | let mut counter = 0; 230 | 231 | listener 232 | .wait_with_callback(|_: &mut Link| { 233 | counter += 1; 234 | 235 | if counter < 5 { 236 | std::ops::ControlFlow::Continue(()) 237 | } else { 238 | std::ops::ControlFlow::Break(()) 239 | } 240 | }) 241 | .unwrap(); 242 | 243 | assert_eq!(counter, 5); 244 | } 245 | 246 | /// Test that `wait_with_callback()` will stop waiting if a panic occurs. 247 | #[test] 248 | fn test_link_wait_with_callback_panic() { 249 | let mut listener = Link::listen(Protocol::IntraProcess, "").unwrap(); 250 | 251 | let mut counter = 0; 252 | 253 | listener 254 | .wait_with_callback(|_: &mut Link| { 255 | counter += 1; 256 | 257 | panic!("STOP"); 258 | }) 259 | .unwrap(); 260 | 261 | assert_eq!(counter, 1); 262 | } 263 | 264 | #[test] 265 | fn test_link_wait_with_callback_drops_closure() { 266 | use std::sync::Arc; 267 | 268 | let mut listener = Link::listen(Protocol::IntraProcess, "").unwrap(); 269 | 270 | let data = Arc::new(()); 271 | let inner: Arc<()> = data.clone(); 272 | 273 | assert_eq!(Arc::strong_count(&data), 2); 274 | 275 | // `inner` is moved into `closure`. `inner` will only be dropped if `closure` is. This 276 | // allows us to indirectly verify that `closure` itself is dropped, even if it panics 277 | // during the wait. (At a lower level, this is testing an implementation detail of 278 | // wait_with_callback(): that Box::from_raw(boxed_closure_ptr) is called as expected.) 279 | let closure = move |_: &mut Link| { 280 | assert_eq!(Arc::strong_count(&inner), 2); 281 | 282 | panic!() 283 | }; 284 | 285 | listener.wait_with_callback(closure).unwrap(); 286 | 287 | assert_eq!(Arc::strong_count(&data), 1); 288 | } 289 | 290 | #[test] 291 | fn test_link_wait_with_callback_nested() { 292 | let mut listener = Link::listen(Protocol::IntraProcess, "").unwrap(); 293 | 294 | let mut failed = false; 295 | 296 | listener 297 | .wait_with_callback(|this: &mut Link| { 298 | // We're expecting this to panic. 299 | let _ = this.wait_with_callback(|_| panic!()); 300 | 301 | failed = true; 302 | std::ops::ControlFlow::Break(()) 303 | }) 304 | .unwrap(); 305 | 306 | assert!(!failed); 307 | } 308 | 309 | //----------------------------- 310 | // Test transfering expressions 311 | //----------------------------- 312 | 313 | #[test] 314 | fn test_loopback_transfer_expression() { 315 | let mut a = Link::new_loopback().unwrap(); 316 | let mut b = Link::new_loopback().unwrap(); 317 | 318 | a.put_i64(5).unwrap(); 319 | 320 | a.transfer_expr_to(&mut b).unwrap(); 321 | 322 | assert_eq!(b.get_i64().unwrap(), 5); 323 | } 324 | 325 | #[test] 326 | fn test_get_expr_missing_symbol_context_error() { 327 | let mut link = Link::new_loopback().unwrap(); 328 | 329 | link.put_symbol("List").unwrap(); 330 | 331 | let err: wstp::Error = link.get_expr().unwrap_err(); 332 | 333 | assert!(err.code().is_none()); 334 | assert_eq!( 335 | err.to_string(), 336 | "WSTP error: symbol name 'List' has no context" 337 | ); 338 | } 339 | 340 | //-------------------------------- 341 | // Test getting and putting arrays 342 | //-------------------------------- 343 | 344 | #[test] 345 | fn test_roundtrip_i64_array() { 346 | let mut link = Link::new_loopback().unwrap(); 347 | 348 | link.put_i64_array(&[1, 2, 3, 4], &[2, 2]).unwrap(); 349 | 350 | let out = link.get_i64_array().unwrap(); 351 | 352 | assert_eq!(out.data().len(), 4); 353 | assert_eq!(out.dimensions(), &[2, 2]); 354 | } 355 | 356 | #[test] 357 | fn test_roundtrip_f64_array() { 358 | let mut link = Link::new_loopback().unwrap(); 359 | 360 | link.put_f64_array(&[3.141, 1.618, 2.718], &[3]).unwrap(); 361 | 362 | let out = link.get_f64_array().unwrap(); 363 | 364 | assert_eq!(out.data().len(), 3); 365 | assert_eq!(out.data(), &[3.141, 1.618, 2.718]); 366 | assert_eq!(out.dimensions(), &[3]); 367 | } 368 | 369 | // Test that getting an f64 array as an i64 array performs rounding. 370 | #[test] 371 | fn test_mismatched_array_type_rounding() { 372 | let mut link = Link::new_loopback().unwrap(); 373 | 374 | link.put_f64_array(&[3.141, 1.618, 2.718], &[3]).unwrap(); 375 | 376 | let out = link.get_i64_array().unwrap(); 377 | 378 | assert_eq!(out.data(), &[3, 2, 3]); 379 | } 380 | 381 | // Test that reading an f64 array as a scalar i64 results in an get sequence error. 382 | #[test] 383 | fn test_mismatched_type_error() { 384 | let mut link = Link::new_loopback().unwrap(); 385 | 386 | link.put_f64_array(&[3.141, 1.618, 2.718], &[3]).unwrap(); 387 | 388 | assert_eq!( 389 | link.get_i64().map_err(|err| err.code()), 390 | Err(Some(sys::MLEGSEQ)) 391 | ); 392 | } 393 | 394 | //-------------------------------------- 395 | // Test sending urgent messages 396 | //-------------------------------------- 397 | 398 | #[test] 399 | fn test_urgent_messages() { 400 | let (mut a, mut b) = wstp::channel(Protocol::SharedMemory).unwrap(); 401 | 402 | a.put_message(UrgentMessage::ABORT).unwrap(); 403 | 404 | assert_eq!(b.get_message(), Some(UrgentMessage::ABORT)); 405 | 406 | b.put_message(UrgentMessage { 407 | code: 500, 408 | param: 123, 409 | }) 410 | .unwrap(); 411 | 412 | assert_eq!( 413 | a.get_message(), 414 | Some(UrgentMessage::new_with_param(500, 123)) 415 | ); 416 | } 417 | -------------------------------------------------------------------------------- /wstp/tests/test_loopback_links.rs: -------------------------------------------------------------------------------- 1 | use wolfram_expr::{Expr, Symbol}; 2 | use wstp::{sys, Link, LinkStr, Protocol, Token, TokenType}; 3 | 4 | fn check_loopback_roundtrip(expr: Expr) { 5 | let mut link = Link::new_loopback().expect("failed to create Loopback link"); 6 | 7 | link.put_expr(&expr).expect("failed to write expr"); 8 | 9 | let read = link.get_expr().expect("failed to read expr"); 10 | 11 | assert_eq!(expr, read); 12 | } 13 | 14 | #[test] 15 | fn test_loopback_link() { 16 | check_loopback_roundtrip(Expr::from(5i64)); 17 | check_loopback_roundtrip(Expr::normal( 18 | Expr::symbol(Symbol::new("System`List")), 19 | vec![Expr::from(1i64)], 20 | )); 21 | check_loopback_roundtrip(Expr::normal( 22 | Expr::symbol(Symbol::new("Global`MyHead")), 23 | vec![Expr::from(1i16)], 24 | )); 25 | } 26 | 27 | #[test] 28 | fn test_loopback_get_put_atoms() { 29 | let mut link = Link::new_loopback().expect("failed to create Loopback link"); 30 | 31 | { 32 | // Test the `Link::get_string_ref()` method. 33 | link.put_expr(&Expr::string("Hello!")).unwrap(); 34 | let link_str: LinkStr = link.get_string_ref().unwrap(); 35 | assert_eq!(link_str.as_str(), "Hello!") 36 | } 37 | 38 | { 39 | // Test the `Link::get_symbol_ref()` method. 40 | link.put_expr(&Expr::symbol(Symbol::new("System`Plot"))) 41 | .unwrap(); 42 | let link_str: LinkStr = link.get_symbol_ref().unwrap(); 43 | assert_eq!(link_str.as_str(), "System`Plot") 44 | } 45 | } 46 | 47 | #[test] 48 | fn test_is_loopback() { 49 | let link = Link::new_loopback().unwrap(); 50 | assert!(link.is_loopback()); 51 | 52 | let link = Link::listen(Protocol::IntraProcess, "name-test").unwrap(); 53 | assert!(!link.is_loopback()); 54 | } 55 | 56 | #[test] 57 | fn test_loopback_idempotence_of_get_arg_count() { 58 | let mut link = Link::new_loopback().unwrap(); 59 | 60 | link.put_function("List", 1).unwrap(); 61 | link.put_i64(10).unwrap(); 62 | 63 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKFUNC.into())); 64 | 65 | // Test that it doesn't matter how many times we call WSArgCount(). 66 | for _ in 0..5 { 67 | assert_eq!(link.get_arg_count(), Ok(1)); 68 | } 69 | 70 | assert_eq!( 71 | link.get_string_ref().map(|s| s.as_str().to_owned()), 72 | Ok(String::from("List")) 73 | ); 74 | } 75 | 76 | #[test] 77 | fn test_get_arg_count_must_be_called_at_least_once() { 78 | let mut link = Link::new_loopback().unwrap(); 79 | 80 | link.put_function("List", 1).unwrap(); 81 | link.put_i64(10).unwrap(); 82 | 83 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKFUNC.into())); 84 | 85 | // This call is required for this code to be correct: 86 | // assert_eq!(link.get_arg_count(), Ok(1)); 87 | 88 | // Expect that trying to get the head fails. Even though we know what the arg count 89 | // should be, we're still required to query it using WSArgCount(). 90 | assert_eq!( 91 | link.get_string_ref().unwrap_err().code(), 92 | Some(sys::WSEGSEQ) 93 | ); 94 | } 95 | 96 | #[test] 97 | fn test_loopback_basic_put_and_get_list() { 98 | let mut link = Link::new_loopback().unwrap(); 99 | 100 | link.put_function("List", 1).unwrap(); 101 | link.put_i64(10).unwrap(); 102 | 103 | 104 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKFUNC.into())); 105 | assert_eq!(link.get_arg_count(), Ok(1)); 106 | assert_eq!( 107 | link.get_string_ref().map(|s| s.as_str().to_owned()), 108 | Ok(String::from("List")) 109 | ); 110 | assert_eq!(link.get_i64(), Ok(10)); 111 | } 112 | 113 | #[test] 114 | fn test_loopback_get_next() { 115 | let mut link = Link::new_loopback().unwrap(); 116 | 117 | link.put_function("List", 1).unwrap(); 118 | link.put_i64(10).unwrap(); 119 | 120 | assert!(link.is_ready()); 121 | 122 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKFUNC.into())); 123 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKSYM.into())); 124 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKINT.into())); 125 | 126 | assert_eq!(link.raw_get_next().unwrap_err().code(), Some(sys::WSEABORT)); 127 | 128 | assert!(!link.is_ready()); 129 | } 130 | 131 | #[test] 132 | fn test_loopback_new_packet() { 133 | let mut link = Link::new_loopback().unwrap(); 134 | 135 | link.put_function("List", 1).unwrap(); 136 | link.put_i64(10).unwrap(); 137 | 138 | assert!(link.is_ready()); 139 | 140 | assert_eq!(link.raw_get_next(), Ok(sys::WSTKFUNC.into())); 141 | assert_eq!(link.new_packet(), Ok(())); 142 | 143 | assert_eq!(link.raw_get_next().unwrap_err().code(), Some(sys::WSEABORT)); 144 | 145 | assert!(!link.is_ready()); 146 | } 147 | 148 | #[test] 149 | fn test_loopback_test_head() { 150 | let mut link = Link::new_loopback().unwrap(); 151 | 152 | link.put_function("List", 1).unwrap(); 153 | link.put_i64(10).unwrap(); 154 | 155 | assert_eq!(link.test_head("List"), Ok(1)); 156 | } 157 | 158 | #[test] 159 | fn test_loopback_test_head_error() { 160 | let mut link = Link::new_loopback().unwrap(); 161 | 162 | link.put_function("List", 1).unwrap(); 163 | link.put_i64(10).unwrap(); 164 | 165 | assert_eq!( 166 | link.test_head("Plot").unwrap_err().code().unwrap(), 167 | sys::WSEGSEQ 168 | ); 169 | } 170 | 171 | #[test] 172 | fn test_loopback_transfer_simple() { 173 | let mut link = Link::new_loopback().unwrap(); 174 | link.put_str("hello").unwrap(); 175 | 176 | let mut new = Link::new_loopback().unwrap(); 177 | link.transfer_to_end_of_loopback_link(&mut new).unwrap(); 178 | 179 | assert_eq!(new.get_string_ref().unwrap().as_str(), "hello"); 180 | } 181 | 182 | #[test] 183 | fn test_loopback_transfer_list() { 184 | let mut link = Link::new_loopback().unwrap(); 185 | link.put_function("System`List", 3).unwrap(); 186 | link.put_i64(5).unwrap(); 187 | link.put_str("second").unwrap(); 188 | link.put_symbol("Global`foo").unwrap(); 189 | 190 | let mut new = Link::new_loopback().unwrap(); 191 | link.transfer_to_end_of_loopback_link(&mut new).unwrap(); 192 | 193 | assert_eq!( 194 | new.get_expr().unwrap().to_string(), 195 | "System`List[5, \"second\", Global`foo]" 196 | ); 197 | } 198 | 199 | #[test] 200 | #[rustfmt::skip] 201 | fn test_loopback_get_tokens() { 202 | // Put {5, "second", foo} 203 | let mut link = Link::new_loopback().unwrap(); 204 | link.put_function("System`List", 3).unwrap(); 205 | link.put_i64(5).unwrap(); 206 | link.put_str("second").unwrap(); 207 | link.put_symbol("Global`foo").unwrap(); 208 | 209 | assert!(matches!(link.get_token().unwrap(), Token::Function { length: 3 })); 210 | assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "System`List")); 211 | assert!(matches!(link.get_token().unwrap(), Token::Integer(5))); 212 | assert!(matches!(link.get_token().unwrap(), Token::String(s) if s.as_str() == "second")); 213 | assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "Global`foo")); 214 | } 215 | 216 | #[test] 217 | #[rustfmt::skip] 218 | fn test_loopback_get_token_type_is_idempotent() { 219 | // Put {5, "second", foo} 220 | let mut link = Link::new_loopback().unwrap(); 221 | link.put_function("System`List", 3).unwrap(); 222 | link.put_i64(5).unwrap(); 223 | link.put_str("second").unwrap(); 224 | link.put_symbol("Global`foo").unwrap(); 225 | 226 | // Calling get_type(), even multiple times in a row, should not advance the link at 227 | // all. 228 | assert_eq!(link.get_type().unwrap(), TokenType::Function); 229 | assert_eq!(link.get_type().unwrap(), TokenType::Function); 230 | assert_eq!(link.get_type().unwrap(), TokenType::Function); 231 | 232 | assert!(matches!(link.get_token().unwrap(), Token::Function { length: 3 })); 233 | 234 | assert_eq!(link.get_type().unwrap(), TokenType::Symbol); 235 | assert_eq!(link.get_type().unwrap(), TokenType::Symbol); 236 | assert_eq!(link.get_type().unwrap(), TokenType::Symbol); 237 | 238 | assert!(matches!(link.get_token().unwrap(), Token::Symbol(s) if s.as_str() == "System`List")); 239 | 240 | assert_eq!(link.get_type().unwrap(), TokenType::Integer); 241 | assert_eq!(link.get_type().unwrap(), TokenType::Integer); 242 | assert_eq!(link.get_type().unwrap(), TokenType::Integer); 243 | 244 | assert!(matches!(link.get_token().unwrap(), Token::Integer(5))); 245 | } 246 | -------------------------------------------------------------------------------- /wstp/tests/test_shutdown.rs: -------------------------------------------------------------------------------- 1 | use wstp::Link; 2 | 3 | // Test that trying to create a link after shutdown() is called causes an error 4 | // to be returned, instead of a panic. 5 | #[test] 6 | fn test_shutdown() { 7 | unsafe { 8 | wstp::shutdown().unwrap(); 9 | } 10 | 11 | assert_eq!( 12 | Link::new_loopback().unwrap_err().to_string(), 13 | "WSTP error: wstp-rs: STDENV has been shutdown. No more links can be created." 14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtask" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | clap = { version = "4.3.3", features = ["derive"] } 10 | bindgen = "^0.65.1" 11 | wolfram-app-discovery = "0.4.8" 12 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | //! `cargo xtask` helper commands for the wstp-rs project. 2 | //! 3 | //! This crate follows the [`cargo xtask`](https://github.com/matklad/cargo-xtask) 4 | //! convention. 5 | 6 | use std::path::{Path, PathBuf}; 7 | 8 | use clap::{Parser, Subcommand}; 9 | 10 | use wolfram_app_discovery::{SystemID, WolframApp, WolframVersion, WstpSdk}; 11 | 12 | const FILENAME: &str = "WSTP_bindings.rs"; 13 | 14 | #[derive(Parser)] 15 | struct Cli { 16 | #[command(subcommand)] 17 | command: Commands, 18 | } 19 | 20 | #[derive(Subcommand)] 21 | enum Commands { 22 | /// Generate and save WSTP bindings automatically for the current platform. 23 | GenBindings { 24 | /// Target to generate bindings for. 25 | #[arg(long)] 26 | target: Option, 27 | }, 28 | /// Generate and save WSTP bindings from the specified WSTP SDK. 29 | GenBindingsFrom { 30 | sdk_path: PathBuf, 31 | 32 | /// Target to generate bindings for. 33 | #[arg(long)] 34 | target: String, 35 | 36 | #[arg(long, value_delimiter = '.')] 37 | wolfram_version: Vec, 38 | }, 39 | } 40 | 41 | //====================================== 42 | // Main 43 | //====================================== 44 | 45 | fn main() { 46 | let Cli { command } = Cli::parse(); 47 | 48 | let target = match command { 49 | Commands::GenBindings { target } => target, 50 | Commands::GenBindingsFrom { 51 | sdk_path, 52 | target, 53 | wolfram_version, 54 | } => { 55 | let wolfram_version = { 56 | let [major, minor, patch]: [u32; 3] = 57 | wolfram_version.try_into().expect("--wolfram-version requires 3 components. E.g. --wolfram-version=13.0.1"); 58 | WolframVersion::new(major, minor, patch) 59 | }; 60 | 61 | let sdk = WstpSdk::try_from_directory(sdk_path.clone()) 62 | .map_err(|err| { 63 | format!( 64 | "unrecognized WSTP SDK at path '{}': {err}", 65 | sdk_path.display() 66 | ) 67 | }) 68 | .unwrap(); 69 | 70 | // Path to the WSTP SDK 'wstp.h` header file. 71 | let wstp_h = sdk.wstp_c_header_path(); 72 | 73 | generate_bindings(&wolfram_version, &wstp_h, &target); 74 | 75 | return; 76 | }, 77 | }; 78 | 79 | let app = WolframApp::try_default().expect("unable to locate WolframApp"); 80 | 81 | let wolfram_version: WolframVersion = 82 | app.wolfram_version().expect("unable to get WolframVersion"); 83 | 84 | let wstp_sdks: Vec = app 85 | .wstp_sdks() 86 | .expect("unable to locate WSTP SDKs in app") 87 | .into_iter() 88 | .filter_map(|entry| entry.ok()) 89 | .collect(); 90 | 91 | let targets: Vec<&str> = match target { 92 | Some(ref target) => vec![target.as_str()], 93 | None => determine_targets().to_vec(), 94 | }; 95 | 96 | println!("Generating bindings for: {targets:?}"); 97 | 98 | for target in targets { 99 | let target_system_id = SystemID::try_from_rust_target(target).unwrap(); 100 | 101 | // Find the WSTP SDK suitable for the specified Rust target. 102 | let sdk: Option<&WstpSdk> = wstp_sdks 103 | .iter() 104 | .find(|sdk| sdk.system_id() == target_system_id); 105 | 106 | let Some(sdk) = sdk else { 107 | println!("WARNING: App does not provide WSTP SDK for {target_system_id} (Rust target: {target})."); 108 | continue 109 | }; 110 | 111 | // Path to the WSTP SDK 'wstp.h` header file. 112 | let wstp_h = sdk.wstp_c_header_path(); 113 | 114 | generate_bindings(&wolfram_version, &wstp_h, target); 115 | } 116 | } 117 | 118 | /// Generte bindings for multiple targets at once, based on the current 119 | /// operating system. 120 | fn determine_targets() -> &'static [&'static str] { 121 | if cfg!(target_os = "macos") { 122 | &["x86_64-apple-darwin", "aarch64-apple-darwin"] 123 | } else if cfg!(target_os = "windows") { 124 | &["x86_64-pc-windows-msvc"] 125 | } else if cfg!(target_os = "linux") { 126 | &["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] 127 | } else { 128 | panic!("unsupported operating system for determining LibraryLink bindings target architecture") 129 | } 130 | } 131 | 132 | fn generate_bindings(wolfram_version: &WolframVersion, wstp_h: &Path, target: &str) { 133 | assert!(wstp_h.file_name().unwrap() == "wstp.h"); 134 | 135 | let target_system_id: SystemID = SystemID::try_from_rust_target(target) 136 | .expect("Rust target doesn't map to a known SystemID"); 137 | 138 | let bindings = bindgen::Builder::default() 139 | .header(wstp_h.display().to_string()) 140 | .generate_comments(true) 141 | // Force the WSE* error macro definitions to be interpreted as signed constants. 142 | // WSTP uses `int` as it's error type, so this is necessary to avoid having to 143 | // scatter `as i32` everywhere. 144 | .default_macro_constant_type(bindgen::MacroTypeVariation::Signed) 145 | .clang_args(&["-target", target]) 146 | .generate() 147 | .expect("unable to generate Rust bindings to WSTP using bindgen"); 148 | 149 | // OUT_DIR is set by cargo before running this build.rs file. 150 | let out_path = repo_root_dir() 151 | .join("wstp-sys") 152 | .join("generated") 153 | .join(&wolfram_version.to_string()) 154 | .join(target_system_id.as_str()) 155 | .join(FILENAME); 156 | 157 | std::fs::create_dir_all(out_path.parent().unwrap()) 158 | .expect("failed to create parent directories for generating bindings file"); 159 | 160 | bindings 161 | .write_to_file(&out_path) 162 | .expect("failed to write Rust bindings with IO error"); 163 | 164 | println!( 165 | " 166 | ==== GENERATED BINDINGS ==== 167 | 168 | wstp.h location: {} 169 | 170 | $SystemID: {} 171 | 172 | $VersionNumber / $ReleaseNumber: {} 173 | 174 | Output: {} 175 | 176 | ============================ 177 | ", 178 | wstp_h.display(), 179 | target_system_id, 180 | wolfram_version, 181 | out_path.strip_prefix(repo_root_dir()).unwrap().display() 182 | ) 183 | } 184 | 185 | fn repo_root_dir() -> PathBuf { 186 | let xtask_crate = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); 187 | assert!(xtask_crate.file_name().unwrap() == "xtask"); 188 | xtask_crate.parent().unwrap().to_path_buf() 189 | } 190 | --------------------------------------------------------------------------------