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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
#![cfg_attr(rustfmt, rustfmt_skip)]

use std::{fmt, mem};
use std::borrow::{Borrow, BorrowMut, Cow};
use std::error::Error;
use std::ffi::{CStr, CString};
use std::any::Any;
use std::str::FromStr;
use std::ops::{Deref, DerefMut, Add, AddAssign, Index, IndexMut};
use std::iter::FromIterator;

#[cfg(feature = "quickcheck")]
use quickcheck::{Arbitrary, Gen};

use ascii_char::AsciiChar;
use ascii_str::{AsciiStr, AsAsciiStr, AsAsciiStrError};

/// A growable string stored as an ASCII encoded buffer.
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AsciiString {
    vec: Vec<AsciiChar>,
}

impl AsciiString {
    /// Creates a new, empty ASCII string buffer without allocating.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::new();
    /// ```
    #[inline]
    pub fn new() -> Self {
        AsciiString { vec: Vec::new() }
    }

    /// Creates a new ASCII string buffer with the given capacity.
    /// The string will be able to hold exactly `capacity` bytes without reallocating.
    /// If `capacity` is 0, the ASCII string will not allocate.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::with_capacity(10);
    /// ```
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        AsciiString { vec: Vec::with_capacity(capacity) }
    }

    /// Creates a new `AsciiString` from a length, capacity and pointer.
    ///
    /// # Safety
    ///
    /// This is highly unsafe, due to the number of invariants that aren't checked:
    ///
    /// * The memory at `ptr` need to have been previously allocated by the same allocator this
    ///   library uses.
    /// * `length` needs to be less than or equal to `capacity`.
    /// * `capacity` needs to be the correct value.
    ///
    /// Violating these may cause problems like corrupting the allocator's internal datastructures.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use ascii::AsciiString;
    /// use std::mem;
    ///
    /// unsafe {
    ///    let s = AsciiString::from_ascii("hello").unwrap();
    ///    let ptr = s.as_ptr();
    ///    let len = s.len();
    ///    let capacity = s.capacity();
    ///
    ///    mem::forget(s);
    ///
    ///    let s = AsciiString::from_raw_parts(ptr as *mut _, len, capacity);
    ///
    ///    assert_eq!(AsciiString::from_ascii("hello").unwrap(), s);
    /// }
    /// ```
    #[inline]
    pub unsafe fn from_raw_parts(buf: *mut AsciiChar, length: usize, capacity: usize) -> Self {
        AsciiString { vec: Vec::from_raw_parts(buf, length, capacity) }
    }

    /// Converts a vector of bytes to an `AsciiString` without checking for non-ASCII characters.
    ///
    /// # Safety
    /// This function is unsafe because it does not check that the bytes passed to it are valid
    /// ASCII characters. If this constraint is violated, it may cause memory unsafety issues with
    /// future of the `AsciiString`, as the rest of this library assumes that `AsciiString`s are
    /// ASCII encoded.
    #[inline]
    pub unsafe fn from_ascii_unchecked<B>(bytes: B) -> Self
    where
        B: Into<Vec<u8>>,
    {
        let mut bytes = bytes.into();
        let vec = Vec::from_raw_parts(
            bytes.as_mut_ptr() as *mut AsciiChar,
            bytes.len(),
            bytes.capacity(),
        );
        mem::forget(bytes);
        AsciiString { vec: vec }
    }

    /// Converts anything that can represent a byte buffer into an `AsciiString`.
    ///
    /// # Failure
    /// Returns the byte buffer if not all of the bytes are ASCII characters.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let foo = AsciiString::from_ascii("foo".to_string()).unwrap();
    /// let err = AsciiString::from_ascii("Ŋ".to_string()).unwrap_err();
    /// assert_eq!(foo.as_str(), "foo");
    /// assert_eq!(err.into_source(), "Ŋ");
    /// ```
    pub fn from_ascii<B>(bytes: B) -> Result<AsciiString, FromAsciiError<B>>
    where
        B: Into<Vec<u8>> + AsRef<[u8]>,
    {
        unsafe {
            match bytes.as_ref().as_ascii_str() {
                Ok(_) => Ok(AsciiString::from_ascii_unchecked(bytes)),
                Err(e) => Err(FromAsciiError {
                    error: e,
                    owner: bytes,
                }),
            }
        }
    }

    /// Pushes the given ASCII string onto this ASCII string buffer.
    ///
    /// # Examples
    /// ```
    /// # use ascii::{AsciiString, AsAsciiStr};
    /// use std::str::FromStr;
    /// let mut s = AsciiString::from_str("foo").unwrap();
    /// s.push_str("bar".as_ascii_str().unwrap());
    /// assert_eq!(s, "foobar".as_ascii_str().unwrap());
    /// ```
    #[inline]
    pub fn push_str(&mut self, string: &AsciiStr) {
        self.vec.extend(string.chars())
    }

    /// Returns the number of bytes that this ASCII string buffer can hold without reallocating.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let s = String::with_capacity(10);
    /// assert!(s.capacity() >= 10);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.vec.capacity()
    }

    /// Reserves capacity for at least `additional` more bytes to be inserted in the given
    /// `AsciiString`. The collection may reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    /// Panics if the new capacity overflows `usize`.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::new();
    /// s.reserve(10);
    /// assert!(s.capacity() >= 10);
    /// ```
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.vec.reserve(additional)
    }

    /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
    /// given `AsciiString`. Does nothing if the capacity is already sufficient.
    ///
    /// Note that the allocator may give the collection more space than it requests. Therefore
    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
    /// insertions are expected.
    ///
    /// # Panics
    /// Panics if the new capacity overflows `usize`.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::new();
    /// s.reserve_exact(10);
    /// assert!(s.capacity() >= 10);
    /// ```
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.vec.reserve_exact(additional)
    }

    /// Shrinks the capacity of this ASCII string buffer to match it's length.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// use std::str::FromStr;
    /// let mut s = AsciiString::from_str("foo").unwrap();
    /// s.reserve(100);
    /// assert!(s.capacity() >= 100);
    /// s.shrink_to_fit();
    /// assert_eq!(s.capacity(), 3);
    /// ```
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.vec.shrink_to_fit()
    }

    /// Adds the given ASCII character to the end of the ASCII string.
    ///
    /// # Examples
    /// ```
    /// # use ascii::{ AsciiChar, AsciiString};
    /// let mut s = AsciiString::from_ascii("abc").unwrap();
    /// s.push(AsciiChar::from('1').unwrap());
    /// s.push(AsciiChar::from('2').unwrap());
    /// s.push(AsciiChar::from('3').unwrap());
    /// assert_eq!(s, "abc123");
    /// ```
    #[inline]
    pub fn push(&mut self, ch: AsciiChar) {
        self.vec.push(ch)
    }

    /// Shortens a ASCII string to the specified length.
    ///
    /// # Panics
    /// Panics if `new_len` > current length.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::from_ascii("hello").unwrap();
    /// s.truncate(2);
    /// assert_eq!(s, "he");
    /// ```
    #[inline]
    pub fn truncate(&mut self, new_len: usize) {
        self.vec.truncate(new_len)
    }

    /// Removes the last character from the ASCII string buffer and returns it.
    /// Returns `None` if this string buffer is empty.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::from_ascii("foo").unwrap();
    /// assert_eq!(s.pop().map(|c| c.as_char()), Some('o'));
    /// assert_eq!(s.pop().map(|c| c.as_char()), Some('o'));
    /// assert_eq!(s.pop().map(|c| c.as_char()), Some('f'));
    /// assert_eq!(s.pop(), None);
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<AsciiChar> {
        self.vec.pop()
    }

    /// Removes the ASCII character at position `idx` from the buffer and returns it.
    ///
    /// # Warning
    /// This is an O(n) operation as it requires copying every element in the buffer.
    ///
    /// # Panics
    /// If `idx` is out of bounds this function will panic.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::from_ascii("foo").unwrap();
    /// assert_eq!(s.remove(0).as_char(), 'f');
    /// assert_eq!(s.remove(1).as_char(), 'o');
    /// assert_eq!(s.remove(0).as_char(), 'o');
    /// ```
    #[inline]
    pub fn remove(&mut self, idx: usize) -> AsciiChar {
        self.vec.remove(idx)
    }

    /// Inserts an ASCII character into the buffer at position `idx`.
    ///
    /// # Warning
    /// This is an O(n) operation as it requires copying every element in the buffer.
    ///
    /// # Panics
    /// If `idx` is out of bounds this function will panic.
    ///
    /// # Examples
    /// ```
    /// # use ascii::{AsciiString,AsciiChar};
    /// let mut s = AsciiString::from_ascii("foo").unwrap();
    /// s.insert(2, AsciiChar::b);
    /// assert_eq!(s, "fobo");
    /// ```
    #[inline]
    pub fn insert(&mut self, idx: usize, ch: AsciiChar) {
        self.vec.insert(idx, ch)
    }

    /// Returns the number of bytes in this ASCII string.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let s = AsciiString::from_ascii("foo").unwrap();
    /// assert_eq!(s.len(), 3);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    /// Returns true if the ASCII string contains zero bytes.
    ///
    /// # Examples
    /// ```
    /// # use ascii::{AsciiChar, AsciiString};
    /// let mut s = AsciiString::new();
    /// assert!(s.is_empty());
    /// s.push(AsciiChar::from('a').unwrap());
    /// assert!(!s.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Truncates the ASCII string, setting length (but not capacity) to zero.
    ///
    /// # Examples
    /// ```
    /// # use ascii::AsciiString;
    /// let mut s = AsciiString::from_ascii("foo").unwrap();
    /// s.clear();
    /// assert!(s.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.vec.clear()
    }
}

