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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
//! This crate provides a `Vec` wrapper (`Vec1`) which guarantees to have at least 1 element.
//!
//! This can be useful if you have a API which accepts one ore more ofe a kind.
//! Instead of accepting a `Vec` and returning an error if it's empty a `Vec1`
//! can be used assuring there is at least 1 element and through this reducing
//! the number of possible error causes.
//!
//! The crate provides an optional `serde` feature, which provides
//! implementations of `serde::Serialize`/`serde::Deserialize`.
//!
//! # Example
//!
//! ```
//! #[macro_use]
//! extern crate vec1;
//!
//! use vec1::Vec1;
//!
//! fn main() {
//!     // vec1![] makes sure at compiler time
//!     // there is at least one element
//!     //let names = vec1! [ ];
//!     let names = vec1! [ "Liz" ];
//!     greet(names);
//! }
//!
//! fn greet(names: Vec1<&str>) {
//!     // methods like first/last which return a Option on Vec do
//!     // directly return the value, we know it's possible
//!     let first = names.first();
//!     println!("hallo {}", first);
//!     for name in names.iter().skip(1) {
//!         println!("  who is also know as {}", name)
//!     }
//! }
//!
//! ```
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde;
#[cfg(all(feature = "serde", test))]
extern crate serde_json;

use std::borrow::{Borrow, BorrowMut};
use std::error::Error as StdError;
use std::iter::{Extend, IntoIterator};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::result::Result as StdResult;
use std::{fmt, slice, vec};

/// A macro similar to `vec!` to create a `Vec1`.
///
/// If it is called with less then 1 element a
/// compiler error is triggered (using `compile_error`
/// to make sure you know what went wrong).
#[macro_export]
macro_rules! vec1 {
    () => (
        compile_error!("Vec1 needs at least 1 element")
    );
    ($first:expr) => (
         $crate::Vec1::new($first)
    );
    ($first:expr,) => (
         $crate::Vec1::new($first)
    );
    ($first:expr, $($item:expr),*) => ({
        let mut tmp = $crate::Vec1::new($first);
        $(tmp.push($item);)*
        tmp
    });
}

/// Error returned by operations which would cause `Vec1` to have a length of 0.
#[derive(Debug, Hash, Eq, PartialEq, Copy, Clone)]
pub struct Size0Error;

impl fmt::Display for Size0Error {
    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        write!(fter, "{}", self.description())
    }
}
impl StdError for Size0Error {
    fn description(&self) -> &str {
        "Cannot produce a Vec1 with a length of zero."
    }
}

type Vec1Result<T> = StdResult<T, Size0Error>;

/// `std::vec::Vec` wrapper which guarantees to have at least 1 element.
///
/// `Vec1<T>` dereferences to `&[T]` and `&mut [T]` as functionality
/// exposed through this can not change the length.
///
/// Methods of `Vec` which can be called without reducing the length
/// (e.g. `capacity()`, `reserve()`) are exposed through wrappers
/// with the same function signature.
///
/// Methods of `Vec` which could reduce the length to 0
/// are implemented with a `try_` prefix returning a `Result`.
/// (e.g. `try_pop(&self)`, `try_truncate()`, etc.).
///
/// Methods with returned `Option<T>` with `None` if the length was 0
/// (and do not reduce the length) now return T. (e.g. `first`,
/// `last`, `first_mut`, etc.).
///
/// All stable traits and methods implemented on `Vec<T>` _should_ also
/// be implemented on `Vec1<T>` (except if they make no sense to implement
/// due to the len 1 gurantee). Note that some small thinks are still missing
/// e.g. `Vec1` does not implement drain currently as drains generic argument
/// is `R: RangeArgument<usize>` and `RangeArgument` is not stable.
#[derive(Debug, Clone, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Vec1<T>(Vec<T>);

