wstp 0.6.0-alpha.2

Bindings to the Wolfram Symbolic Transfer Protocol (WSTP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::convert::TryFrom;
use std::ffi::CString;

use crate::{
    sys::{
        self, WSPutArgCount, WSPutInteger16, WSPutInteger32, WSPutInteger64,
        WSPutInteger8, WSPutReal32, WSPutReal64, WSPutUTF16String, WSPutUTF32String,
        WSPutUTF8String, WSPutUTF8Symbol,
    },
    Error, Link,
};

impl Link {
    /// TODO: Augment this function with a `put_type()` method which takes a
    ///       (non-exhaustive) enum value.
    ///
    /// *WSTP C API Documentation:* [`WSPutType()`](https://reference.wolfram.com/language/ref/c/WSPutType.html)
    pub fn put_raw_type(&mut self, type_: i32) -> Result<(), Error> {
        if unsafe { sys::WSPutType(self.raw_link, type_) } == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSEndPacket()`](https://reference.wolfram.com/language/ref/c/WSEndPacket.html)
    pub fn end_packet(&mut self) -> Result<(), Error> {
        if unsafe { sys::WSEndPacket(self.raw_link) } == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    //==================================
    // Atoms
    //==================================

    /// *WSTP C API Documentation:* [`WSPutUTF8String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF8String.html)
    pub fn put_str(&mut self, string: &str) -> Result<(), Error> {
        let len = i32::try_from(string.as_bytes().len()).expect("usize overflows i32");
        let ptr = string.as_ptr() as *const u8;

        if unsafe { WSPutUTF8String(self.raw_link, ptr, len) } == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutUTF8Symbol()`](https://reference.wolfram.com/language/ref/c/WSPutUTF8Symbol.html)
    pub fn put_symbol(&mut self, symbol: &str) -> Result<(), Error> {
        // FIXME:
        //     Is this extra allocation necessary?WSPutUTF8Symbol doesn't seem to require
        //     that the data contains a NULL terminator, so we should be able to just
        //     pass a pointer to `symbol`'s data.
        let c_string = CString::new(symbol).unwrap();

        let len = i32::try_from(c_string.as_bytes().len()).expect("usize overflows i32");
        let ptr = c_string.as_ptr() as *const u8;

        if unsafe { WSPutUTF8Symbol(self.raw_link, ptr, len) } == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    //==================================
    // Strings
    //==================================

    /// *WSTP C API Documentation:* [`WSPutUTF8String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF8String.html)
    ///
    /// This function will return a WSTP error if `utf8` is not a valid UTF-8 encoded
    /// string.
    pub fn put_utf8_str(&mut self, utf8: &[u8]) -> Result<(), Error> {
        let len = i32::try_from(utf8.len()).expect("usize overflows i32");

        if unsafe { WSPutUTF8String(self.raw_link, utf8.as_ptr(), len) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// Put a UTF-16 encoded string.
    ///
    /// This function will return a WSTP error if `utf16` is not a valid UTF-16 encoded
    /// string.
    ///
    /// *WSTP C API Documentation:* [`WSPutUTF16String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF16String.html)
    ///
    pub fn put_utf16_str(&mut self, utf16: &[u16]) -> Result<(), Error> {
        let len = i32::try_from(utf16.len()).expect("usize overflows i32");

        if unsafe { WSPutUTF16String(self.raw_link, utf16.as_ptr(), len) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// Put a UTF-32 encoded string.
    ///
    /// This function will return a WSTP error if `utf32` is not a valid UTF-32 encoded
    /// string.
    ///
    /// *WSTP C API Documentation:* [`WSPutUTF32String()`](https://reference.wolfram.com/language/ref/c/WSPutUTF32String.html)
    pub fn put_utf32_str(&mut self, utf32: &[u32]) -> Result<(), Error> {
        let len = i32::try_from(utf32.len()).expect("usize overflows i32");

        if unsafe { WSPutUTF32String(self.raw_link, utf32.as_ptr(), len) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    //==================================
    // Functions
    //==================================

    /// Begin putting a function onto this link.
    ///
    /// # Examples
    ///
    /// Put the expression `{1, 2, 3}` on the link:
    ///
    /// ```
    /// # use wstp::Link;
    /// # fn test() -> Result<(), wstp::Error> {
    /// let mut link = Link::new_loopback()?;
    ///
    /// link.put_function("System`List", 3)?;
    /// link.put_i64(1)?;
    /// link.put_i64(2)?;
    /// link.put_i64(3)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Put the expression `foo["a"]["b"]` on the link:
    ///
    /// ```
    /// # use wstp::Link;
    /// # fn test() -> Result<wolfram_expr::Expr, wstp::Error> {
    /// let mut link = Link::new_loopback()?;
    ///
    /// link.put_function(None, 1)?;
    /// link.put_function("Global`foo", 1)?;
    /// link.put_str("a")?;
    /// link.put_str("b")?;
    /// # link.get_expr()
    /// # }
    ///
    /// # use wolfram_expr::{Expr, Symbol};
    /// # assert_eq!(test().unwrap(), Expr::normal(
    /// #     Expr::normal(Symbol::new("Global`foo"), vec![Expr::string("a")]),
    /// #     vec![Expr::string("b")]
    /// # ))
    /// ```
    pub fn put_function<'h, H: Into<Option<&'h str>>>(
        &mut self,
        head: H,
        count: usize,
    ) -> Result<(), Error> {
        self.put_raw_type(i32::from(sys::WSTKFUNC))?;
        self.put_arg_count(count)?;

        if let Some(head) = head.into() {
            self.put_symbol(head)?;
        }

        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutArgCount()`](https://reference.wolfram.com/language/ref/c/WSPutArgCount.html)
    pub fn put_arg_count(&mut self, count: usize) -> Result<(), Error> {
        let count: i32 = i32::try_from(count).map_err(|err| {
            Error::custom(format!(
                "put_arg_count: Error converting usize to i32: {}",
                err
            ))
        })?;

        if unsafe { WSPutArgCount(self.raw_link, count) } == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    //==================================
    // Numerics
    //==================================

    /// *WSTP C API Documentation:* [`WSPutInteger64()`](https://reference.wolfram.com/language/ref/c/WSPutInteger64.html)
    pub fn put_i64(&mut self, value: i64) -> Result<(), Error> {
        if unsafe { WSPutInteger64(self.raw_link, value) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutInteger32()`](https://reference.wolfram.com/language/ref/c/WSPutInteger32.html)
    pub fn put_i32(&mut self, value: i32) -> Result<(), Error> {
        if unsafe { WSPutInteger32(self.raw_link, value) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutInteger16()`](https://reference.wolfram.com/language/ref/c/WSPutInteger16.html)
    pub fn put_i16(&mut self, value: i16) -> Result<(), Error> {
        // Note: This conversion is necessary due to the declaration of WSPutInteger16,
        //       which takes an int for legacy reasons.
        let value = i32::from(value);

        if unsafe { WSPutInteger16(self.raw_link, value) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutInteger8()`](https://reference.wolfram.com/language/ref/c/WSPutInteger8.html)
    pub fn put_u8(&mut self, value: u8) -> Result<(), Error> {
        if unsafe { WSPutInteger8(self.raw_link, value) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutReal64()`](https://reference.wolfram.com/language/ref/c/WSPutReal64.html)
    pub fn put_f64(&mut self, value: f64) -> Result<(), Error> {
        if unsafe { WSPutReal64(self.raw_link, value) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutReal32()`](https://reference.wolfram.com/language/ref/c/WSPutReal32.html)
    pub fn put_f32(&mut self, value: f32) -> Result<(), Error> {
        // Note: This conversion is necessary due to the declaration of WSPutReal32,
        //       which takes a double for legacy reasons.
        let value = f64::from(value);

        if unsafe { WSPutReal32(self.raw_link, value) } == 0 {
            return Err(self.error_or_unknown());
        }
        Ok(())
    }

    //==================================
    // Integer numeric arrays
    //==================================

    /// Put a multidimensional array of [`i64`].
    ///
    /// # Panics
    ///
    /// This function will panic if the product of `dimensions` is not equal to `data.len()`.
    ///
    /// *WSTP C API Documentation:* [`WSPutInteger64Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger64Array.html)
    pub fn put_i64_array(
        &mut self,
        data: &[i64],
        dimensions: &[usize],
    ) -> Result<(), Error> {
        assert_eq!(
            data.len(),
            dimensions.iter().product(),
            "data length does not equal product of dimensions"
        );

        let dimensions: Vec<i32> = abi_array_dimensions(dimensions)?;

        let result = unsafe {
            sys::WSPutInteger64Array(
                self.raw_link,
                data.as_ptr(),
                dimensions.as_ptr(),
                std::ptr::null_mut(),
                dimensions.len() as i32,
            )
        };

        if result == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    /// Put a multidimensional array of [`i32`].
    ///
    /// # Panics
    ///
    /// This function will panic if the product of `dimensions` is not equal to `data.len()`.
    ///
    /// *WSTP C API Documentation:* [`WSPutInteger32Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger32Array.html)
    pub fn put_i32_array(
        &mut self,
        data: &[i32],
        dimensions: &[usize],
    ) -> Result<(), Error> {
        assert_eq!(
            data.len(),
            dimensions.iter().product(),
            "data length does not equal product of dimensions"
        );

        let dimensions: Vec<i32> = abi_array_dimensions(dimensions)?;

        let result = unsafe {
            sys::WSPutInteger32Array(
                self.raw_link,
                data.as_ptr(),
                dimensions.as_ptr(),
                std::ptr::null_mut(),
                dimensions.len() as i32,
            )
        };

        if result == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    /// Put a multidimensional array of [`i16`].
    ///
    /// # Panics
    ///
    /// This function will panic if the product of `dimensions` is not equal to `data.len()`.
    ///
    /// *WSTP C API Documentation:* [`WSPutInteger16Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger16Array.html)
    pub fn put_i16_array(
        &mut self,
        data: &[i16],
        dimensions: &[usize],
    ) -> Result<(), Error> {
        assert_eq!(
            data.len(),
            dimensions.iter().product(),
            "data length does not equal product of dimensions"
        );

        let dimensions: Vec<i32> = abi_array_dimensions(dimensions)?;

        let result = unsafe {
            sys::WSPutInteger16Array(
                self.raw_link,
                data.as_ptr(),
                dimensions.as_ptr(),
                std::ptr::null_mut(),
                dimensions.len() as i32,
            )
        };

        if result == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    /// *WSTP C API Documentation:* [`WSPutInteger8Array()`](https://reference.wolfram.com/language/ref/c/WSPutInteger8Array.html)
    pub fn put_u8_array(
        &mut self,
        data: &[u8],
        dimensions: &[usize],
    ) -> Result<(), Error> {
        assert_eq!(
            data.len(),
            dimensions.iter().product(),
            "data length does not equal product of dimensions"
        );

        let dimensions: Vec<i32> = abi_array_dimensions(dimensions)?;

        let result = unsafe {
            sys::WSPutInteger8Array(
                self.raw_link,
                data.as_ptr(),
                dimensions.as_ptr(),
                std::ptr::null_mut(),
                dimensions.len() as i32,
            )
        };

        if result == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    //==================================
    // Floating-point numeric arrays
    //==================================

    /// Put a multidimensional array of [`f64`].
    ///
    /// # Panics
    ///
    /// This function will panic if the product of `dimensions` is not equal to `data.len()`.
    ///
    /// *WSTP C API Documentation:* [`WSPutReal64Array()`](https://reference.wolfram.com/language/ref/c/WSPutReal64Array.html)
    pub fn put_f64_array(
        &mut self,
        data: &[f64],
        dimensions: &[usize],
    ) -> Result<(), Error> {
        assert_eq!(
            data.len(),
            dimensions.iter().product(),
            "data length does not equal product of dimensions"
        );

        let dimensions: Vec<i32> = abi_array_dimensions(dimensions)?;

        let result = unsafe {
            sys::WSPutReal64Array(
                self.raw_link,
                data.as_ptr(),
                dimensions.as_ptr(),
                std::ptr::null_mut(),
                dimensions.len() as i32,
            )
        };

        if result == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }

    /// Put a multidimensional array of [`f32`].
    ///
    /// # Panics
    ///
    /// This function will panic if the product of `dimensions` is not equal to `data.len()`.
    ///
    /// *WSTP C API Documentation:* [`WSPutReal32Array()`](https://reference.wolfram.com/language/ref/c/WSPutReal32Array.html)
    pub fn put_f32_array(
        &mut self,
        data: &[f32],
        dimensions: &[usize],
    ) -> Result<(), Error> {
        assert_eq!(
            data.len(),
            dimensions.iter().product(),
            "data length does not equal product of dimensions"
        );

        let dimensions: Vec<i32> = abi_array_dimensions(dimensions)?;

        let result = unsafe {
            sys::WSPutReal32Array(
                self.raw_link,
                data.as_ptr(),
                dimensions.as_ptr(),
                std::ptr::null_mut(),
                dimensions.len() as i32,
            )
        };

        if result == 0 {
            return Err(self.error_or_unknown());
        }

        Ok(())
    }
}

/// Convert `dimensions` to a `Vec<i32>`, which can further be converted to a
/// *const i32, which is needed when calling the low-level WSTP API functions.
fn abi_array_dimensions(dimensions: &[usize]) -> Result<Vec<i32>, Error> {
    let mut i32_dimensions = Vec::with_capacity(dimensions.len());

    for (index, dim) in dimensions.iter().copied().enumerate() {
        match i32::try_from(dim) {
            Ok(val) => i32_dimensions.push(val),
            Err(err) => {
                // Overflowing the array dimension size should probably never happen in
                // well-behaved code, but if it does happen, there is probably some subtle
                // bug, so we should try to emit an error message that is as specific as
                // possible.
                return Err(Error::custom(format!(
                    "in dimensions list {dimensions:?}, the dimension at index {index} \
                     (value: {dim}) overflows i32: {}; during WSTP array operation.",
                    err
                )));
            },
        }
    }

    Ok(i32_dimensions)
}