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

use core::ffi::CStr;
use std::ptr::NonNull;

use crate::convert::FromMatlab;

use rustmex_core::{
	convert::{
		FromMatlabError,
	},
	classid::ClassID,
	raw::mwSize,
	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,
	},
};

pub use super::index::Index;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StructError {
	NotAField,
	OutOfBounds,
}

#[derive(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> {
		if mx.class_id() == ClassID::Struct {
			Ok(Self(mx))
		} else {
			Err(FromMatlabError::BadClass)
		}
	}
}

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

	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> Struct<P> {

	/// Destructure the structure array to get at the inner pointer
	pub fn into_inner(self) -> P {
		self.0
	}

	/// 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.
	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> {

	/**
	 * 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)
	}

	pub fn unset<I: Index, F: FieldIndex>(&mut self, idx: I, field: F) -> Result<Option<MxArray>, StructError> {
		self.replace(idx, field, None)
	}

	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()))
	}

	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()))
	}

	pub fn add_field(&mut self, field: &CStr) -> i32 {
		let fieldnum = unsafe { mxAddField(self.0.deref_mut(), field.as_ptr()) };
		if fieldnum == -1 {
			panic!("OOM")
		}

		fieldnum
	}

	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(())
	}

	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 a new structure array with a given set of fields, providing the array's
	 * dimensions in the native matlab type. _See also_ [`StructureArray::new`]
	 */
	pub fn new_mwsize(shape: &[mwSize], fieldnames: &[&CStr]) -> Self {
		#[cfg(all(not(feature = "doc"), feature = "octave"))]
		assert!(shape.iter().all(|&v| v.is_positive()),
			"Octave uses a signed type for the lengths of dimensions. One or more values in the give shape are negative"
		);

		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) } )
	}

	/**
	 * Create a new structure array with the given fieldnames.
	 */
	pub fn new(shape: &[usize], fieldnames: &[&CStr]) -> Self {
		#[cfg(feature = "octave")]
		assert!(shape.iter().all(|&v| v <= mwSize::MAX as usize),
			"Octave uses a signed type for the length of dimensions. One or more values was over this signed type's maximum value."
		);

		Self::new_mwsize(unsafe { std::mem::transmute(shape) }, fieldnames)
	}
}


/**
 * 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`.
 */
#[derive(Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct ScalarStruct<P>(Struct<P>);

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

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

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

impl<'p, P: MatlabPtr + 'p> ScalarStruct<P> {
	pub fn from_struct(s: Struct<P>) -> Result<Self, Struct<P>> {
		if s.numel() == 1 {
			Ok(Self(s))
		} else {
			Err(s)
		}
	}

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

impl<'p, P: MutMatlabPtr + 'p> ScalarStruct<P> {
	#[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)
	}
}