impl<T> IntoIterator for Vec1<T> {
    type Item = T;
    type IntoIter = vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<T> Vec1<T> {

    /// Creates a new `Vec1` instance containing a single element.
    ///
    /// This is roughly `Vec1(vec![first])`.
    pub fn new(first: T) -> Self {
        Vec1(vec![first])
    }

    /// Tries to create a `Vec1<T>` from a `Vec<T>`.
    ///
    /// The fact that the input is returned _as error_ if it's empty,
    /// means that it doesn't work well with the `?` operator. It naming
    /// is also semantic sub-optimal as it's not a "from" but "try from"
    /// conversion. Which is why this method is now deprecated. Instead
    /// use `try_from_vec` and once `TryFrom` is stable it will be possible
    /// to use `try_from`, too.
    ///
    /// # Errors
    ///
    /// If the input is empty the input is returned _as error_.
    #[deprecated(since="1.2.0", note="does not work with `?` use Vec1::try_from_vec() instead")]
    pub fn from_vec(vec: Vec<T>) -> StdResult<Self, Vec<T>> {
        if vec.is_empty() {
            Err(vec)
        } else {
            Ok(Vec1(vec))
        }
    }

    /// Tries to create a `Vec1<T>` from a normal `Vec<T>`.
    ///
    /// # Errors
    ///
    /// This will fail if the input `Vec<T>` is empty.
    /// The returned error is a `Size0Error` instance, as
    /// such this means the _input vector will be dropped if
    /// it's empty_. But this is normally fine as it only
    /// happens if the `Vec<T>` is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use vec1::Vec1;
    /// let vec1 = Vec1::try_from_vec(vec![1u8, 2, 3])
    ///     .unwrap();
    /// assert_eq!(vec1, vec![1u8, 2, 3]);
    /// ```
    ///
    /// If you need to return a `Option<Vec1<T>>` you
    /// can use `.ok()` on the returned result:
    ///
    /// ```
    /// # use vec1::Vec1;
    /// fn foobar(input: Vec<u8>) -> Option<Vec1<u8>> {
    ///     let mut res = Vec1::try_from_vec(input).ok()?;
    ///     for x in res.iter_mut() {
    ///         *x *= 2;
    ///     }
    ///     Some(res)
    /// }
    /// ```
    pub fn try_from_vec(vec: Vec<T>) -> Vec1Result<Self> {
        if vec.is_empty() {
            Err(Size0Error)
        } else {
            Ok(Vec1(vec))
        }
    }

    /// Creates a new `Vec1` with a given capacity and a given "first" element.
    pub fn with_capacity(first: T, capacity: usize) -> Self {
        let mut vec = Vec::with_capacity(capacity);
        vec.push(first);
        Vec1(vec)
    }

    /// Turns this `Vec1` into a `Vec`.
    pub fn into_vec(self) -> Vec<T> {
        self.0
    }

    /// Create a new `Vec1` by consuming `self` and mapping each element.
    ///
    /// This is useful as it keeps the knowledge that the length is >= 1,
    /// even through the old `Vec1` is consumed and turned into an iterator.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate vec1;
    /// # use vec1::Vec1;
    /// # fn main() {
    /// let data = vec1![1u8,2,3];
    ///
    /// let data = data.mapped(|x|x*2);
    /// assert_eq!(data, vec![2,4,6]);
    ///
    /// // without mapped
    /// let data = Vec1::try_from_vec(data.into_iter().map(|x|x*2).collect::<Vec<_>>()).unwrap();
    /// assert_eq!(data, vec![4,8,12]);
    /// # }
    /// ```
    pub fn mapped<F, N>(self, map_fn: F) -> Vec1<N>
    where
        F: FnMut(T) -> N,
    {
        Vec1(self.into_iter().map(map_fn).collect::<Vec<_>>())
    }

    /// Create a new `Vec1` by mapping references to the elements of `self`.
    ///
    /// The benefit to this compared to `Iterator::map` is that it's known
    /// that the length will still be at least 1 when creating the new `Vec1`.
    pub fn mapped_ref<F, N>(&self, map_fn: F) -> Vec1<N>
    where
        F: FnMut(&T) -> N,
    {
        Vec1(self.iter().map(map_fn).collect::<Vec<_>>())
    }

    /// Create a new `Vec1` by mapping mutable references to the elements of `self`.
    ///
    /// The benefit to this compared to `Iterator::map` is that it's known
    /// that the length will still be at least 1 when creating the new `Vec1`.
    pub fn mapped_mut<F, N>(&mut self, map_fn: F) -> Vec1<N>
    where
        F: FnMut(&mut T) -> N,
    {
        Vec1(self.iter_mut().map(map_fn).collect::<Vec<_>>())
    }

    /// Create a new `Vec1` by consuming `self` and mapping each element
    /// to a `Result`.
    ///
    /// This is useful as it keeps the knowledge that the length is >= 1,
    /// even through the old `Vec1` is consumed and turned into an iterator.
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate vec1;
    /// # use vec1::Vec1;
    /// # fn main() {
    /// let data = vec1![1,2,3];
    ///
    /// let data: Result<Vec1<u8>, &'static str> = data.try_mapped(|x| Err("failed"));
    /// assert_eq!(data, Err("failed"));
    /// # }
    /// ```
    pub fn try_mapped<F, N, E>(self, map_fn: F) -> Result<Vec1<N>, E>
    where
        F: FnMut(T) -> Result<N, E>,
    {
        let mut map_fn = map_fn;
        // ::collect<Result<Vec<_>>>() is uses the iterators size hint's lower bound
        // for with_capacity, which is 0 as it might fail at the first element
        let mut out = Vec::with_capacity(self.len());
        for element in self.into_iter() {
            out.push(map_fn(element)?);
        }
        Ok(Vec1(out))
    }

    /// Create a new `Vec1` by mapping references to the elements of `self`
    /// to `Result`s.
    ///
    /// The benefit to this compared to `Iterator::map` is that it's known
    /// that the length will still be at least 1 when creating the new `Vec1`.
    pub fn try_mapped_ref<F, N, E>(&self, map_fn: F) -> Result<Vec1<N>, E>
    where
        F: FnMut(&T) -> Result<N, E>,
    {
        let mut map_fn = map_fn;
        let mut out = Vec::with_capacity(self.len());
        for element in self.iter() {
            out.push(map_fn(element)?);
        }
        Ok(Vec1(out))
    }

    /// Create a new `Vec1` by mapping mutable references to the elements of
    /// `self` to `Result`s.
    ///
    /// The benefit to this compared to `Iterator::map` is that it's known
    /// that the length will still be at least 1 when creating the new `Vec1`.
    pub fn try_mapped_mut<F, N, E>(&mut self, map_fn: F) -> Result<Vec1<N>, E>
    where
        F: FnMut(&mut T) -> Result<N, E>,
    {
        let mut map_fn = map_fn;
        let mut out = Vec::with_capacity(self.len());
        for element in self.iter_mut() {
            out.push(map_fn(element)?);
        }
        Ok(Vec1(out))
    }

    /// Returns a reference to the last element.
    ///
    /// As `Vec1` always contains at least one element there is always a last element.
    pub fn last(&self) -> &T {
        //UNWRAP_SAFE: len is at least 1
        self.0.last().unwrap()
    }

    /// Returns a mutable reference to the last element.
    ///
    /// As `Vec1` always contains at least one element there is always a last element.
    pub fn last_mut(&mut self) -> &mut T {
        //UNWRAP_SAFE: len is at least 1
        self.0.last_mut().unwrap()
    }

    /// Returns a reference to the first element.
    ///
    /// As `Vec1` always contains at least one element there is always a first element.
    pub fn first(&self) -> &T {
        //UNWRAP_SAFE: len is at least 1
        self.0.first().unwrap()
    }

    /// Returns a mutable reference to the first element.
    ///
    /// As `Vec1` always contains at least one element there is always a first element.
    pub fn first_mut(&mut self) -> &mut T {
        //UNWRAP_SAFE: len is at least 1
        self.0.first_mut().unwrap()
    }

    pub fn try_truncate(&mut self, len: usize) -> Vec1Result<()> {
        if len > 0 {
            self.0.truncate(len);
            Ok(())
        } else {
            Err(Size0Error)
        }
    }

    pub fn try_swap_remove(&mut self, index: usize) -> Vec1Result<T> {
        if self.len() > 1 {
            Ok(self.0.swap_remove(index))
        } else {
            Err(Size0Error)
        }
    }

    pub fn try_remove(&mut self, index: usize) -> Vec1Result<T> {
        if self.len() > 1 {
            Ok(self.0.remove(index))
        } else {
            Err(Size0Error)
        }
    }

    pub fn try_split_off(&mut self, at: usize) -> Vec1Result<Vec1<T>> {
        if at == 0 {
            Err(Size0Error)
        } else if at >= self.len() {
            Err(Size0Error)
        } else {
            let out = self.0.split_off(at);
            Ok(Vec1(out))
        }
    }

    pub fn dedup_by_key<F, K>(&mut self, key: F)
    where
        F: FnMut(&mut T) -> K,
        K: PartialEq<K>,
    {
        self.0.dedup_by_key(key)
    }

    pub fn dedup_by<F>(&mut self, same_bucket: F)
    where
        F: FnMut(&mut T, &mut T) -> bool,
    {
        self.0.dedup_by(same_bucket)
    }

    /// Tries to remove the last element from the `Vec1`.
    ///
    /// Returns an error if the length is currently 1 (so the `try_pop` would reduce
    /// the length to 0).
    pub fn try_pop(&mut self) -> Vec1Result<T> {
        if self.len() > 1 {
            //UNWRAP_SAFE: pop on len > 1 can not be none
            Ok(self.0.pop().unwrap())
        } else {
            Err(Size0Error)
        }
    }

    pub fn as_vec(&self) -> &Vec<T> {
        &self.0
    }
}

macro_rules! impl_wrapper {
    (pub $T:ident>
        $(fn $name:ident(&$($m:ident)* $(, $param:ident: $tp:ty)*) -> $rt:ty);*) => (
            impl<$T> Vec1<$T> {$(
                #[inline]
                pub fn $name(self: impl_wrapper!{__PRIV_SELF &$($m)*} $(, $param: $tp)*) -> $rt {
                    (self.0).$name($($param),*)
                }
            )*}
    );
    (__PRIV_SELF &mut self) => (&mut Self);
    (__PRIV_SELF &self) => (&Self);
}

// methods in Vec not in &[] which can be directly exposed
impl_wrapper! {
    pub T>
        fn reserve(&mut self, additional: usize) -> ();
        fn reserve_exact(&mut self, additional: usize) -> ();
        fn shrink_to_fit(&mut self) -> ();
        fn as_mut_slice(&mut self) -> &mut [T];
        fn push(&mut self, value: T) -> ();
        fn append(&mut self, other: &mut Vec<T>) -> ();
        fn insert(&mut self, idx: usize, val: T) -> ();
        fn len(&self) -> usize;
        fn capacity(&self) -> usize;
        fn as_slice(&self) -> &[T]
}

impl<T> Vec1<T>
where
    T: Clone,
{
    pub fn try_resize(&mut self, new_len: usize, value: T) -> Vec1Result<()> {
        if new_len >= 1 {
            Ok(self.0.resize(new_len, value))
        } else {
            Err(Size0Error)
        }
    }

    pub fn extend_from_slice(&mut self, other: &[T]) {
        self.0.extend_from_slice(other)
    }
}

impl<T> Vec1<T>
where
    T: PartialEq<T>,
{
    pub fn dedub(&mut self) {
        self.0.dedup()
    }
}

impl<T> Vec1<T>
where
    T: PartialEq<T>,
{
    pub fn dedup(&mut self) {
        self.0.dedup()
    }
}

impl<T> Deref for Vec1<T> {
    type Target = [T];

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

impl<T> DerefMut for Vec1<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> Into<Vec<T>> for Vec1<T> {
    fn into(self) -> Vec<T> {
        self.0
    }
}

impl<A, B> PartialEq<Vec1<B>> for Vec1<A>
where
    A: PartialEq<B>,
{
    fn eq(&self, other: &Vec1<B>) -> bool {
        self.0.eq(&other.0)
    }
}

impl<A, B> PartialEq<B> for Vec1<A>
where
    Vec<A>: PartialEq<B>,
{
    fn eq(&self, other: &B) -> bool {
        self.0.eq(other)
    }
}

impl<T, O, R> Index<R> for Vec1<T>
where
    Vec<T>: Index<R, Output = O>,
    O: ?Sized,
{
    type Output = O;

    fn index(&self, index: R) -> &O {
        self.0.index(index)
    }
}

impl<T, O, R> IndexMut<R> for Vec1<T>
where
    Vec<T>: IndexMut<R, Output = O>,
    O: ?Sized,
{
    fn index_mut(&mut self, index: R) -> &mut Self::Output {
        self.0.index_mut(index)
    }
}

impl<T> Borrow<[T]> for Vec1<T> {
    fn borrow(&self) -> &[T] {
        self
    }
}

impl<T> BorrowMut<[T]> for Vec1<T> {
    fn borrow_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T> Borrow<Vec<T>> for Vec1<T> {
    fn borrow(&self) -> &Vec<T> {
        &self.0
    }
}

impl<'a, T> Extend<&'a T> for Vec1<T>
where
    T: 'a + Copy,
{
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = &'a T>,
    {
        self.0.extend(iter)
    }
}

impl<T> Extend<T> for Vec1<T> {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.0.extend(iter)
    }
}

impl<T> AsRef<[T]> for Vec1<T> {
    fn as_ref(&self) -> &[T] {
        self
    }
}

impl<T> AsMut<[T]> for Vec1<T> {
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T> AsRef<Vec<T>> for Vec1<T> {
    fn as_ref(&self) -> &Vec<T> {
        &self.0
    }
}
impl<T> AsRef<Vec1<T>> for Vec1<T> {
    fn as_ref(&self) -> &Vec1<T> {
        self
    }
}

impl<T> AsMut<Vec1<T>> for Vec1<T> {
    fn as_mut(&mut self) -> &mut Vec1<T> {
        self
    }
}

impl<'a, T> IntoIterator for &'a Vec1<T> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}
impl<'a, T> IntoIterator for &'a mut Vec1<T> {
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}

#[cfg(feature = "serde")]
impl<'de, T> ::serde::Deserialize<'de> for Vec1<T>
where
    T: ::serde::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        use serde::de::Error;