impl Deref for AsciiString {
    type Target = AsciiStr;

    #[inline]
    fn deref(&self) -> &AsciiStr {
        self.vec.as_slice().as_ref()
    }
}

impl DerefMut for AsciiString {
    #[inline]
    fn deref_mut(&mut self) -> &mut AsciiStr {
        self.vec.as_mut_slice().as_mut()
    }
}

impl PartialEq<str> for AsciiString {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        **self == *other
    }
}

impl PartialEq<AsciiString> for str {
    #[inline]
    fn eq(&self, other: &AsciiString) -> bool {
        **other == *self
    }
}

macro_rules! impl_eq {
    ($lhs:ty, $rhs:ty) => {
        impl<'a> PartialEq<$rhs> for $lhs {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                PartialEq::eq(&**self, &**other)
            }
            #[inline]
            fn ne(&self, other: &$rhs) -> bool {
                PartialEq::ne(&**self, &**other)
            }
        }
    }
}

impl_eq! { AsciiString, String }
impl_eq! { String, AsciiString }
impl_eq! { &'a AsciiStr, String }
impl_eq! { String, &'a AsciiStr }
impl_eq! { &'a AsciiStr, AsciiString }
impl_eq! { AsciiString, &'a AsciiStr }
impl_eq! { &'a str, AsciiString }
impl_eq! { AsciiString, &'a str }

impl Borrow<AsciiStr> for AsciiString {
    #[inline]
    fn borrow(&self) -> &AsciiStr {
        &*self
    }
}

impl BorrowMut<AsciiStr> for AsciiString {
    #[inline]
    fn borrow_mut(&mut self) -> &mut AsciiStr {
        &mut*self
    }
}

impl From<Vec<AsciiChar>> for AsciiString {
    #[inline]
    fn from(vec: Vec<AsciiChar>) -> Self {
        AsciiString { vec: vec }
    }
}

impl Into<Vec<u8>> for AsciiString {
    fn into(self) -> Vec<u8> {
        unsafe {
            let v = Vec::from_raw_parts(
                self.vec.as_ptr() as *mut u8,
                self.vec.len(),
                self.vec.capacity(),
            );

            // We forget `self` to avoid freeing it at the end of the scope.
            // Otherwise, the returned `Vec` would point to freed memory.
            mem::forget(self);
            v
        }
    }
}

impl<'a> From<&'a AsciiStr> for AsciiString {
    #[inline]
    fn from(s: &'a AsciiStr) -> Self {
        s.to_ascii_string()
    }
}

impl<'a> From<&'a [AsciiChar]> for AsciiString {
    #[inline]
    fn from(s: &'a [AsciiChar]) -> AsciiString {
        s.into_iter().map(|c| *c).collect()
    }
}

impl Into<String> for AsciiString {
    #[inline]
    fn into(self) -> String {
        unsafe { String::from_utf8_unchecked(self.into()) }
    }
}

impl<'a> From<Cow<'a,AsciiStr>> for AsciiString {
    fn from(cow: Cow<'a,AsciiStr>) -> AsciiString {
        cow.into_owned()
    }
}

impl From<AsciiString> for Cow<'static,AsciiStr> {
    fn from(string: AsciiString) -> Cow<'static,AsciiStr> {
        Cow::Owned(string)
    }
}

impl<'a> From<&'a AsciiStr> for Cow<'a,AsciiStr> {
    fn from(s: &'a AsciiStr) -> Cow<'a,AsciiStr> {
        Cow::Borrowed(s)
    }
}

impl AsRef<AsciiStr> for AsciiString {
    #[inline]
    fn as_ref(&self) -> &AsciiStr {
        &*self
    }
}

impl AsRef<[AsciiChar]> for AsciiString {
    #[inline]
    fn as_ref(&self) -> &[AsciiChar] {
        &self.vec
    }
}

impl AsRef<[u8]> for AsciiString {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<str> for AsciiString {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl AsMut<AsciiStr> for AsciiString {
    #[inline]
    fn as_mut(&mut self) -> &mut AsciiStr {
        &mut *self
    }
}

impl AsMut<[AsciiChar]> for AsciiString {
    #[inline]
    fn as_mut(&mut self) -> &mut [AsciiChar] {
        &mut self.vec
    }
}

impl FromStr for AsciiString {
    type Err = AsAsciiStrError;

    fn from_str(s: &str) -> Result<AsciiString, AsAsciiStrError> {
        s.as_ascii_str().map(AsciiStr::to_ascii_string)
    }
}

impl fmt::Display for AsciiString {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl fmt::Debug for AsciiString {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

/// Please note that the `std::fmt::Result` returned by these methods does not support
/// transmission of an error other than that an error occurred.
impl fmt::Write for AsciiString {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let astr = try!(AsciiStr::from_ascii(s).map_err(|_| fmt::Error));
        self.push_str(astr);
        Ok(())
    }

    fn write_char(&mut self, c: char) -> fmt::Result {
        let achar = try!(AsciiChar::from(c).map_err(|_| fmt::Error));
        self.push(achar);
        Ok(())
    }
}

impl FromIterator<AsciiChar> for AsciiString {
    fn from_iter<I: IntoIterator<Item = AsciiChar>>(iter: I) -> AsciiString {
        let mut buf = AsciiString::new();
        buf.extend(iter);
        buf
    }
}

impl<'a> FromIterator<&'a AsciiStr> for AsciiString {
    fn from_iter<I: IntoIterator<Item = &'a AsciiStr>>(iter: I) -> AsciiString {
        let mut buf = AsciiString::new();
        buf.extend(iter);
        buf
    }
}

impl<'a> FromIterator<Cow<'a, AsciiStr>> for AsciiString {
    fn from_iter<I: IntoIterator<Item = Cow<'a, AsciiStr>>>(iter: I) -> AsciiString {
        let mut buf = AsciiString::new();
        buf.extend(iter);
        buf
    }
}

impl Extend<AsciiChar> for AsciiString {
    fn extend<I: IntoIterator<Item = AsciiChar>>(&mut self, iterable: I) {
        let iterator = iterable.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.reserve(lower_bound);
        for ch in iterator {
            self.push(ch)
        }
    }
}

impl<'a> Extend<&'a AsciiChar> for AsciiString {
    fn extend<I: IntoIterator<Item = &'a AsciiChar>>(&mut self, iter: I) {
        self.extend(iter.into_iter().cloned())
    }
}

impl<'a> Extend<&'a AsciiStr> for AsciiString {
    fn extend<I: IntoIterator<Item = &'a AsciiStr>>(&mut self, iterable: I) {
        let iterator = iterable.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.reserve(lower_bound);
        for s in iterator {
            self.push_str(s)
        }
    }
}

impl<'a> Extend<Cow<'a, AsciiStr>> for AsciiString {
    fn extend<I: IntoIterator<Item = Cow<'a,AsciiStr>>>(&mut self, iterable: I) {
        let iterator = iterable.into_iter();
        let (lower_bound, _) = iterator.size_hint();
        self.reserve(lower_bound);
        for s in iterator {
            self.push_str(&*s);
        }
    }
}

impl<'a> Add<&'a AsciiStr> for AsciiString {
    type Output = AsciiString;

    #[inline]
    fn add(mut self, other: &AsciiStr) -> AsciiString {
        self.push_str(other);
        self
    }
}

impl<'a> AddAssign<&'a AsciiStr> for AsciiString {
    #[inline]
    fn add_assign(&mut self, other: &AsciiStr) {
        self.push_str(other);
    }
}

impl<T> Index<T> for AsciiString
where
    AsciiStr: Index<T>,
{
    type Output = <AsciiStr as Index<T>>::Output;

    #[inline]
    fn index(&self, index: T) -> &<AsciiStr as Index<T>>::Output {
        &(**self)[index]
    }
}

impl<T> IndexMut<T> for AsciiString
where
    AsciiStr: IndexMut<T>,
{
    #[inline]
    fn index_mut(&mut self, index: T) -> &mut <AsciiStr as Index<T>>::Output {
        &mut (**self)[index]
    }
}


/// A possible error value when converting an `AsciiString` from a byte vector or string.
/// It wraps an `AsAsciiStrError` which you can get through the `ascii_error()` method.
///
/// This is the error type for `AsciiString::from_ascii()` and
/// `IntoAsciiString::into_ascii_string()`. They will never clone or touch the content of the
/// original type; It can be extracted by the `into_source` method.
///
/// #Examples
/// ```
/// # use ascii::IntoAsciiString;
/// let err = "bø!".to_string().into_ascii_string().unwrap_err();
/// assert_eq!(err.ascii_error().valid_up_to(), 1);
/// assert_eq!(err.into_source(), "bø!".to_string());
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FromAsciiError<O> {
    error: AsAsciiStrError,
    owner: O,
}
impl<O> FromAsciiError<O> {
    /// Get the position of the first non-ASCII byte or character.
    #[inline]
    pub fn ascii_error(&self) -> AsAsciiStrError {
        self.error
    }
    /// Get back the original, unmodified type.
    #[inline]
    pub fn into_source(self) -> O {
        self.owner
    }
}
impl<O> fmt::Debug for FromAsciiError<O> {
    #[inline]
    fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.error, fmtr)
    }
}
impl<O> fmt::Display for FromAsciiError<O> {
    #[inline]
    fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.error, fmtr)
    }
}
impl<O: Any> Error for FromAsciiError<O> {
    #[inline]
    fn description(&self) -> &str {
        self.error.description()
    }
    /// Always returns an `AsAsciiStrError`
    fn cause(&self) -> Option<&Error> {
        Some(&self.error as &Error)
    }
}


