rustmex 0.6.4

Rustmex: providing convenient Rust bindings to Matlab MEX API's
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*!
 * Structures and structure arrays
 */
use core::ffi::CStr;
use std::ptr::NonNull;
use core::ops::DerefMut;

use crate::convert::FromMatlab;

use rustmex_core::{
	convert::{
		FromMatlabError,
	},
	classid::ClassID,
	shim::{
		rustmex_get_field_number as mxGetFieldNumber,
		rustmex_get_field_by_number as mxGetFieldByNumber,
		rustmex_set_field_by_number as mxSetFieldByNumber,

		rustmex_get_number_of_fields as mxGetNumberOfFields,
		rustmex_get_field_name_by_number as mxGetFieldNameByNumber,

		rustmex_create_struct_array as mxCreateStructArray,

		rustmex_add_field as mxAddField,
		rustmex_remove_field as mxRemoveField,
	},

	mxArray,
	pointers::{
		MxArray,
		MatlabPtr,
		MutMatlabPtr,
	},

	MatlabClass,
	MutMatlabClass,
	OwnedMatlabClass,
	NewEmpty,
};

pub use super::index::Index;

/**
 * List of possible errors that might occur when operating on structure arrays
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StructError {
	/// The field you're trying to access does not exist
	NotAField,
	/// The structure element you're trying to access is out of bounds
	OutOfBounds,
}

/**
 * ND Structure array.
 */
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Struct<P>(P);

impl<'a> FromMatlab<'a> for Struct<&'a mxArray> {
	fn from_matlab(mx: &'a mxArray) -> Result<Self, FromMatlabError<&'a mxArray>> {
		Self::from_mx_array(mx)
	}
}

impl<P> std::ops::Deref for Struct<P> where P: MatlabPtr {
	type Target = mxArray;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl<P> std::ops::DerefMut for Struct<P> where P: MutMatlabPtr {
	fn deref_mut(&mut self) -> &mut Self::Target {
		&mut self.0
	}
}

/// Trait to compute the "field index" for both strings and numbers. Matlab allows
/// accesses to struct fields through both.
pub trait FieldIndex {
	fn index_into<P: MatlabPtr>(&self, s: &Struct<P>) -> Result<i32, StructError>;
}

impl FieldIndex for &CStr {
	fn index_into<P: MatlabPtr>(&self, s: &Struct<P>) -> Result<i32, StructError> {
		s.field_number(self)
	}
}

impl FieldIndex for i32 {
	fn index_into<P: MatlabPtr>(&self, s: &Struct<P>) -> Result<i32, StructError> {
		if *self < 0 || *self >= s.num_fields() {
			Err(StructError::NotAField)
		} else {
			Ok(*self)
		}
	}
}

impl<'p, P: MatlabPtr + 'p> MatlabClass<P> for Struct<P> {
	fn from_mx_array(mx: P) -> Result<Self, FromMatlabError<P>> {
		if mx.class_id() == Ok(ClassID::Struct) {
			Ok(Self(mx))
		} else {
			Err(FromMatlabError::new_badclass(mx))
		}
	}

	fn into_inner(self) -> P {
		self.0
	}

	fn inner(&self) -> &P {
		&self.0
	}

	type Owned = Struct<MxArray>;
	fn duplicate(&self) -> Self::Owned {
		Struct(self.0.duplicate())
	}
}

impl<'p, P: MutMatlabPtr + 'p> MutMatlabClass<P> for Struct<P> {
	type AsBorrowed<'a> = Struct<&'a mxArray> where P: 'a;

	fn as_borrowed<'a>(&'a self) -> Self::AsBorrowed<'a> {
		Struct(self.0.deref())
	}

	fn inner_mut(&mut self) -> &mut P {
		&mut self.0
	}
}

pub type OwnedStruct = Struct<MxArray>;

impl OwnedMatlabClass for Struct<MxArray> {
	type AsMutable<'a> = Struct<&'a mut mxArray> where Self: 'a;
	fn as_mutable<'a>(&'a mut self) -> Self::AsMutable<'a> {
		Struct(self.0.deref_mut())
	}
}

impl NewEmpty for Struct<MxArray> {
	fn new_empty() -> Self {
		Self::new_empty_with_fields(&[])
	}
}

impl<'p, P: MatlabPtr + 'p> Struct<P> {

	/// If the structure array only holds one element, convert it to a type that
	/// reflects that
	pub fn into_scalar(self) -> Result<ScalarStruct<P>, Self> {
		ScalarStruct::from_struct(self)
	}

