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
pub mod numeric;
pub mod pointers;
pub mod raw;
pub mod classid;
pub mod mappable;

pub mod shim;
pub mod convert;

pub use raw::{mxArray, mxComplexity};

// I wanted to use cfg(doc) for this, but it didn't really work.
#[allow(unused)]
use crate::{
	pointers::{
		MatlabPtr,
		MutMatlabPtr,
	},
};

/**
 * Macro to construct a valid pointer for slice construction. Internal Rustmex tool.
 *
 * Matlab returns, for empty arrays, a null pointer. For this case, we want to construct
 * an empty slice, but cannot pass in the null pointer for that. Instead, per
 * [std::slice::from_raw_parts]' documentation, we can obtain a valid pointer through NonNull.
 *
 * ```rust
 * # use rustmex_core::data_or_dangling;
 * # use core::ffi::c_void;
 * fn get_some_maybe_null_pointer() -> *const c_void { 0 as *const c_void }
 * const DATA: *const i8 = 0xbeef as *const i8;
 * let nonnull_i8 = data_or_dangling!{ get_some_maybe_null_pointer(), *const i8 };
 * let data = data_or_dangling!{ DATA, *const i8 };
 * assert_ne!(nonnull_i8, core::ptr::null());
 * assert_eq!(data, DATA);
 * ```
 */
#[macro_export]
macro_rules! data_or_dangling {
	($p:expr, $t:ty) => {{
		let ptr = { $p };
		(if ptr.is_null() {
			::core::ptr::NonNull::dangling().as_ptr()
		} else {
			ptr
		}) as $t
	}}
}

/**
 * Given some data and a shape, check whether the size is okay. Internal Rustmex tool.
 *
 * _Cf._ [`DataShapeMismatch`](convert::DataShapeMismatch).
 */
#[macro_export]
macro_rules! data_shape_ok {
	($data:ident, $shape:ident) => {
		::rustmex_core::shape_ok!($shape);

		// In this case, the provided shape does not match the total data size.
		if $shape.iter().product::<usize>() != $data.len() {
			return Err(::rustmex_core::convert
				::DataShapeMismatch::because_numel_shape($data))
		}
	}
}

/**
 * Flag for whether a real or complex numeric array should be created.
 *
 * Enumerates over the allowed values of the [`mxComplexity`](raw::mxComplexity) type.
 * Besides that, it has the same size and ABI as that type, so can be passed as is.
 */
#[repr(u32)]
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum Complexity {
	Real = raw::mxComplexity_mxREAL,
	Complex = raw::mxComplexity_mxCOMPLEX
}

impl mxArray {
	pub fn complexity(&self) -> Complexity {
		self.is_complex().into()
	}
}

impl From<Complexity> for bool {
	fn from(c: Complexity) -> Self {
		match c {
			Complexity::Real => false,
			Complexity::Complex => true,
		}
	}
}

impl From<bool> for Complexity {
	fn from(b: bool) -> Self {
		if b { Complexity::Complex } else { Complexity::Real }
	}
}

impl From<Complexity> for mxComplexity {
	fn from(c: Complexity) -> Self {
		bool::from(c) as Self
	}
}

impl PartialEq<bool> for Complexity {
	fn eq(&self, other: &bool) -> bool {
		bool::from(*self) == *other
	}
}

impl PartialEq<Complexity> for bool {
	fn eq(&self, other: &Complexity) -> bool {
		other.eq(self)
	}
}

/**
 * Create an [`mxArray`] of a specified shape, type, and complexity, **without** a
 * backing array. Internal Rustmex tool.
 *
 * Creating an empty [`mxArray`] avoids the allocation matlab would otherwise make. The
 * expectation is that that data will be provided immediately after the creation of the
 * [`mxArray`]. Until the data is provided, the data get methods will return `NULL`,
 * which is an invalid state for Rustmex mxArrays to be in, which expect that they will
 * always have a backing array and thus a valid reference to return to that.
 */