/// Convert vectors into `AsciiString`.
pub trait IntoAsciiString: Sized {
    /// Convert to `AsciiString` without checking for non-ASCII characters.
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString;
    /// Convert to `AsciiString`.
    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>>;
}

impl IntoAsciiString for Vec<AsciiChar> {
    #[inline]
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
        AsciiString::from(self)
    }
    #[inline]
    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
        Ok(AsciiString::from(self))
    }
}

impl<'a> IntoAsciiString for &'a [AsciiChar] {
    #[inline]
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
        AsciiString::from(self)
    }
    #[inline]
    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
        Ok(AsciiString::from(self))
    }
}

impl<'a> IntoAsciiString for &'a AsciiStr {
    #[inline]
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
        AsciiString::from(self)
    }
    #[inline]
    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
        Ok(AsciiString::from(self))
    }
}

macro_rules! impl_into_ascii_string {
    ('a, $wider:ty) => {
        impl<'a> IntoAsciiString for $wider {
            #[inline]
            unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
                AsciiString::from_ascii_unchecked(self)
            }

            #[inline]
            fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
                AsciiString::from_ascii(self)
            }
        }
    };

    ($wider:ty) => {
        impl IntoAsciiString for $wider {
            #[inline]
            unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
                AsciiString::from_ascii_unchecked(self)
            }

            #[inline]
            fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
                AsciiString::from_ascii(self)
            }
        }
    };
}