        let v = Vec::deserialize(deserializer)?;
        let v1 = Vec1::try_from_vec(v)
            .map_err(|e| D::Error::custom(e))?;

        Ok(v1)
    }
}

/// **Warning: This impl is unstable and requires nightly,
///   it's not covert by semver stability guarantees.**
///
/// (Through as long as the `TryFrom` trait does not change this
///  crate does not intend to change this implementation.)
#[cfg(feature = "unstable-nightly-try-from-impl")]
impl<T> std::convert::TryFrom<Vec<T>> for Vec1<T> {
    type Error = Size0Error;

    fn try_from(vec: Vec<T>) -> StdResult<Self, Self::Error> {
        Vec1::try_from_vec(vec)
    }
}

#[cfg(test)]
mod test {

    #[macro_export]
    macro_rules! assert_ok {
        ($val:expr) => {{
            match $val {
                Ok(res) => res,
                Err(err) => panic!("expected Ok(..) got Err({:?})", err),
            }
        }};
        ($val:expr, $ctx:expr) => {{
            match $val {
                Ok(res) => res,
                Err(err) => panic!("expected Ok(..) got Err({:?}) [ctx: {:?}]", err, $ctx),
            }
        }};
    }

    macro_rules! assert_err {
        ($val:expr) => {{
            match $val {
                Ok(val) => panic!("expected Err(..) got Ok({:?})", val),
                Err(err) => err,
            }
        }};
        ($val:expr, $ctx:expr) => {{
            match $val {
                Ok(val) => panic!("expected Err(..) got Ok({:?}) [ctx: {:?}]", val, $ctx),
                Err(err) => err,
            }
        }};
    }

