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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
mod inner_types {
    /// Iterates over a a PyTuple and returns a corresponding Rust tuple.
    ///
    /// When destructured all inner data is moved out of the tuple which will retain the structure
    /// but will point to PyArg::None variant, so is safe to assume the PyTuple as consumed.
    ///
    /// Inner containers (ie. `PyList<PyArg(T)>`) are converted to the respective Rust analog
    /// (ie. `Vec<T>`) and require valid syntax for their respective unpack macro (ie.
    /// [unpack_pylist!](../rustypy/macro.unpack_pylist!.html)).
    ///
    /// # Examples
    ///
    /// Unpack a PyTuple which contains a two PyDict types with PyString keys
    /// and values of PyList<i64>:
    ///
    /// ```
    /// # #[macro_use] extern crate rustypy;
    /// # fn main(){
    /// # use rustypy::{PyDict, PyList, PyTuple, PyArg, PyString};
    /// # use std::collections::HashMap;
    /// # let mut hm = HashMap::new();
    /// # hm.insert(PyString::from("one"), vec![0_i32, 1, 2]);
    /// # hm.insert(PyString::from("two"), vec![3_i32, 2, 1]);
    /// # let mut pytuple = pytuple!(PyArg::PyDict(PyDict::from(hm.clone()).into_raw()),
    /// #                            PyArg::PyDict(PyDict::from(hm.clone()).into_raw())).into_raw();
    /// // tuple from Python: ({"one": [0, 1, 3]}, {"two": [3, 2, 1]})
    /// let unpacked = unpack_pytuple!(pytuple; ({PyDict{(PyString, PyList{I32 => i64})}},
    ///                                          {PyDict{(PyString, PyList{I32 => i64})}},));
    /// # }
    /// ```
    ///
    #[macro_export]
    macro_rules! unpack_pytuple {
        // FIXME: produces clippy warning on macro expansion due to usage `cnt`
        ($t:ident; ($($p:tt,)+) ) => {{
            use rustypy::{PyArg, PyTuple};
            use rustypy::pytypes::abort_and_exit;

            let mut cnt = 0;
            let mut pytuple = unsafe { PyTuple::from_ptr($t) };
            ($(
                unpack_pytuple!(pytuple; cnt; elem: $p)
            ,)*)
        }};
        ($t:ident; $i:ident; elem: ($($p:tt,)+))  => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::PyTuple(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    let mut val = unsafe { PyTuple::from_ptr(val) };
                    let mut cnt = 0;
                    ($(
                        unpack_pytuple!(val; cnt; elem: $p)
                    ,)*)
                },
                _ => abort_and_exit("failed while extracting a PyTuple inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: {PyDict{$u:tt}}) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::PyDict(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    unpack_pydict!(val; PyDict{$u})
                },
                _ => abort_and_exit("failed while extracting a PyDict inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: {PyList{$($u:tt)*}}) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::PyList(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    unpack_pylist!(val; PyList{$($u)*})
                },
                _ => abort_and_exit("failed while extracting a PyList inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: PyBool) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::PyBool(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val.to_bool()
                },
                _ => abort_and_exit("failed while extracting a PyBool inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: PyString) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::PyString(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val.to_string()
                },
                _ => abort_and_exit("failed while extracting a PyString inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: I64) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::I64(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a i64 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: I32) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::I32(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val.clone()
                },
                _ => abort_and_exit("failed while extracting a i32 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: I16) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::I16(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a i16 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: I8) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::I8(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a i8 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: U32) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::U32(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a u32 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: U16) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::U16(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a u16 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: U8) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::U8(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a u8 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: F32) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::F32(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a f32 inside a PyTuple"),
            }
        }};
        ($t:ident; $i:ident; elem: F64) => {{
            let e = $t.replace_elem($i).unwrap();
            match e {
                PyArg::F64(val) => {
                    $i += 1;
                    if $i == 0 {}; // stub to remove warning...
                    val
                },
                _ => abort_and_exit("failed while extracting a f64 inside a PyTuple"),
            }
        }};
    }

    /// Consumes a `PyList<PyArg(T)>` content as recived from Python (raw pointer)
    /// and returns a `Vec<T>` from it, no copies are performed in the process.
    ///
    /// All inner elements are moved out if possible, if not (like with PyTuples) are copied.
    /// PyTuple variants are destructured into Rust tuples which contain the appropiate Rust types
    /// (valid syntax for [unpack_pytuple!](../rustypy/macro.unpack_pytuple!.html) macro must
    /// be provided). The same for other container types (inner PyList, PyDict, etc.).
    ///
    /// # Examples
    ///
    /// A simple PyList which contains PyString types::
    ///
    /// ```
    /// # #[macro_use] extern crate rustypy;
    /// # fn main(){
    /// use rustypy::{PyList, PyString};
    /// let string_list = PyList::from(vec!["Python", "in", "Rust"]).into_raw();
    /// let unpacked = unpack_pylist!(string_list; PyList{PyString => PyString});
    /// # }
    /// ```
    ///
    /// And an other with i32:
    ///
    /// ```
    /// # #[macro_use] extern crate rustypy;
    /// # fn main(){
    /// # use rustypy::PyList;
    /// # let int_list = PyList::from(vec![1i32; 5]).into_raw();
    /// // list from python: [1, 1, 1, 1, 1]
    /// let unpacked = unpack_pylist!(int_list; PyList{I32 => i32});
    /// # }
    /// ```
    ///
    /// It can contain nested containers. A PyList which contains PyTuples which contain a list
    /// of i64 PyTuples and a single f32:
    ///
    /// ```
    /// # #[macro_use] extern crate rustypy;
    /// # fn main(){
    /// #    use rustypy::{PyList, PyArg};
    /// #    let list = PyList::from(vec![
    /// #        pytuple!(PyArg::PyList(PyList::from(vec![
    /// #                    pytuple!(PyArg::I64(1), PyArg::I64(2), PyArg::I64(3))]).into_raw()),
    /// #                 PyArg::F32(0.1)),
    /// #        pytuple!(PyArg::PyList(PyList::from(vec![
    /// #                    pytuple!(PyArg::I64(3), PyArg::I64(2), PyArg::I64(1))]).into_raw()),
    /// #                 PyArg::F32(0.2))
    /// #        ]).into_raw();
    /// // list from Python: [([(i64; 3)], f32)]
    /// let unpacked = unpack_pylist!(list;
    ///     PyList{
    ///         PyTuple{(
    ///             {PyList{PyTuple{(I64, I64, I64,)}}}, F32,
    ///         )}
    ///     });
    /// assert_eq!(vec![(vec![(1, 2, 3,)], 0.1), (vec![(3, 2, 1,)], 0.2)], unpacked);
    /// # }
    /// ```
    ///
    #[macro_export]
    macro_rules! unpack_pylist {
        ( $pylist:ident; PyList { $o:tt { $($t:tt)* } } ) => {{
            use rustypy::{PyList, PyArg};
            use rustypy::pytypes::abort_and_exit;
            use std::collections::VecDeque;

            let mut unboxed = unsafe { PyList::from_ptr($pylist) };
            let mut list = VecDeque::with_capacity(unboxed.len());
            for _ in 0..unboxed.len() {
                match unboxed.pop() {
                    Some(PyArg::$o(val)) => {
                        let inner = unpack_pylist!(val; $o { $($t)* });
                        list.push_front(inner);
                    },
                    Some(_) => abort_and_exit("failed while converting pylist to vec"),
                    None => {}
                }
            };
            Vec::from(list)
        }};
        ( $pytuple:ident; PyTuple { $t:tt } ) => {{
            unpack_pytuple!($pytuple; $t)
        }};
        ( $pylist:ident; PyList{$t:tt => $type_:ty} ) => {{
            use rustypy::{PyList, PyArg};
            use rustypy::pytypes::abort_and_exit;
            use std::collections::VecDeque;

            let mut unboxed = unsafe { PyList::from_ptr($pylist) };
            let mut list = VecDeque::with_capacity(unboxed.len());
            for _ in 0..unboxed.len() {
                match unboxed.pop() {
                    Some(PyArg::$t(val)) => { list.push_front(<$type_>::from(val)); },
                    Some(_) => abort_and_exit("failed while converting pylist to vec"),
                    None => {}
                }
            };
            Vec::from(list)
        }};
        ( $pydict:ident; PyDict{$t:tt} ) => {{
            unpack_pydict!( $pydict; PyDict{$t} )
        }};
    }

    /// Consumes the content of a `PyDict<K, T>` as received from Python (raw pointer)
    /// and returns a `HashMap<K, T>` from it, no copies are performed in the process.
    ///
    /// All inner elements are moved out if possible, if not (like with PyTuples) are copied.
    /// PyTuple variants are destructured into Rust tuples which contain the appropiate Rust types
    /// (valid syntax for [unpack_pytuple!](../rustypy/macro.unpack_pytuple!.html) macro must
    /// be provided). The same happens with other container types (inner PyList, PyDict, etc.).
    ///
    /// # Examples
    ///
    /// A simple PyDict with i32 keys which contains PyString types::
    ///
    /// ```
    /// # #[macro_use] extern crate rustypy;
    /// # fn main(){
    /// # use std::iter::FromIterator;
    /// use rustypy::{PyDict, PyString};
    /// use std::collections::HashMap;
    ///
    /// let mut hm = HashMap::from_iter(vec![(0_i32, "Hello"), (1_i32, " "), (2_i32, "World!")]);
    /// let dict = PyDict::from(hm).into_raw();
    /// let unpacked = unpack_pydict!(dict; PyDict{(i32, PyString => String)});
    /// # }
    /// ```
    ///
    /// With nested container types:
    ///
    /// ```
    /// # #[macro_use] extern crate rustypy;
    /// # #[allow(unused_variables)]
    /// # fn main(){
    /// # use rustypy::{PyDict, PyString, PyArg};
    /// # use std::collections::HashMap;
    /// # let mut hm0 = HashMap::new();
    /// # for &(k, v) in &[(0_i32, "Hello"), (1, " "), (2, "World!")] {
    /// #     hm0.insert(k, v);
    /// # }
    /// # let mut hm1 = HashMap::new();
    /// # for i in 0..3_i64 {
    /// #     let k = format!("#{}", i);
    /// #     let v = PyArg::from(hm0.clone());
    /// #     let l = PyArg::from(vec![0_i64; 3]);
    /// #     hm1.insert(PyString::from(k), pytuple!(l, v));
    /// # }
    /// # let dict = PyDict::from(hm1).into_raw();
    /// // dict from Python: {str: ([u64], {i32: str})} as *mut size_t
    /// let unpacked = unpack_pydict!(dict;
    ///     PyDict{(PyString, PyTuple{({PyList{I64 => i64}},
    ///                                {PyDict{(i32, PyString => String)}},)})}
    ///     );
    /// # }
    /// ```
    ///
    #[macro_export]
    macro_rules! unpack_pydict {
        ( $pydict:ident; PyDict{($kt:ty, $o:tt { $($t:tt)* })} ) => {{
            use rustypy::{PyArg, PyDict};
            use rustypy::pytypes::abort_and_exit;
            use std::collections::HashMap;

            let mut unboxed = unsafe { *(Box::from_raw($pydict as *mut PyDict<$kt>)) };
            let mut dict = HashMap::new();
            for (k, v) in unboxed.drain() {
                match v {
                    PyArg::$o(val) => {
                        let inner = unpack_pydict!(val; $o { $($t)* });
                        dict.insert(k, inner);
                    }
                    _ => abort_and_exit("failed while converting PyDict to HashMap")
                }
            }
            dict
        }};
        ( $pytuple:ident; PyTuple { $t:tt } ) => {{
            unpack_pytuple!($pytuple; $t)
        }};
        ( $pylist:ident; PyList{ $($u:tt)* } ) => {{
            unpack_pylist!( $pylist; PyList{ $($u)* } )
        }};
        ( $pydict:ident; PyDict{($kt:ty, $t:tt => $type_:ty)} ) => {{
            use rustypy::{PyArg, PyDict};
            use rustypy::pytypes::abort_and_exit;
            use std::collections::HashMap;

            let mut unboxed = unsafe { *(Box::from_raw($pydict as *mut PyDict<$kt>)) };
            let mut dict = HashMap::new();
            for (k, v) in unboxed.drain() {
                match v {
                    PyArg::$t(val) => { dict.insert(k, <$type_>::from(val)); },
                    _ => abort_and_exit("failed while converting PyDict to HashMap"),
                }
            }
            dict
        }};
    }
}