impl_into_ascii_string!{AsciiString}
impl_into_ascii_string!{Vec<u8>}
impl_into_ascii_string!{'a, &'a [u8]}
impl_into_ascii_string!{String}
impl_into_ascii_string!{'a, &'a str}

/// Note that the trailing null byte will be removed in the conversion.
impl IntoAsciiString for CString {
    #[inline]
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
        AsciiString::from_ascii_unchecked(self.into_bytes())
    }

    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
        AsciiString::from_ascii(self.into_bytes_with_nul())
            .map_err(|FromAsciiError { error, owner }| {
                FromAsciiError {
                    owner: unsafe {
                        // The null byte is preserved from the original
                        // `CString`, so this is safe.
                        CString::from_vec_unchecked(owner)
                    },
                    error: error,
                }
            })
            .map(|mut s| {
                let _nul = s.pop();
                debug_assert_eq!(_nul, Some(AsciiChar::Null));
                s
            })
    }
}

/// Note that the trailing null byte will be removed in the conversion.
impl<'a> IntoAsciiString for &'a CStr {
    #[inline]
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
        AsciiString::from_ascii_unchecked(self.to_bytes())
    }

    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
        AsciiString::from_ascii(self.to_bytes_with_nul())
            .map_err(|FromAsciiError { error, owner }| {
                FromAsciiError {
                    owner: unsafe {
                        CStr::from_ptr(owner.as_ptr() as *const _)
                    },
                    error: error,
                }
            })
            .map(|mut s| {
                let _nul = s.pop();
                debug_assert_eq!(_nul, Some(AsciiChar::Null));
                s
            })
    }
}