    mod Size0Error {
        #![allow(non_snake_case)]
        use super::super::*;

        #[test]
        fn implements_std_error() {
            fn comp_check<T: StdError>() {}
            comp_check::<Size0Error>();
        }
    }

    mod Vec1 {
        #![allow(non_snake_case)]
        use super::super::*;

        #[test]
        fn now_warning_on_empty_vec() {
            #![deny(warnings)]

            let _ = vec1![1u8,];
            let _ = vec1![1u8];
        }

        #[test]
        fn deref_slice() {
            let vec = Vec1::new(1u8);
            let _: &[u8] = &*vec;
        }

        #[test]
        fn deref_slice_mut() {
            let mut vec = Vec1::new(1u8);
            let _: &mut [u8] = &mut *vec;
        }

        #[test]
        fn provided_all_ro_functions() {
            let vec = Vec1::new(1u8);
            assert_eq!(vec.len(), 1);
            assert!(vec.capacity() > 0);
            assert_eq!(vec.as_slice(), &*vec);
            // there is obviously no reason we should provide this,
            // as it can't be empty at all, that's the point behind Vec1
            //assert_eq!(vec.is_empty(), true)
        }

        #[test]
        fn provides_some_safe_mut_functions() {
            let mut vec = Vec1::new(1u8);
            vec.reserve(12);
            assert!(vec.capacity() >= 13);
            vec.reserve_exact(31);
            assert!(vec.capacity() >= 31);
            vec.shrink_to_fit();
            let _: &mut [u8] = vec.as_mut_slice();
            vec.insert(1, 31u8);
            vec.insert(1, 2u8);
            assert_eq!(&*vec, &[1, 2, 31]);
            vec.dedup_by_key(|k| *k / 3);
            assert_eq!(&*vec, &[1, 31]);
            vec.push(31);
            assert_eq!(&*vec, &[1, 31, 31]);
            vec.dedup_by(|l, r| l == r);
            assert_eq!(&*vec, &[1, 31]);
            vec.extend_from_slice(&[31, 2, 3]);
            assert_eq!(&*vec, &[1, 31, 31, 2, 3]);
            vec.dedub();
            assert_eq!(&*vec, &[1, 31, 2, 3]);
            // as the passed in vec is emptied this won't work with a vec1 as parameter
            vec.append(&mut vec![1, 2, 3]);
            assert_eq!(&*vec, &[1, 31, 2, 3, 1, 2, 3])
        }

