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
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

/// A macro for easier writing of functions that accept any string-, path-, iterator-, array-, or ndarray-like input.
/// The AnyInputs are `AnyString`, `AnyPath`, `AnyIter`, `AnyArray`, and (optionally) `AnyNdArray`.
///
/// See the [documentation](https://docs.rs/anyinput/) for for details.
///
/// # Example
/// ```
/// use anyinput::anyinput;
/// use anyhow::Result;
///
/// #[anyinput]
/// fn len_plus_2(s: AnyString) -> Result<usize, anyhow::Error> {
///     Ok(s.len()+2)
/// }
///
/// // By using AnyString, len_plus_2 works with
/// // &str, String, or &String -- borrowed or moved.
/// assert_eq!(len_plus_2("Hello")?, 7); // move a &str
/// let input: &str = "Hello";
/// assert_eq!(len_plus_2(&input)?, 7); // borrow a &str
/// let input: String = "Hello".to_string();
/// assert_eq!(len_plus_2(&input)?, 7); // borrow a String
/// let input2: &String = &input;
/// assert_eq!(len_plus_2(&input2)?, 7); // borrow a &String
/// assert_eq!(len_plus_2(input2)?, 7); // move a &String
/// assert_eq!(len_plus_2(input)?, 7); // move a String
/// # // '# OK...' needed for doctest
/// # Ok::<(), anyhow::Error>(())
/// ```
pub use anyinput_derive::anyinput;

#[cfg(test)]
mod tests {

    use crate::anyinput;
    use std::path::PathBuf;