impl<'a, B: ?Sized> IntoAsciiString for Cow<'a, B>
where
    B: 'a + ToOwned,
    &'a B: IntoAsciiString,
    <B as ToOwned>::Owned: IntoAsciiString,
{
    #[inline]
    unsafe fn into_ascii_string_unchecked(self) -> AsciiString {
        IntoAsciiString::into_ascii_string_unchecked(self.into_owned())
    }

    fn into_ascii_string(self) -> Result<AsciiString, FromAsciiError<Self>> {
        match self {
            Cow::Owned(b) => {
                IntoAsciiString::into_ascii_string(b)
                    .map_err(|FromAsciiError { error, owner }| {
                        FromAsciiError {
                            owner: Cow::Owned(owner),
                            error: error,
                        }
                    })
            }
            Cow::Borrowed(b) => {
                IntoAsciiString::into_ascii_string(b)
                    .map_err(|FromAsciiError { error, owner }| {
                        FromAsciiError {
                            owner: Cow::Borrowed(owner),
                            error: error,
                        }
                    })
            }
        }
    }
}

#[cfg(feature = "quickcheck")]
impl Arbitrary for AsciiString {
    fn arbitrary<G: Gen>(g: &mut G) -> Self {
        let size = {
            let s = g.size();
            g.gen_range(0, s)
        };
        let mut s = AsciiString::with_capacity(size);
        for _ in 0..size {
            s.push(AsciiChar::arbitrary(g));
        }
        s
    }