	/// Get the number of fields as an i32, how Matlab returns it.
	fn num_fields(&self) -> i32 {
		let num = unsafe { mxGetNumberOfFields(self.0.deref()) };
		assert_ne!(num, 0,
			"Only documented failure case if self.0 is not a struct, but we know it is");
		num
	}

	/**
	 * Determine the field number for some field name.
	 *
	 * NOTE: field numbers are not static; if a new field is added or removed the
	 * field numbers change. The only reliable way accessing fields is via their
	 * name.
	 */
	pub fn field_number(&self, field: &CStr) -> Result<i32, StructError> {
		let num = unsafe { mxGetFieldNumber(self.0.deref(), field.as_ptr()) };
		if num < 0 {
			Err(StructError::NotAField)
		} else {
			Ok(num)
		}
	}

	/// Determine the field name of the `fieldnum`th field.
	pub fn field_name(&self, fieldnum: i32) -> Result<&'p CStr, StructError> {
		if fieldnum < 0 {
			return Err(StructError::NotAField)
		}
		let name = unsafe { mxGetFieldNameByNumber(self.0.deref(), fieldnum) };
		if name.is_null() {
			Err(StructError::NotAField)
		} else {
			Ok( unsafe { CStr::from_ptr(name) })
		}
	}

	/// Iterate over all the field names of this struct
	pub fn field_names(&self) -> impl Iterator<Item = &'p CStr> + '_ {
		let n = self.num_fields();
		(0..n).map(|idx| self.field_name(idx).unwrap())
	}

	/// Get the field of some structure within this array.
	pub fn get<I: Index, F: FieldIndex>(&self, idx: I, field: F) -> Result<Option<&'p mxArray>, StructError> {
		let linidx   = idx.index_into(&self.0).ok_or(StructError::OutOfBounds)?;
		let fieldidx = field.index_into(self)?;

		Ok(unsafe { NonNull::new(mxGetFieldByNumber(self.0.deref(), linidx as _, fieldidx)) }
			.map(|mx| unsafe { mx.as_ref() }))
	}

	/**
	 *  Get an iterator which returns references to the fields of each child
	 *  structure. So, e.g.: `s(1).field, s(2).field`, etc.
	 */
	pub fn fields<F: FieldIndex>(&self, field: F) -> Result<impl Iterator<Item = Option<&'p mxArray>> + '_, StructError> {
		let n = self.0.numel();
		let f = field.index_into(self)?;

		Ok((0..n).map(move |linidx| self.get(linidx, f).expect("linidx should be in range")))
	}
}

impl<'p, P: MutMatlabPtr + 'p> Struct<P> {