    #[test]
    fn one_input() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_str_len1(s: AnyString) -> Result<usize, anyhow::Error> {
            let len = s.len();
            Ok(len)
        }
        assert!(any_str_len1("123")? == 3);
        Ok(())
    }

    #[test]
    fn two_inputs() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_str_len2(a: AnyString, b: AnyString) -> Result<usize, anyhow::Error> {
            let len = a.len() + b.len();
            Ok(len)
        }
        let s = "Hello".to_string();
        assert!(any_str_len2("123", s)? == 8);
        Ok(())
    }

    #[test]
    fn zero_inputs() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_str_len0() -> Result<usize, anyhow::Error> {
            let len = 0;
            Ok(len)
        }
        assert!(any_str_len0()? == 0);
        Ok(())
    }

    #[test]
    fn one_plus_two_input() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_str_len1plus2(a: usize, s: AnyString, b: usize) -> Result<usize, anyhow::Error> {
            let len = s.len() + a + b;
            Ok(len)
        }
        assert!(any_str_len1plus2(1, "123", 2)? == 6);
        Ok(())
    }

    #[test]
    fn one_path_input() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_count_path(p: AnyPath) -> Result<usize, anyhow::Error> {
            let count = p.iter().count();
            Ok(count)
        }
        assert!(any_count_path(PathBuf::from("one/two/three"))? == 3);
        Ok(())
    }

    #[test]
    fn one_iter_usize_input() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_count_iter(i: AnyIter<usize>) -> Result<usize, anyhow::Error> {
            let count = i.count();
            Ok(count)
        }
        assert_eq!(any_count_iter([1, 2, 3])?, 3);
        Ok(())
    }

    #[test]
    fn one_iter_i32() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_count_iter(i: AnyIter<i32>) -> Result<usize, anyhow::Error> {
            let count = i.count();
            Ok(count)
        }
        assert_eq!(any_count_iter([1, 2, 3])?, 3);
        Ok(())
    }

    #[test]
    fn one_iter_t() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_count_iter<T>(i: AnyIter<T>) -> Result<usize, anyhow::Error> {
            let count = i.count();
            Ok(count)
        }
        assert_eq!(any_count_iter([1, 2, 3])?, 3);
        Ok(())
    }

    #[test]
    fn one_iter_path() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_count_iter(i: AnyIter<AnyPath>) -> Result<usize, anyhow::Error> {
            let sum_count = i.map(|x| x.as_ref().iter().count()).sum();
            Ok(sum_count)
        }
        assert_eq!(any_count_iter(["a/b", "d"])?, 3);
        Ok(())
    }

    #[test]
    fn one_vec_path() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_count_vec(i: Vec<AnyPath>) -> Result<usize, anyhow::Error> {
            let sum_count = i.iter().map(|x| x.as_ref().iter().count()).sum();
            Ok(sum_count)
        }
        assert_eq!(any_count_vec(vec!["a/b", "d"])?, 3);
        Ok(())
    }

    #[cfg(feature = "ndarray")]
    #[test]
    fn one_array_usize_input() -> Result<(), anyhow::Error> {
        #[anyinput]
        pub fn any_array_len(a: AnyArray<usize>) -> Result<usize, anyhow::Error> {
            let len = a.len();
            Ok(len)
        }
        assert_eq!(any_array_len([1, 2, 3])?, 3);
        Ok(())
    }

    #[cfg(feature = "ndarray")]
    #[test]
    fn one_ndarray_usize_input() -> Result<(), anyhow::Error> {
        use ndarray;

        #[anyinput]
        pub fn any_array_len(a: AnyNdArray<usize>) -> Result<usize, anyhow::Error> {
            let len = a.len();
            Ok(len)
        }
        assert_eq!(any_array_len([1, 2, 3].as_ref())?, 3);
        Ok(())
    }

    #[cfg(feature = "ndarray")]
    #[test]
    fn complex() -> Result<(), anyhow::Error> {
        use ndarray;

        #[anyinput]
        pub fn complex_total(
            a: usize,
            b: AnyIter<Vec<AnyArray<AnyPath>>>,
            c: AnyNdArray<usize>,
        ) -> Result<usize, anyhow::Error> {
            let mut total = a + c.sum();
            for vec in b {
                for any_array in vec {
                    let any_array = any_array.as_ref();
                    for any_path in any_array.iter() {
                        let any_path = any_path.as_ref();
                        total += any_path.iter().count();
                    }
                }
            }
            Ok(total)
        }
        assert_eq!(complex_total(17, [vec![["one"]]], [1, 2, 3].as_ref())?, 24);
        Ok(())
    }

    #[test]
    #[cfg(feature = "ndarray")]
    fn doc_ndarray() -> Result<(), anyhow::Error> {
        use anyhow::Result;
        use ndarray;

        #[anyinput]
        fn any_mean(array: AnyNdArray<f32>) -> Result<f32, anyhow::Error> {
            if let Some(mean) = array.mean() {
                Ok(mean)
            } else {
                Err(anyhow::anyhow!("empty array"))
            }
        }

        // 'AnyNdArray' works with any 1-D array-like thing, but must be borrowed.
        assert_eq!(any_mean(&[10.0, 20.0, 30.0, 40.0])?, 25.0);
        assert_eq!(any_mean(&ndarray::array![10.0, 20.0, 30.0, 40.0])?, 25.0);

        Ok(())
    }

    #[test]
    fn doc_path() -> Result<(), anyhow::Error> {
        use crate::anyinput;
        use anyhow::Result;
        use std::path::Path;

        #[anyinput]
        fn component_count(path: AnyPath) -> Result<usize, anyhow::Error> {
            let count = path.iter().count();
            Ok(count)
        }

        // By using AnyPath, component_count works with any
        // string-like or path-like thing, borrowed or moved.
        assert_eq!(component_count("usr/files/home")?, 3);
        let path = Path::new("usr/files/home");
        let pathbuf = path.to_path_buf();
        assert_eq!(component_count(&path)?, 3);
        assert_eq!(component_count(pathbuf)?, 3);

        Ok(())
    }

    #[test]
    fn doc_iter() -> Result<(), anyhow::Error> {
        use crate::anyinput;
        use anyhow::Result;

        #[anyinput]
        fn two_iterator_sum(
            iter1: AnyIter<usize>,
            iter2: AnyIter<AnyString>,
        ) -> Result<usize, anyhow::Error> {
            let mut sum = iter1.sum();
            for any_string in iter2 {
                // Needs .as_ref to turn the nested AnyString into a &str.
                sum += any_string.as_ref().len();
            }
            Ok(sum)
        }
        assert_eq!(two_iterator_sum(1..=10, ["a", "bb", "ccc"])?, 61);
        Ok(())
    }

    #[test]
    fn doc_array() -> Result<(), anyhow::Error> {
        use crate::anyinput;
        use anyhow::Result;

        #[anyinput]
        fn indexed_component_count(
            array: AnyArray<AnyPath>,
            index: usize,
        ) -> Result<usize, anyhow::Error> {
            // Needs .as_ref to turn the nested AnyPath into a &Path.
            let path = array[index].as_ref();
            let count = path.iter().count();
            Ok(count)
        }
        assert_eq!(
            indexed_component_count(vec!["usr/files/home", "usr/data"], 1)?,
            2
        );
        Ok(())
    }

    #[test]
    #[cfg(feature = "ndarray")]
    fn doc_ndarray2() -> Result<(), anyhow::Error> {
        use crate::anyinput;
        use anyhow::Result;
        use ndarray;

        #[anyinput]
        fn any_mean(array: AnyNdArray<f32>) -> Result<f32, anyhow::Error> {
            if let Some(mean) = array.mean() {
                Ok(mean)
            } else {
                Err(anyhow::anyhow!("empty array"))
            }
        }

        // 'AnyNdArray' works with any 1-D array-like thing, but must be borrowed.
        assert_eq!(any_mean(&[10.0, 20.0, 30.0, 40.0])?, 25.0);
        assert_eq!(any_mean(&ndarray::array![10.0, 20.0, 30.0, 40.0])?, 25.0);
        Ok(())
    }

    #[test]
    fn more_path() -> Result<(), anyhow::Error> {
        use crate::anyinput;
        use anyhow::Result;
        use std::path::Path;

        fn component_count1(path: impl AsRef<Path>) -> Result<usize, anyhow::Error> {
            let path = path.as_ref();
            Ok(path.iter().count())
        }
        assert_eq!(component_count1("usr/files/home")?, 3);

        #[anyinput]
        fn component_count2(path: AnyPath) -> Result<usize, anyhow::Error> {
            Ok(path.iter().count())
        }
        assert_eq!(component_count2("usr/files/home")?, 3);

        Ok(())
    }

    #[test]
    fn more_string() -> Result<(), anyhow::Error> {
        use std::borrow::Borrow;

        pub fn len_plus_2(s: impl Borrow<str>) -> usize {
            s.borrow().len() + 2
        }

        assert_eq!(len_plus_2("Hello"), 7); // move a &str
                                            // let input: &str = "Hello";
                                            // assert_eq!(len_plus_2(&input), 7); // borrow a &str
                                            // let input: String = "Hello".to_string();
                                            // assert_eq!(len_plus_2(&input), 7); // borrow a String
                                            // let input2: &String = &input;
                                            // assert_eq!(len_plus_2(&input2), 7); // borrow a &String
                                            // assert_eq!(len_plus_2(input2), 7); // move a &String
                                            // assert_eq!(len_plus_2(input), 7); // move a String
        Ok(())
    }

    #[test]
    fn more_iter() -> Result<(), anyhow::Error> {
        use crate::anyinput;
        use std::borrow::Borrow;

        pub fn two_iterator_sum(
            iter1: impl IntoIterator<Item = usize>,
            iter2: impl IntoIterator<Item = impl Borrow<str>>,
        ) -> usize {
            let mut sum = iter1.into_iter().sum();

            for string in iter2 {
                sum += string.borrow().len();
            }

            sum
        }

        two_iterator_sum(1..=10, ["a", "bb", "ccc"]);
        let s0 = "bb".to_string();
        // two_iterator_sum(1..=10, [&s0]);

        #[anyinput]
        pub fn two_iterator_sum2(iter1: AnyIter<usize>, iter2: AnyIter<AnyString>) -> usize {
            let mut sum = iter1.sum();

            for string in iter2 {
                sum += string.as_ref().len();
            }

            sum
        }
        two_iterator_sum2(1..=10, [&s0]);

        Ok(())
    }

    #[test]
    fn more_iter2() -> Result<(), anyhow::Error> {
        use crate::anyinput;

        #[anyinput]
        fn iid0(iid: AnyIter<AnyString>) -> usize {
            let mut sum = 0;
            for s in iid {
                sum += s.as_ref().len();
            }
            sum
        }

        fn iid1<I: IntoIterator<Item = T>, T: AsRef<str>>(iid: I) -> usize {
            let mut sum = 0;
            for s in iid {
                sum += s.as_ref().len();
            }
            sum
        }

        fn iid2<I: IntoIterator>(iid: I) -> usize
        where
            <I as IntoIterator>::Item: AsRef<str>,
        {
            let mut sum = 0;
            for s in iid {
                sum += s.as_ref().len();
            }
            sum
        }

        //let fa = iid0;

        assert_eq!(iid0::<&str, [&str; 3]>(["a", "bb", "ccc"]), 6);

        // assert_eq!(iid0::<_, _>(["a", "bb", "ccc"]), 6);
        assert_eq!(iid1::<[&str; 3], &str>(["a", "bb", "ccc"]), 6);
        assert_eq!(iid2::<[&str; 3]>(["a", "bb", "ccc"]), 6);
        assert_eq!(iid1(["a", "bb", "ccc"]), 6);
        assert_eq!(iid2(["a", "bb", "ccc"]), 6);

        Ok(())
    }

    // todo make this a real test
    // #[test]
    // fn misapply() -> Result<(), anyhow::Error> {
    //     use crate::anyinput;

    //     #[anyinput]
    //     struct Test {
    //         a: AnyString,
    //         b: AnyString,
    //     }
    //     Ok(())
    // }

    // todo should their be a warning/error if there is no Anyinput on a function to which this has been applied?
    // todo must test badly-formed functions to see that the error messages make sense.
}