/// Converts python data to `std` Rust collections or tuples, moving the data:
/// * Consumes the content of a `PyDict<K, T>` as received from Python (raw pointer)
///   and returns a `HashMap<K, T>` from it.
/// * Consumes a `PyList<PyArg(T)>` content as recived from Python (raw pointer)
///   and returns a `Vec<T>` from it.
/// * Iterates over a a PyTuple and returns a corresponding Rust tuple. Moves the data
///   leaving an empty PyTuple.
///
/// Inner containers (ie. `PyList<PyArg(T)>`) are converted to the respective Rust analog
/// (ie. `Vec<T>`)
///
/// # Examples
///
/// Unpack a PyTuple from Python:
///
/// ```
/// # #[macro_use] extern crate rustypy;
/// # fn main(){
/// # use rustypy::{PyDict, PyList, PyTuple, PyArg, PyString};
/// # use std::collections::HashMap;
/// # let mut hm = HashMap::new();
/// # hm.insert(PyString::from("one"), vec![0_i32, 1, 2]);
/// # hm.insert(PyString::from("two"), vec![3_i32, 2, 1]);
/// # let mut pytuple = pytuple!(PyArg::PyDict(PyDict::from(hm.clone()).into_raw()),
/// #                            PyArg::PyDict(PyDict::from(hm.clone()).into_raw())).into_raw();
/// // tuple from Python: ({"one": [0, 1, 3]}, {"two": [3, 2, 1]})
/// let unpacked = unpack_pytuple!(pytuple; ({PyDict{(PyString, PyList{I32 => i64})}},
///                                          {PyDict{(PyString, PyList{I32 => i64})}},));
/// # }
/// ```
///
/// Unpack a PyList from Python:
///
/// ```
/// # #[macro_use] extern crate rustypy;
/// # fn main(){
/// # use rustypy::PyList;
/// # let int_list = PyList::from(vec![1i32; 5]).into_raw();
/// // list from python: [1, 1, 1, 1, 1]
/// let unpacked = unpack_pytype!(int_list; PyList{I32 => i32});
/// # }
/// ```
///
/// Unpack a PyDict from Python:
///
/// ```
/// # #[macro_use] extern crate rustypy;
/// # fn main(){
/// # use std::iter::FromIterator;
/// # use rustypy::{PyDict, PyString};
/// # use std::collections::HashMap;
/// #
/// # let mut hm = HashMap::from_iter(vec![(0_i32, "Hello"), (1_i32, " "), (2_i32, "World!")]);
/// # let dict = PyDict::from(hm).into_raw();
/// let unpacked = unpack_pytype!(dict; PyDict{(i32, PyString => String)});
/// # }
/// ```
///
/// You can combine different containers and nest them:
///
/// ```
/// # #[macro_use] extern crate rustypy;
/// # #[allow(unused_variables)]
/// # fn main(){
/// # use rustypy::{PyDict, PyString, PyArg};
/// # use std::collections::HashMap;
/// # let mut hm0 = HashMap::new();
/// # for &(k, v) in &[(0_i32, "Hello"), (1, " "), (2, "World!")] {
/// #     hm0.insert(k, v);
/// # }
/// # let mut hm1 = HashMap::new();
/// # for i in 0..3_i64 {
/// #     let k = format!("#{}", i);
/// #     let v = PyArg::from(hm0.clone());
/// #     let l = PyArg::from(vec![0_i64; 3]);
/// #     hm1.insert(PyString::from(k), pytuple!(l, v));
/// # }
/// # let dict = PyDict::from(hm1).into_raw();
/// // dict from Python: {str: ([u64], {i32: str})} as *mut size_t
/// let unpacked = unpack_pytype!(dict;
///     PyDict{(PyString, PyTuple{({PyList{I64 => i64}},
///                                {PyDict{(i32, PyString => String)}},)})}
///     );
/// # }
/// ```
#[macro_export]
macro_rules! unpack_pytype {
    ($t:ident; ($($p:tt,)+)) => {
        unpack_pytuple!($t; ($($p,)*))
    };
    ($pylist:ident; PyList{$t:tt => $type_:ty}) => {
        unpack_pylist!($pylist; PyList{$t => $type_})
    };
    ($pylist:ident; PyList { $o:tt { $($t:tt)* } }) => {
        unpack_pylist!($pylist; PyList { $o { $($t)* } })
    };
    ($pydict:ident; PyDict{($kt:ty, $o:tt { $($t:tt)* })}) => {
        unpack_pydict!($pydict; PyDict{($kt, $o { $($t)* })})
    };
    ($pydict:ident; PyDict{($kt:ty, $t:tt => $type_:ty)}) => {
        unpack_pydict!($pydict; PyDict{($kt, $t => $type_)})
    };
}

#[cfg(test)]
mod tests {
    use crate as rustypy;
    use rustypy::*;

    #[test]
    fn pytuple_macro() {
        let pytuple = pytuple!(
            PyArg::PyBool(PyBool::from(false)),
            PyArg::PyString(PyString::from("test")),
            PyArg::I64(55i64)
        )
        .into_raw();
        let unpacked = unpack_pytype!(pytuple; (PyBool, PyString, I64,));
        assert_eq!((false, String::from("test"), 55i64), unpacked);
    }

    #[test]
    fn unpack_pylist_macro() {
        use std::iter::FromIterator;
        let nested = PyList::from_iter(vec![
            pytuple!(
                PyArg::PyList(PyList::from_iter(vec![1i32, 2, 3]).into_raw()),
                PyArg::F32(0.1)
            ),
            pytuple!(
                PyArg::PyList(PyList::from_iter(vec![3i32, 2, 1]).into_raw()),
                PyArg::F32(0.2)
            ),
        ])
        .into_raw();
        let unpacked = unpack_pytype!(nested; PyList{PyTuple{({PyList{I32 => i32}}, F32,)}});
        assert_eq!(vec![(vec![1, 2, 3], 0.1), (vec![3, 2, 1], 0.2)], unpacked);
    }
}