#[macro_export]
macro_rules! create_uninit_numeric_array {
	($shape:ident, $t:ty, $complexity:expr) => {{
		use rustmex_core::{
			Complexity,
			raw::{mxClassID, mwSize},
			shim::{
				rustmex_create_uninit_numeric_array,
				rustmex_set_dimensions,
			}
		};

		const EMPTY_ARRAY_SIZE: [mwSize; 2] = [0, 0];
		const RESIZE_FAILURE: i32 = 1;

		let ptr = unsafe {
			rustmex_create_uninit_numeric_array(
				EMPTY_ARRAY_SIZE.len() as mwSize,
				EMPTY_ARRAY_SIZE.as_ptr(),
				<$t>::class_id() as mxClassID,
				$complexity as u32)
		};

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

		if unsafe { rustmex_set_dimensions(
			ptr,
			$shape.as_ptr(),
			$shape.len()
		) } == RESIZE_FAILURE {
			panic!("could not resize array!")
		}

		ptr
	}}
}

/**
 * Check whether a shape is okay. Internal Rustmex tool
 *
 * Since some backends use a signed type for the dimension lenghts, values greater that
 * [`isize::MAX`] are not supported. Currently implemented as a [`debug_assert`], but
 * that may change in the future.
 */
#[macro_export]
macro_rules! shape_ok {
	($shape:ident) => {
		debug_assert!($shape.iter().all(|&v| v <= isize::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."
		)
	}
}

use core::ops::{Deref, DerefMut};
use crate::pointers::MxArray;
use crate::convert::FromMatlabError;

/**
 * Base Matlab class trait. Matlab classes, in Rustmex, are wrapper structures around a
 * bare [`MatlabPtr`], giving them some type information.
 */
pub trait MatlabClass<P>: Deref<Target = mxArray> + Sized {
	/**
	 * Try to build a matlab class from a [`MatlabPtr`]. If the type requirements of
	 * the class match what the pointer is, then the class is constructed. Otherwise,
	 * an error is returned; containing the reason of the failure and the original
	 * pointer. The latter is especially useful with [`MxArray`]s; the owned
	 * [`MatlabPtr`] type --- otherwise it would be dropped.
	 */
	fn from_mx_array(mx: P) -> Result<Self, FromMatlabError<P>>;

	/// Deconstruct the `MatlabClass` back to a bare [`MatlabPtr`].
	fn into_inner(self) -> P;
	/**
	 * Get a reference to the inner [`MatlabPtr`]. However, note that for `&mxArray`
	 * and `&mut mxArray`, the returned references will be of type `&&mxArray` and
	 * `&&mut mxArray`.
	 */
	fn inner(&self) -> &P;

	/// The owned variant of this matlab class.
	type Owned;
	/**
	 * Make a deep clone of the inner [`MatlabPtr`], and construct an
	 * [`Owned`](Self::Owned) [`MatlabClass`] from it.
	 */
	fn duplicate(&self) -> Self::Owned;
}

/// Denotes whether the Matlab class is mutable.
pub trait MutMatlabClass<P>: MatlabClass<P> + DerefMut {
	type AsBorrowed<'a> where Self: 'a, P: 'a;
	fn as_borrowed<'a>(&'a self) -> Self::AsBorrowed<'a>;
	fn inner_mut(&mut self) -> &mut P;
}

/// Denotes whether a Matlab class owns its data.
pub trait OwnedMatlabClass: MutMatlabClass<MxArray> {
	/// The way this class would be represented if it were a mutable borrow.
	type AsMutable<'a> where Self: 'a; // e.g. Numeric<&'s mut mxArray>
	/// Create a [`MutMatlabClass`] from this owned instance.
	fn as_mutable<'a>(&'a mut self) -> Self::AsMutable<'a>;

}

/**
 * Only some Matlab classes, _i.e_ the numeric classes, have data that can be
 * meaningfully taken out of the backing [`MutMatlabPtr`].
 */
pub trait TakeData<P>: MutMatlabClass<P> {
	/// The type of data that this array wraps.
	type OwnedData;

	/// Take the data out of the array, leaving it in an empty state.
	fn take_data(&mut self) -> Self::OwnedData;
}

/**
 * Some, but not all types, can be created in an empty state; whether they can is denoted
 * by this trait.
 */
pub trait NewEmpty: OwnedMatlabClass {
	/// Construct the empty type
	fn new_empty() -> Self;
}