	pub fn as_ref_struct<'s>(&'s self) -> Struct<&'s mxArray> {
		Struct(&self.0)
	}

	/**
	 * Get a mutable access to the field of some child struct.
	 */
	pub fn get_mut<I: Index, F: FieldIndex>(&mut self, idx: I, field: F) -> Result<Option<&'p mut mxArray>, StructError> {
		let linidx   = idx.index_into(&self.0).ok_or(StructError::OutOfBounds)?;
		let fieldidx = field.index_into(self)?;

		Ok(unsafe { NonNull::new(mxGetFieldByNumber(self.0.deref_mut(), linidx as _, fieldidx)) }
			.map(|mut mx| unsafe { mx.as_mut() }))
	}

	/// Set the value of a field of some child struct. Returns the previous value, if
	/// there was any.
	pub fn set<I: Index, F: FieldIndex>(&mut self, idx: I, field: F, value: MxArray) -> Result<Option<MxArray>, StructError> {
		self.replace(idx, field, Some(value))
	}

	/**
	 * Replace the current value of some child struct. This can be either `None`
	 * (removing the element), or `Some(value)` (in which case it replaces the old
	 * value). In either case, it returns what was previously there, which can also
	 * be `None` or `Some(value)`.
	 */
	pub fn replace<I: Index, F: FieldIndex>(&mut self, idx: I, field: F, value: Option<MxArray>) -> Result<Option<MxArray>, StructError> {
		let linidx   = idx.index_into(&self.0).ok_or(StructError::OutOfBounds)?;
		let fieldidx = field.index_into(self)?;

		let old = unsafe { NonNull::new(mxGetFieldByNumber(self.0.deref_mut(), linidx as _, fieldidx)) }
			.map(|mut ptr| unsafe { MxArray::assume_responsibility(ptr.as_mut()) } );

		// SAFETY: When not setting a new mxArray, we can't just skip this call,
		// since it will leave a dangling pointer to the mxArray which may be
		// destroyed. Instead, we must set a NULL pointer.
		unsafe {
			mxSetFieldByNumber(
				self.0.deref_mut(),
				linidx as _,
				fieldidx,
				if let Some(val) = value {
					MxArray::transfer_responsibility_ptr(val)
				} else {
					std::ptr::null_mut()
				}
			)
		}

		Ok(old)
	}

	/// Unset a struct field by setting it to None. See [`replace`](Self::replace).
	pub fn unset<I: Index, F: FieldIndex>(&mut self, idx: I, field: F) -> Result<Option<MxArray>, StructError> {
		self.replace(idx, field, None)
	}

	/**
	 * Return an iterator, returning mutable references to a field on each struct in
	 * the array, as with [`Struct::fields`].
	 */
	pub fn fields_mut<F: FieldIndex>(&mut self, field: F) -> Result<impl Iterator<Item = Option<&'p mut mxArray>> + '_, StructError> {
		let n = self.0.numel();
		let f = field.index_into(self)?;

		Ok((0..n).map(move |linidx| self.get_mut(linidx, f).unwrap()))
	}

	/**
	 * Return an iterator, yielding the values of a field on each struct in the
	 * array. This will set each yielded field to `None`. _Also see_
	 * [`Struct::fields`].
	 */
	pub fn fields_values<F: FieldIndex>(&mut self, field: F) -> Result<impl Iterator<Item = Option<MxArray>> + '_, StructError> {
		let n = self.0.numel();
		let f = field.index_into(self)?;

		Ok((0..n).map(move |linidx| self.unset(linidx, f).unwrap()))
	}

	/**
	 * Add a field to the structure array. If the field does not yet exist, it
	 * returns `Ok(new_field_num)`; if the field already exists it returns
	 * `Err(existing_field_number)`.
	 *
	 * Since no values for the fields are provided, they are initialised with
	 * [`None`].
	 *
	 * If you're not interested in whether the field existed or not, you can obtain
	 * the field number to the field you wanted to add with:
	 * ```rust,ignore
	 * use std::convert::identity as idtt;
	 * let fieldnum = s.add_field(name).map_or_else(idtt, idtt)
	 * ```
	 *
	 * NOTE that the field number is not static; if the structure array layout is
	 * mutated (_e.g._ a new field being added or removed), the field numbers
	 * for the fields may change.
	 */
	pub fn add_field(&mut self, field: &CStr) -> Result<i32, i32> {
		if let Ok(fieldnum) = self.field_number(field) {
			return Err(fieldnum);
		}

		let fieldnum = unsafe { mxAddField(self.0.deref_mut(), field.as_ptr()) };
		if fieldnum == -1 {
			panic!("OOM")
		}

		Ok(fieldnum)
	}

	/**
	 * Remove a field from a structure array _without_ dropping and freeing their
	 * values. _See_ [`Struct::delete_field`] instead
	 */
	pub fn remove_field<F: FieldIndex>(&mut self, field: F) -> Result<(), StructError> {
		let fieldidx = field.index_into(self)?;
		unsafe { mxRemoveField(self.0.deref_mut(), fieldidx) };

		Ok(())
	}

	/**
	 * Removes a field from a structure array, dropping and freeing their resources
	 * in the process.
	 */
	pub fn delete_field<F: FieldIndex>(&mut self, field: F) -> Result<(), StructError> {
		let fieldidx = field.index_into(self)?;
		self.fields_values(fieldidx).unwrap().for_each(|_value| {});
		self.remove_field(fieldidx)
	}
}

impl Struct<MxArray> {
	/// Create an empty struct but with field names.
	pub fn new_empty_with_fields(fieldnames: &[&CStr]) -> Self {
		const EMPTY: [usize; 2] = [0,0];
		Self::new(&EMPTY[..], fieldnames)
	}

	/**
	 * Create a new structure array with the given fieldnames.
	 */
	pub fn new(shape: &[usize], fieldnames: &[&CStr]) -> Self {
		rustmex_core::shape_ok!(shape);
		more_asserts::assert_lt!(fieldnames.len(), i32::MAX as usize, "Too many field names");

		// It would be nice if we could just cast the &[&CStr] to a **char, but
		// of course we can't.
		//
		// For one, the CStr documentation specifies that it is not safe to pass
		// a &CStr over an FFI boundary — directing the user to as_ptr(). Only
		// there is no method to convert a slice of CStr's, while **char is a
		// common pattern. Furthermore, in a comment it says that casting to
		// **char is safe, but _only_ in the standard library.
		//
		// The second problem is that mxCreateStructArray is declared with *mut
		// *const c_char, not *const *const c_char — which is the promise
		// &[&CStr] makes.
		let mut fieldnames = fieldnames
			.iter()
			.map(|fieldname| fieldname.as_ptr())
			.collect::<Vec<_>>();

		let ptr = unsafe { mxCreateStructArray(
			shape.len(),
			shape.as_ptr(),
			fieldnames.len() as i32,
			fieldnames.as_mut_ptr()
		)};

		if ptr.is_null() {
			panic!("OOM")
		}

		Self(unsafe { MxArray::assume_responsibility(&mut *ptr) } )
	}
}