    fn shrink(&self) -> Box<Iterator<Item = Self>> {
        let chars: Vec<AsciiChar> = self.as_slice().to_vec();
        Box::new(chars.shrink().map(
            |x| x.into_iter().collect::<AsciiString>(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;
    use std::ffi::CString;
    use AsciiChar;
    use super::{AsciiString, IntoAsciiString};

    #[test]
    fn into_string() {
        let v = AsciiString::from_ascii(&[40_u8, 32, 59][..]).unwrap();
        assert_eq!(Into::<String>::into(v), "( ;".to_string());
    }

    #[test]
    fn into_bytes() {
        let v = AsciiString::from_ascii(&[40_u8, 32, 59][..]).unwrap();
        assert_eq!(Into::<Vec<u8>>::into(v), vec![40_u8, 32, 59])
    }

    #[test]
    fn from_ascii_vec() {
        let vec = vec![AsciiChar::from('A').unwrap(), AsciiChar::from('B').unwrap()];
        assert_eq!(AsciiString::from(vec), AsciiString::from_str("AB").unwrap());
    }

    #[test]
    fn from_cstring() {
        let cstring = CString::new("baz").unwrap();
        let ascii_str = cstring.clone().into_ascii_string().unwrap();
        let expected_chars = &[AsciiChar::b, AsciiChar::a, AsciiChar::z];
        assert_eq!(ascii_str.len(), 3);
        assert_eq!(ascii_str.as_slice(), expected_chars);

        let ascii_str_unchecked = unsafe {
            cstring.into_ascii_string_unchecked()
        };
        assert_eq!(ascii_str_unchecked.len(), 3);
        assert_eq!(ascii_str_unchecked.as_slice(), expected_chars);

        let sparkle_heart_bytes = vec![240u8, 159, 146, 150];
        let cstring = CString::new(sparkle_heart_bytes).unwrap();
        let cstr = &*cstring;
        let ascii_err = cstr.into_ascii_string().unwrap_err();
        assert_eq!(ascii_err.into_source(), &*cstring);
    }

    #[test]
    fn fmt_ascii_string() {
        let s = "abc".to_string().into_ascii_string().unwrap();
        assert_eq!(format!("{}", s), "abc".to_string());
        assert_eq!(format!("{:?}", s), "\"abc\"".to_string());
    }

    #[test]
    fn write_fmt() {
        use std::{fmt, str};

        let mut s0 = AsciiString::new();
        fmt::write(&mut s0, format_args!("Hello World")).unwrap();
        assert_eq!(s0, "Hello World");

        let mut s1 = AsciiString::new();
        fmt::write(&mut s1, format_args!("{}", 9)).unwrap();
        assert_eq!(s1, "9");

        let mut s2 = AsciiString::new();
        let sparkle_heart_bytes = [240, 159, 146, 150];
        let sparkle_heart = str::from_utf8(&sparkle_heart_bytes).unwrap();
        assert!(fmt::write(&mut s2, format_args!("{}", sparkle_heart)).is_err());
    }
}