        #[test]
        fn provides_other_methos_in_failible_form() {
            let mut vec = vec1![1u8, 2, 3, 4];
            assert_ok!(vec.try_truncate(3));
            assert_err!(vec.try_truncate(0));
            assert_eq!(vec, &[1, 2, 3]);

            assert_ok!(vec.try_swap_remove(0));
            assert_eq!(vec, &[3, 2]);
            assert_ok!(vec.try_remove(0));
            assert_eq!(vec, &[2]);
            assert_err!(vec.try_swap_remove(0));
            assert_err!(vec.try_remove(0));
            vec.push(12);

            assert_eq!(vec.try_pop(), Ok(12));
            assert_eq!(vec.try_pop(), Err(Size0Error));
            assert_eq!(vec, &[2]);
        }

        #[test]
        fn try_split_of() {
            let mut vec = vec1![1, 2, 3, 4];
            assert_err!(vec.try_split_off(0));
            let len = vec.len();
            assert_err!(vec.try_split_off(len));
            let nvec = assert_ok!(vec.try_split_off(len - 1));
            assert_eq!(vec, &[1, 2, 3]);
            assert_eq!(nvec, &[4]);
        }

        #[test]
        fn try_resize() {
            let mut vec = Vec1::new(1u8);
            assert_ok!(vec.try_resize(10, 2u8));
            assert_eq!(vec.len(), 10);
            assert_ok!(vec.try_resize(1, 2u8));
            assert_eq!(vec, &[1]);
            assert_err!(vec.try_resize(0, 2u8));
        }