/**
 * Often, one only deals with a structure array with one item (configuration structs, for
 * example). In that case, one can convert the `Struct` to this `ScalarStruct`, which
 * always passes in `0` for the linear index. It's just a very thin wrapper around
 * `Struct`.
 *
 * For documentation on methods, see the documentation on [`Struct`]; the functionality
 * is the same, just one fewer argument (you no longer need to index into the struct).
 *
 * The reason [`MatlabClass`] isn't implemented for [`ScalarStruct`] is that it is not a
 * real matlab primitive. Moreover, [`MutMatlabClass`] allows for the extraction of a
 * mutable reference to the inner [`MutMatlabPtr`], allowing its size to change,
 * undermining the base assuption of this type.
 */
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct ScalarStruct<P>(Struct<P>);

impl<'p, P: MatlabPtr + 'p> ScalarStruct<P> {
	/// Convert a [`Struct`] to a `ScalarStruct` if the former only holds one struct
	pub fn from_struct(s: Struct<P>) -> Result<Self, Struct<P>> {
		if s.numel() == 1 {
			Ok(Self(s))
		} else {
			Err(s)
		}
	}

	/// Convert a `ScalarStruct` back into a [`Struct`]
	pub fn into_struct(self) -> Struct<P> {
		self.0
	}

	/// Return the backing [`MatlabPtr`]
	pub fn into_inner(self) -> P {
		self.into_struct().into_inner()
	}

	#[inline]
	pub fn get<F: FieldIndex>(&self, f: F) -> Result<Option<&'p mxArray>, StructError> {
		self.0.get(0, f)
	}

	#[inline]
	pub fn field_name(&self, fieldnum: i32) -> Result<&'p CStr, StructError> {
		self.0.field_name(fieldnum)
	}

	#[inline]
	pub fn field_number(&self, fieldname: &CStr) -> Result<i32, StructError> {
		self.0.field_number(fieldname)
	}


	#[inline]
	pub fn field_names(&self) -> impl Iterator<Item = &'p CStr> + '_ {
		self.0.field_names()
	}

	#[inline]
	pub fn fields<F: FieldIndex>(&self, field: F) -> Result<impl Iterator<Item = Option<&'p mxArray>> + '_, StructError> {
		self.0.fields(field)
	}
}

impl<'p, P: MutMatlabPtr + 'p> ScalarStruct<P> {

	pub fn as_ref_struct<'s>(&'s self) -> ScalarStruct<&'s mxArray> {
		ScalarStruct(self.0.as_ref_struct())
	}

	#[inline]
	pub fn get_mut<F: FieldIndex>(&mut self, f: F) -> Result<Option<&'p mut mxArray>, StructError> {
		self.0.get_mut(0, f)
	}

	#[inline]
	pub fn set<F: FieldIndex>(&mut self, field: F, value: MxArray) -> Result<Option<MxArray>, StructError> {
		self.replace(field, Some(value))
	}

	#[inline]
	pub fn replace<F: FieldIndex>(&mut self, field: F, value: Option<MxArray>) -> Result<Option<MxArray>, StructError> {
		self.0.replace(0, field, value)
	}

	#[inline]
	pub fn unset<F: FieldIndex>(&mut self, field: F) -> Result<Option<MxArray>, StructError> {
		self.replace(field, None)
	}

	#[inline]
	pub fn fields_mut<F: FieldIndex>(&mut self, field: F) -> Result<impl Iterator<Item = Option<&'p mut mxArray>> + '_, StructError> {
		self.0.fields_mut(field)
	}

	#[inline]
	pub fn fields_values<F: FieldIndex>(&mut self, field: F) -> Result<impl Iterator<Item = Option<MxArray>> + '_, StructError> {
		self.0.fields_values(field)
	}

	#[inline]
	pub fn remove_field<F: FieldIndex>(&mut self, field: F) -> Result<(), StructError> {
		self.0.remove_field(field)
	}

	#[inline]
	pub fn delete_field<F: FieldIndex>(&mut self, field: F) -> Result<(), StructError> {
		self.0.delete_field(field)
	}

	#[inline]
	pub fn add_field(&mut self, field: &CStr) -> Result<i32, i32> {
		self.0.add_field(field)
	}
}