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
/*!
 * This module handles Matlab's Cell arrays
 *
 */

use std::ptr::NonNull;
use crate::convert::FromMatlab;

use rustmex_core::shim::{
	rustmex_get_cell as mxGetCell,
	rustmex_set_cell as mxSetCell,
	rustmex_create_cell_array as mxCreateCellArray,
};

use rustmex_core::classid::ClassID;

use rustmex_core::raw::{
	mwIndex,
	mwSize,
};
use rustmex_core::convert::{FromMatlabError};
use rustmex_core::{mxArray, pointers::{MxArray, MatlabPtr, MutMatlabPtr},};

use super::index::Index;

#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct CellArray<P: MatlabPtr>(P);

impl<'a> FromMatlab<'a> for CellArray<&'a mxArray> {
	fn from_matlab(mx: &'a mxArray) -> Result<Self, FromMatlabError> {
		if mx.class_id() == ClassID::Cell {
			Ok(Self(mx))
		} else {
			Err(FromMatlabError::BadClass)
		}
	}
}

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

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

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

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

impl<'a, P: MatlabPtr + 'a> CellArray<P> {
	/**
	 * Get the inner value of some cell in this array at a given index.
	 *
	 * This value may not yet be initialised, in which case this method returns
	 * `Ok(None)`. If the index is out of bounds, it returns
	 * `Err(CellError::OutOfBounds)`.
	 */
	pub fn get<I: Index>(&self, idx: I) -> Result<Option<&'a mxArray>, CellError> {
		Ok(self.get_core(idx)?.map(|ptr| unsafe { ptr.as_ref() }))
	}

	/// Shared behaviour for the get(_mut)? methods.
	///
	/// If this returns a None, it means that the particular cell was not initialised
	fn get_core<I: Index>(&self, idx: I) -> Result<Option<NonNull<mxArray>>, CellError> {
		let idx = idx.index_into(self).ok_or(CellError::OutOfBounds)?;

		Ok(NonNull::new(unsafe { mxGetCell(self.0.as_ref(), idx as mwIndex) }))
	}

	/**
	 * When one uses the "spread operator" in matlab on a cell array (i.e. `x{:}`) it
	 * produces a "comma separated list". This method is the Rustmex equivalent;
	 * collecting all of the mxArrays contained within the cell array into a [`Vec`],
	 * which can then be passed to other methods.
	 *
	 * If some of the cells are not initialised, this method returns None.
	 */
	// NOTE: I don't know whether it's wise to expose this.
	#[allow(unused)]
	fn comma_separated_list(&self) -> Option<Vec<&'a mxArray>> {
		(0..self.numel())
			.map(|idx| self.get(idx).unwrap())
			.collect()
	}
}

impl<'a, P: MutMatlabPtr + 'a> CellArray<P> {
	/// Get a mutable reference to a child mxArray
	pub fn get_mut<I: Index>(&mut self, idx: I) -> Result<Option<&'a mut mxArray>, CellError> {
		Ok(self.get_core(idx)?.map(|mut ptr| unsafe { ptr.as_mut() }))
	}

	/**
	 * Replace the current value of the cell at the given index, by optionally a new
	 * value. Returns the value that was there previously, if there was any.
	 */
	pub fn replace<I: Index>(&mut self, idx: I, mx: Option<MxArray>) -> Result<Option<MxArray>, CellError> {
		let idx = idx.index_into(self).ok_or(CellError::OutOfBounds)?;

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

		unsafe { mxSetCell(
				self.0.deref_mut(),
				idx as _,
				if let Some(val) = mx {
					MxArray::transfer_responsibility_ptr(val)
				} else {
					std::ptr::null_mut()
				}
			)
		}

		Ok(old)
	}

	/// Set the value at the given index. Returns the previous, if there was any.
	#[inline]
	pub fn set<I: Index>(&mut self, idx: I, mx: MxArray) -> Result<Option<MxArray>, CellError> {
		self.replace(idx, Some(mx))
	}

	/// Remove the value (if there is any) at the given index and return it, leaving the cell empty.
	#[inline]
	pub fn unset<I: Index>(&mut self, idx: I) -> Result<Option<MxArray>, CellError> {
		self.replace(idx, None)
	}
}

impl CellArray<MxArray> {
	pub fn new_mwsize(shape: &[mwSize]) -> 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"
		);

		let ptr = unsafe { mxCreateCellArray(
			shape.len(),
			shape.as_ptr(),
		)};

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

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

	/**
	 * Create a new cell array with the given fieldnames.
	 */
	pub fn new(shape: &[usize]) -> 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) })
	}

}