        #[test]
        fn with_capacity() {
            let vec = Vec1::with_capacity(1u8, 16);
            assert!(vec.capacity() >= 16);
        }

        #[test]
        fn impl_index() {
            let vec = vec1![1, 2, 3, 3];
            assert_eq!(&vec[..2], &[1, 2]);
        }
        #[test]
        fn impl_index_mut() {
            let mut vec = vec1![1, 2, 3, 3];
            assert_eq!(&mut vec[..2], &mut [1, 2]);
        }

        #[test]
        fn impl_extend() {
            let mut vec = Vec1::new(1u8);
            vec.extend([2, 3].iter().cloned());
            assert_eq!(vec, &[1, 2, 3]);
        }

        #[test]
        fn impl_extend_ref_copy() {
            let mut vec = Vec1::new(1u8);
            vec.extend([2, 3].iter());
            assert_eq!(vec, &[1, 2, 3]);
        }

        #[test]
        fn impl_borrow_mut_slice() {
            fn chk<E, T: BorrowMut<[E]>>() {};
            chk::<u8, Vec1<u8>>();
        }

        #[test]
        fn impl_borrow_slice() {
            fn chk<E, T: BorrowMut<[E]>>() {};
            chk::<u8, Vec1<u8>>();
        }

        #[test]
        fn impl_as_mut_slice() {
            fn chk<E, T: AsMut<[E]>>() {};
            chk::<u8, Vec1<u8>>();
        }

        #[test]
        fn impl_as_ref() {
            fn chk<E, T: AsRef<[E]>>() {};
            chk::<u8, Vec1<u8>>();
        }
        #[test]
        fn impl_as_mut_slice_self() {
            fn chk<E, T: AsMut<Vec1<E>>>() {};
            chk::<u8, Vec1<u8>>();
        }

        #[test]
        fn impl_as_ref_self() {
            fn chk<E, T: AsRef<Vec1<E>>>() {};
            chk::<u8, Vec1<u8>>();
        }

        #[test]
        fn impl_as_ref_vec() {
            fn chk<E, T: AsRef<Vec<E>>>() {};
            chk::<u8, Vec1<u8>>();
        }

        //into iter self, &, &mut
        #[test]
        fn impl_into_iter() {
            let vec = vec1![1, 2, 3];
            assert_eq!(6, vec.into_iter().sum::<u8>());
        }
        #[test]
        fn impl_into_iter_on_ref() {
            let vec = vec1![1, 2, 3];
            assert_eq!(6, (&vec).into_iter().sum::<u8>());
        }
        #[test]
        fn impl_into_iter_on_ref_mut() {
            let mut vec = vec1![1, 2, 3];
            assert_eq!(
                3,
                (&mut vec).into_iter().fold(0u8, |x, m| {
                    *m = *m + 1;
                    x + 1
                })
            );
            assert_eq!(vec, &[2, 3, 4]);
        }

        #[test]
        fn non_slice_indexing_works() {
            let mut vec = vec1!["a"];
            assert_eq!(&mut vec[0], &mut "a");
        }

        #[cfg(feature = "serde")]
        mod serde {
            use super::super::super::*;

            #[test]
            fn empty() {
                let result: Result<Vec1<u8>, _> = serde_json::from_str("[]");
                assert!(result.is_err());
            }

            #[test]
            fn one_element() {
                let vec: Vec1<u8> = serde_json::from_str("[1]").unwrap();
                assert_eq!(vec, vec1![1]);
                let json = serde_json::to_string(&vec).unwrap();
                assert_eq!(json, "[1]");
            }

            #[test]
            fn multiple_elements() {
                let vec: Vec1<u8> = serde_json::from_str("[1, 2, 3]").unwrap();
                assert_eq!(vec, vec1![1, 2, 3]);
                let json = serde_json::to_string(&vec).unwrap();
                assert_eq!(json, "[1,2,3]");
            }
        }

        #[cfg(feature = "unstable-nightly-try-from-impl")]
        #[test]
        fn has_a_try_from_impl() {
            use std::convert::TryFrom;

            let vec = Vec1::<u8>::try_from(vec![]);
            assert_eq!(vec, Err(Size0Error));

            let vec = Vec1::try_from(vec![1u8,12])
                .unwrap();
            assert_eq!(vec, vec![1u8, 12]);
        }

    }

}