str-queue 0.0.1

Queue for a string
Documentation
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
//! Chars range in a queue.

use core::cmp::Ordering;
use core::fmt;
use core::num::NonZeroUsize;
use core::ops::{Bound, RangeBounds};

use crate::iter::{Chars, Fragment, Fragments};
use crate::range::BytesRange;
use crate::utf8::{self, REPLACEMENT_CHAR};
use crate::StrQueue;
// `BoundExt` trait is a workaround until Rust 1.55.0.
// Suppress `unused_imports` for Rust 1.55.0 beta or later, for now.
#[allow(unused_imports)]
use crate::BoundExt;

/// An internal error type indicating the character is incomplete.
#[derive(Debug, Clone, Copy)]
struct IncompleteCharError;

/// Subrange of a `StrQueue`.
///
/// This can be created by [`StrQueue::chars_range`].
///
/// The range contains valid UTF-8 sequence with the optional
/// last incomplete character.
#[derive(Debug, Clone, Copy, Eq, Hash)]
pub struct CharsRange<'a> {
    /// The range.
    range: BytesRange<'a>,
}

/// Setup.
impl<'a> CharsRange<'a> {
    /// Creates a new `CharsRange` for the queue.
    ///
    /// # Panics
    ///
    /// Panics if the start bound of the range does not lie on UTF-8 sequence boundary.
    #[must_use]
    pub(crate) fn new<R>(queue: &'a StrQueue, range: R) -> Self
    where
        R: RangeBounds<usize>,
    {
        let (former, latter) = queue.inner.as_slices();
        #[allow(unstable_name_collisions)] // This is intended. See `crate::BoundExt` trait.
        Self::from_slices_and_bounds(
            former,
            latter,
            range.start_bound().cloned(),
            range.end_bound().cloned(),
        )
    }

    /// Creates `CharsRange` from slices and range bounds.
    ///
    /// # Panics
    ///
    /// Panics if the start bound of the range does not lie on UTF-8 sequence boundary.
    /// Panics if `former` and `latter` overlaps.
    /// Panics if the given index is out of range.
    #[must_use]
    fn from_slices_and_bounds(
        former: &'a [u8],
        latter: &'a [u8],
        start: Bound<usize>,
        end: Bound<usize>,
    ) -> Self {
        let range = BytesRange::from_slices_and_bounds(former, latter, start, end);

        // Check if the first byte of the index is the start byte of a character.
        if !matches!(start, Bound::Unbounded | Bound::Included(0))
            && range.first().map(utf8::expected_char_len) == Some(0)
        {
            panic!(
                "[precondition] start bound of the range {:?} \
                 does not lie on UTF-8 sequence boundary",
                (start, end)
            );
        }

        Self { range }
    }
}

/// Subrange access.
impl<'a> CharsRange<'a> {
    /// Returns the subrange.
    ///
    /// The returned range can contain an incomplete character at the end.
    /// If you want to exclude a possible trailing incomplete character in the range,
    /// use [`CharsRange::to_complete`] or [`CharsRange::trim_last_incomplete_char`].
    ///
    /// # Panics
    ///
    /// Panics if the start bound of the range does not lie on UTF-8 sequence boundary.
    /// Panics if the given index is out of range.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"Hello \xce\xb1");
    /// let range = queue.chars_range(..);
    /// assert_eq!(range.to_string(), "Hello \u{03B1}");
    ///
    /// assert_eq!(range.range(3..7).to_string(), "lo \u{FFFD}");
    /// ```
    #[must_use]
    pub fn range<R>(&self, range: R) -> Self
    where
        R: RangeBounds<usize>,
    {
        #[allow(unstable_name_collisions)] // This is intended. See `crate::BoundExt` trait.
        Self::from_slices_and_bounds(
            self.range.former,
            self.range.latter,
            range.start_bound().cloned(),
            range.end_bound().cloned(),
        )
    }

    /// Returns the range without the last incomplete character.
    ///
    /// If you want to modify `self` instead of getting a modified copy, use
    /// [`CharsRange::trim_last_incomplete_char`].
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    ///
    /// let queue = StrQueue::from(b"Hello \xce");
    /// let range = queue.chars_range(..);
    /// assert_eq!(range.to_string(), "Hello \u{FFFD}");
    /// assert_eq!(range.to_complete().to_string(), "Hello ");
    /// ```
    #[inline]
    #[must_use]
    pub fn to_complete(mut self) -> Self {
        self.trim_last_incomplete_char();
        self
    }

    /// Returns the range without the last incomplete character and the trimmed length.
    #[inline]
    #[must_use]
    // TODO: Better name?
    fn to_complete_and_trimmed_len(mut self) -> (Self, usize) {
        let trimmed = self.trim_last_incomplete_char();
        (self, trimmed)
    }
}

/// Content length and existence.
impl<'a> CharsRange<'a> {
    /// Returns the total length.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"Hello \xce");
    /// let range = queue.chars_range(..);
    /// assert_eq!(range.len(), b"Hello \xce".len());
    /// ```
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.range.len()
    }

    /// Returns true if the range is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"\xce");
    /// let range = queue.chars_range(..);
    /// assert!(!range.is_empty());
    ///
    /// assert!(queue.chars_range(0..0).is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.range.is_empty()
    }

    /// Returns the string length in bytes, excluding incomplete bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"hello\xce");
    /// assert_eq!(queue.chars_range(..).len_complete(), 5);
    /// ```
    #[inline]
    #[must_use]
    pub fn len_complete(&self) -> usize {
        self.len() - self.len_incomplete()
    }

    /// Returns the length of incomplete bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"hello\xce");
    /// assert_eq!(queue.chars_range(..).len_incomplete(), 1);
    /// ```
    #[inline]
    #[must_use]
    pub fn len_incomplete(&self) -> usize {
        let former = self.range.former;
        let latter = self.range.latter;
        if !latter.is_empty() {
            if let Some(partial_len) = utf8::last_char_len_in_last_4bytes(latter) {
                return partial_len.len_incomplete();
            }
        }

        // No characters starts from the latter slice.
        utf8::last_char_len_in_last_4bytes(former)
            .expect("[validity] the former buffer must be null or start with valid UTF-8 sequence")
            .len_incomplete()
    }

    /// Returns true if the chars range contains no complete string.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let mut queue = StrQueue::new();
    /// assert!(queue.chars_range(..).is_empty_complete());
    ///
    /// queue.push_bytes(b"\xce");
    /// assert!(queue.chars_range(..).is_empty_complete());
    ///
    /// queue.push_bytes(b"\xb1");
    /// assert!(!queue.chars_range(..).is_empty_complete());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_empty_complete(&self) -> bool {
        self.len() == self.len_incomplete()
    }

    /// Returns true if the chars range is a complete string, i.e. has no
    /// trailing incomplete character.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let mut queue = StrQueue::from(b"abc\xce");
    /// assert!(!queue.chars_range(..).is_complete());
    /// queue.push_bytes(b"\xb1");
    /// // Now the string is "abc\u{03B1}".
    /// assert!(queue.chars_range(..).is_complete());
    /// ```
    pub fn is_complete(&self) -> bool {
        if self.range.latter.is_empty() {
            // Check only the former.
            return utf8::last_char_len_in_last_4bytes(self.range.former)
                .map_or(false, |v| v.is_complete());
        }
        if let Some(partial_len) = utf8::last_char_len_in_last_4bytes(self.range.latter) {
            // Check only the latter.
            return partial_len.is_complete();
        }

        // The latter has no beginning of a character.
        let latter_len = self.range.latter.len();
        debug_assert!(
            latter_len < 4,
            "[consistency] a complete character must start in the last 4 bytes"
        );
        debug_assert!(
            latter_len > 0,
            "[consistency] must be returned earlily when the latter is empty"
        );
        let partial_len = match utf8::last_char_len_in_last_4bytes(self.range.former) {
            Some(v) => v,
            None => unreachable!("[consistency] a character start must exist in the last 4 bytes"),
        };
        match partial_len.len_missing().cmp(&latter_len) {
            Ordering::Greater => false,
            Ordering::Equal => true,
            Ordering::Less => {
                unreachable!("[consistency] a character must not be longer than expected")
            }
        }
    }
}

/// Range and content manipulation.
impl<'a> CharsRange<'a> {
    /// Clears the range, removing all elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    ///
    /// let queue = StrQueue::from(b"Hello \xce");
    /// let mut range = queue.chars_range(..);
    /// assert!(!range.is_empty());
    ///
    /// range.clear();
    /// assert!(range.is_empty());
    /// // Only the range is cleared. The underlying queue does not change.
    /// assert!(!queue.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.range.clear()
    }

    /// Trims the last incomplete character, and returns the length of the trimmed bytes.
    ///
    /// If the string is complete (i.e. no incomplete character follows), does
    /// nothing and returns 0.
    ///
    /// If you want to get a modified copy instead of modifying `self` itself,
    /// use [`CharsRange::to_complete`].
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    ///
    /// let queue = StrQueue::from(b"Hello \xce");
    /// let mut range = queue.chars_range(..);
    /// assert_eq!(range.to_string(), "Hello \u{FFFD}");
    ///
    /// range.trim_last_incomplete_char();
    /// assert_eq!(range.to_string(), "Hello ");
    /// ```
    pub fn trim_last_incomplete_char(&mut self) -> usize {
        let former = &mut self.range.former;
        let latter = &mut self.range.latter;

        if !latter.is_empty() {
            if let Some(partial_len) = utf8::last_char_len_in_last_4bytes(latter) {
                let len_incomplete = partial_len.len_incomplete();
                let valid_up_to = latter.len() - len_incomplete;
                *latter = &latter[..valid_up_to];
                return len_incomplete;
            }
        }

        // No characters starts from the latter slice.
        *latter = &latter[..0];
        // Check for the former slice.
        let len_incomplete = utf8::last_char_len_in_last_4bytes(former)
            .expect("[validity] the former buffer must be null or start with valid UTF-8 sequence")
            .len_incomplete();
        let valid_up_to = former.len() - len_incomplete;
        *former = &former[..valid_up_to];

        len_incomplete
    }

    /// Pops the first character in the range and returns it.
    ///
    /// Trailing incomplete character is ignored.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from("hello");
    /// let mut range = queue.chars_range(..);
    ///
    /// assert_eq!(range.pop_char(), Some('h'));
    /// assert_eq!(range.pop_char(), Some('e'));
    /// assert_eq!(range.pop_char(), Some('l'));
    /// assert_eq!(range.pop_char(), Some('l'));
    /// assert_eq!(range.pop_char(), Some('o'));
    /// assert_eq!(range.pop_char(), None);
    /// assert!(range.is_empty());
    /// ```
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"a\xf0");
    /// let mut range = queue.chars_range(..);
    ///
    /// assert_eq!(range.pop_char(), Some('a'));
    /// assert_eq!(range.pop_char(), None);
    /// assert!(!range.is_empty());
    /// ```
    pub fn pop_char(&mut self) -> Option<char> {
        self.pop_char_raw(false).and_then(Result::ok)
    }

    /// Pops the first character from the range and returns it.
    ///
    /// The trailing incomplete character is replaced with `U+FFFD REPLACEMENT
    /// CHARACTER`, if available.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"abc\xce");
    /// let mut range = queue.chars_range(..);
    ///
    /// assert_eq!(range.pop_char_replaced(), Some('a'));
    /// assert_eq!(range.pop_char_replaced(), Some('b'));
    /// assert_eq!(range.pop_char_replaced(), Some('c'));
    /// assert_eq!(range.pop_char_replaced(), Some('\u{FFFD}'));
    /// ```
    pub fn pop_char_replaced(&mut self) -> Option<char> {
        self.pop_char_raw(true)
            .map(|res| res.unwrap_or(REPLACEMENT_CHAR))
    }

    /// Pops the first character from the range and return it.
    ///
    /// If the first character is incomplete, `Some(Err(IncompleteCharError))`
    /// is returned.
    /// The trailing incomplete character is removed from the range if and only
    /// if `pop_incomplete` is true.
    fn pop_char_raw(&mut self, pop_incomplete: bool) -> Option<Result<char, IncompleteCharError>> {
        if self.range.is_empty() {
            return None;
        }
        match utf8::take_char(self.range.bytes()) {
            Some((c, len)) => {
                self.range.trim_start(usize::from(len));
                Some(Ok(c))
            }
            None => {
                debug_assert!(!self.range.is_empty());
                // Incomplete character.
                if pop_incomplete {
                    self.range.clear();
                }
                Some(Err(IncompleteCharError))
            }
        }
    }

    /// Pops the first line in the queue and returns it.
    ///
    /// Incomplete lines are ignored.
    ///
    /// Note that it is unspecified whether the line will be removed from the queue,
    /// if the `PoppedLine` value is not dropped while the borrow it holds expires
    /// (e.g. due to [`core::mem::forget`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// // Note that the last "world\r" is not considered as a complete line
    /// // since the line can be finally "world\r" or "world\r\n".
    /// let queue = StrQueue::from("Hello\nworld\r\nGoodbye\rworld\r");
    /// let mut range = queue.chars_range(..);
    ///
    /// assert_eq!(range.pop_line().map(|v| v.to_string()).as_deref(), Some("Hello\n"));
    /// assert_eq!(range.pop_line().map(|v| v.to_string()).as_deref(), Some("world\r\n"));
    /// assert_eq!(range.pop_line().map(|v| v.to_string()).as_deref(), Some("Goodbye\r"));
    /// assert_eq!(range.pop_line().map(|v| v.to_string()).as_deref(), None);
    /// assert_eq!(range, "world\r");
    /// ```
    #[inline]
    pub fn pop_line<'r>(&'r mut self) -> Option<CharsRangePoppedLine<'a, 'r>> {
        let line_len = self.first_line()?.len();
        let line_len = NonZeroUsize::new(line_len)
            .expect("[validity] a complete line must not be empty since it has a line break");
        Some(CharsRangePoppedLine {
            range: self,
            line_len,
        })
    }

    /// Pops the first [`Fragment`] from the range and return it.
    ///
    /// In other words, takes as much content as possible from the range.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from(b"Hello \xce");
    /// let mut buf = String::new();
    ///
    /// let mut range = queue.chars_range(..);
    /// while let Some(frag) = range.pop_fragment() {
    ///     buf.push_str(&frag.to_string());
    /// }
    ///
    /// assert_eq!(buf, "Hello \u{FFFD}");
    /// assert!(range.is_empty());
    /// ```
    pub fn pop_fragment(&mut self) -> Option<Fragment<'a>> {
        if self.range.is_empty() {
            return None;
        }

        {
            let (former_valid, former_incomplete) =
                utf8::split_incomplete_suffix(self.range.former);
            if !former_valid.is_empty() {
                // The former slice has valid UTF-8 sequence as a prefix.
                self.range.trim_start(former_valid.len());
                return Some(Fragment::Str(former_valid));
            }
            if former_incomplete.is_some() {
                // The former slice starts with incomplete character.
                let frag = self
                    .pop_char_raw(true)
                    .expect("[consistency] the incomplete bytes are not empty")
                    .map_or(Fragment::Incomplete, Fragment::Char);
                return Some(frag);
            }
        }

        let (latter_valid, latter_incomplete) = utf8::split_incomplete_suffix(self.range.latter);
        if !latter_valid.is_empty() {
            // The latter slice has valid UTF-8 sequence as a prefix since
            // the range starts inside the latter slice.
            self.range.trim_start(latter_valid.len());
            return Some(Fragment::Str(latter_valid));
        }
        assert!(
            latter_incomplete.is_some(),
            "[consistency] this cannot be empty since the range is not empty here"
        );
        // The latter slice starts with (and ends with) the incomplete character.
        Some(Fragment::Incomplete)
    }
}

/// Content access.
impl<'a> CharsRange<'a> {
    /// Returns the first character in the range.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let queue = StrQueue::from("hello");
    ///
    /// assert_eq!(queue.first_char(), Some('h'));
    /// ```
    #[inline]
    #[must_use]
    pub fn first_char(&self) -> Option<char> {
        let bytes = self
            .range
            .former
            .iter()
            .chain(self.range.latter.iter())
            .take(4)
            .copied();
        utf8::take_char(bytes).map(|(c, _len)| c)
    }

    /// Returns the subrange of the first line, including the line break.
    ///
    /// Returns `Some(range)` if the range contains a complete line, which
    /// won't be changed if more contents are appended.
    /// Returns `None` if the range contains only an incomplete line,
    /// which will be changed if more contents are appended.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::StrQueue;
    ///
    /// let mut queue = StrQueue::from(b"Hello \xce");
    /// assert_eq!(
    ///     queue.chars_range(..).first_line().map(|r| r.to_string()),
    ///     None
    /// );
    ///
    /// queue.push_bytes(b"\xb1\r");
    /// // The line is still considered incomplete since the line ending can be `\r\n`.
    /// assert_eq!(
    ///     queue.chars_range(..).first_line().map(|r| r.to_string()),
    ///     None
    /// );
    ///
    /// queue.push_bytes(b"\nhello");
    /// assert_eq!(
    ///     queue.chars_range(..).first_line().map(|r| r.to_string()),
    ///     Some("Hello \u{03B1}\r\n".to_owned())
    /// );
    /// ```
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    ///
    /// let queue = StrQueue::from(b"Hello\n");
    /// assert_eq!(
    ///     queue.chars_range(..).first_line().map(|r| r.to_string()),
    ///     Some("Hello\n".to_owned())
    /// );
    /// ```
    pub fn first_line(&self) -> Option<CharsRange<'a>> {
        self.next_line_position().map(|pos| self.range(..pos.get()))
    }

    /// Returns the position where the next line starts.
    #[must_use]
    fn next_line_position(&self) -> Option<NonZeroUsize> {
        let first_newline = self.range.position2(b'\n', b'\r')?;
        debug_assert!(
            first_newline < usize::MAX,
            "the string length won't be `usize::MAX` \
                 since other objects (including self) may exist on memory"
        );
        if self.range.former[first_newline] == b'\n' {
            return NonZeroUsize::new(first_newline + 1);
        }
        assert_eq!(self.range.former[first_newline], b'\r');

        // The string ending with `\r` is considered incomplete line,
        // since it is unsure which is used as the line ending, `\r` or `\r\n`.
        let next = self.range.get_byte(first_newline + 1)?;
        if next == b'\n' {
            debug_assert!(
                first_newline + 1 < usize::MAX,
                "the string length won't be `usize::MAX` \
                 since other objects (including self) may exist on memory"
            );
            NonZeroUsize::new(first_newline + 2)
        } else {
            NonZeroUsize::new(first_newline + 1)
        }
    }
}

/// Iterators.
impl<'a> CharsRange<'a> {
    /// Returns an iterator of `char`s.
    ///
    /// Incomplete characters are emitted as `U+FFFD REPLACEMENT CHARACTER`.
    /// If you want to ignore them, use [`CharsRange::to_complete`] or
    /// [`CharsRange::trim_last_incomplete_char`] before creating the iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    ///
    /// let queue = StrQueue::from(b"alpha->\xce");
    /// let range = queue.chars_range(..);
    ///
    /// // The trailing incomplete character is replaced with U+FFFD.
    /// assert_eq!(
    ///     range.chars().collect::<String>(),
    ///     "alpha->\u{FFFD}"
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn chars(&self) -> Chars<'_> {
        Chars::from_range(*self)
    }

    /// Returns an iterator of content fragments.
    ///
    /// # Examples
    ///
    /// The code below are redundant since they are intended to show how to use [`Fragment`].
    /// To simply create a string from the queue, use [`StrQueue::display`] method.
    ///
    /// ```
    /// use str_queue::{Fragment, StrQueue};
    ///
    /// // `\xce\xb1` is `\u{03B1}`.
    /// let queue = StrQueue::from(b"hello \xce\xb1");
    /// let range = queue.chars_range(3..7);
    ///
    /// let mut buf = String::new();
    /// for frag in range.fragments() {
    ///     match frag {
    ///         Fragment::Str(s) => buf.push_str(s),
    ///         Fragment::Char(c) => buf.push(c),
    ///         Fragment::Incomplete => buf.push_str("<<incomplete>>"),
    ///     }
    /// }
    /// assert_eq!(buf, "lo <<incomplete>>");
    /// ```
    #[inline]
    #[must_use]
    pub fn fragments(&self) -> Fragments<'_> {
        Fragments::from_range(*self)
    }
}

/// Conversion.
impl<'a> CharsRange<'a> {
    /// Returns the bytes range.
    #[inline]
    #[must_use]
    pub fn to_bytes_range(&self) -> BytesRange<'a> {
        (*self).into()
    }
}

/// Comparison.
impl CharsRange<'_> {
    /// Compares the two chars ranges.
    ///
    /// This comparson is arawe of the existence of the last incomplete
    /// characters, but does not aware of its value.
    /// If you care about the value of the incomplete characters, you should use
    /// bytes comparison.
    ///
    /// If the range has the incomplete character, it is treated as a character
    /// which is smaller than any other characters.
    /// In other words, the comparison result can be thought as
    /// `(lhs.complete(), !lhs.is_complete()).cmp(&(rhs.complete(), !rhs.is_complete()))`.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    /// let queue_f0 = StrQueue::from(b"Hello\xf0");
    /// let range_f0 = queue_f0.chars_range(..);
    ///
    /// // Bytes for incomplete characters are considered the same.
    /// assert_eq!(range_ce, range_f0);
    /// assert_eq!(range_ce.cmp(&range_f0), Ordering::Equal);
    /// // To distinguish incomplete characters, use bytes range.
    /// assert_ne!(range_ce.to_bytes_range(), range_f0.to_bytes_range());
    /// assert_eq!(
    ///     range_ce.to_bytes_range().cmp(&range_f0.to_bytes_range()),
    ///     Ordering::Less
    /// );
    /// ```
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    ///
    /// let queue_none = StrQueue::from(b"Hello");
    /// let range_none = queue_none.chars_range(..);
    /// assert_ne!(range_ce, range_none);
    /// assert_eq!(range_ce.partial_cmp(&range_none), Some(Ordering::Greater));
    ///
    /// let queue_00 = StrQueue::from(b"Hello\x00");
    /// let range_00 = queue_00.chars_range(..);
    /// assert_ne!(range_ce, range_00);
    /// // `\xce` is incomplete, so it is considered smaller than `\x00`.
    /// // Note that `\x00` is a valid ASCII character.
    /// assert_eq!(range_ce.partial_cmp(&range_00), Some(Ordering::Less));
    ///
    /// let queue_ufffd = StrQueue::from("Hello\u{FFFD}");
    /// let range_ufffd = queue_ufffd.chars_range(..);
    /// assert_ne!(range_ce, range_ufffd);
    /// // The incomplete character (which consists of `\xce`) is converted to
    /// // `\u{FFFD}` when displayed, but it is not considered to be the same
    /// // as a valid Unicode character `\u{FFFD}`.
    /// assert_eq!(range_ce.partial_cmp(&range_ufffd), Some(Ordering::Less));
    /// ```
    fn cmp_self(&self, rhs: &Self) -> Ordering {
        let self_has_incomplete = !self.is_complete();
        let rhs_has_incomplete = !rhs.is_complete();
        self.to_complete()
            .range
            .cmp_self(&rhs.to_complete().range)
            .then_with(|| self_has_incomplete.cmp(&rhs_has_incomplete))
    }

    /// Compares the chars range and a string slice.
    ///
    /// If the range has the incomplete character, it is treated as a character
    /// which is smaller than any other characters.
    /// In other words, the comparison result can be thought as
    /// `(range.complete(), !range.is_complete()).cmp(&(rhs, false))`.
    /// The complete part differ from the rhs string slice, that result is
    /// returned regardless of the incomplete character.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_00 = StrQueue::from(b"Hello\x00");
    /// let range_00 = queue_00.chars_range(..);
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    ///
    /// assert_eq!(range_00, "Hello\u{0}");
    /// assert_eq!(range_00.partial_cmp("Hello\u{0}"), Some(Ordering::Equal));
    ///
    /// assert_eq!(range_ce.partial_cmp("Hello"), Some(Ordering::Greater));
    /// // `\xce` is incomplete, so it is considered smaller than `\x00`.
    /// // Note that `\x00` is a valid ASCII character.
    /// assert_eq!(range_ce.partial_cmp("Hello\u{0}"), Some(Ordering::Less));
    /// // The incomplete character (which consists of `\xce`) is converted to
    /// // `\u{FFFD}` when displayed, but it is not considered to be the same
    /// // as a valid Unicode character `\u{FFFD}`.
    /// assert_eq!(range_ce.partial_cmp("Hello\u{FFFD}"), Some(Ordering::Less));
    /// ```
    fn cmp_str(&self, rhs: &str) -> Ordering {
        let (complete, trimmed_len) = self.to_complete_and_trimmed_len();
        let fallback = || {
            if trimmed_len == 0 {
                Ordering::Equal
            } else {
                Ordering::Greater
            }
        };

        let former_len = complete.range.former.len();
        let rhs = rhs.as_bytes();
        let rhs_len = rhs.len();

        if former_len > rhs_len {
            complete.range.former.cmp(rhs).then_with(fallback)
        } else {
            complete
                .range
                .former
                .cmp(&rhs[..former_len])
                .then_with(|| complete.range.latter.cmp(&rhs[former_len..]))
                .then_with(fallback)
        }
    }
}

impl fmt::Display for CharsRange<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Fragments::from(*self).fmt(f)
    }
}

impl<'a> From<CharsRange<'a>> for BytesRange<'a> {
    #[inline]
    fn from(v: CharsRange<'a>) -> Self {
        v.range
    }
}

impl PartialEq for CharsRange<'_> {
    /// Compares the two chars ranges and returns true if they are equal.
    ///
    /// This comparson is arawe of the existence of the last incomplete
    /// characters, but does not aware of its value.
    /// If you care about the value of the incomplete characters, you should use
    /// bytes comparison.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue1 = StrQueue::from(b"Hello\xce");
    /// let range1 = queue1.chars_range(..);
    /// let queue2 = StrQueue::from(b"Hello\xf0");
    /// let range2 = queue2.chars_range(..);
    ///
    /// assert_eq!(range1, range2);
    /// assert_ne!(range1.to_bytes_range(), range2.to_bytes_range());
    /// ```
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        // Return earlily if lengths are not the same.
        (self.len() == other.len()) && self.cmp_self(other).is_eq()
    }
}

impl PartialOrd for CharsRange<'_> {
    /// Compares the two chars ranges.
    ///
    /// This comparson is arawe of the existence of the last incomplete
    /// characters, but does not aware of its value.
    /// If you care about the value of the incomplete characters, you should use
    /// bytes comparison.
    ///
    /// If the range has the incomplete character, it is treated as a character
    /// which is smaller than any other characters.
    /// In other words, the comparison result can be thought as
    /// `(lhs.complete(), !lhs.is_complete()).cmp(&(rhs.complete(), !rhs.is_complete()))`.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    /// let queue_f0 = StrQueue::from(b"Hello\xf0");
    /// let range_f0 = queue_f0.chars_range(..);
    ///
    /// // Bytes for incomplete characters are considered the same.
    /// assert_eq!(range_ce, range_f0);
    /// assert_eq!(range_ce.cmp(&range_f0), Ordering::Equal);
    /// // To distinguish incomplete characters, use bytes range.
    /// assert_ne!(range_ce.to_bytes_range(), range_f0.to_bytes_range());
    /// assert_eq!(
    ///     range_ce.to_bytes_range().cmp(&range_f0.to_bytes_range()),
    ///     Ordering::Less
    /// );
    /// ```
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    ///
    /// let queue_none = StrQueue::from(b"Hello");
    /// let range_none = queue_none.chars_range(..);
    /// assert_ne!(range_ce, range_none);
    /// assert_eq!(range_ce.partial_cmp(&range_none), Some(Ordering::Greater));
    ///
    /// let queue_00 = StrQueue::from(b"Hello\x00");
    /// let range_00 = queue_00.chars_range(..);
    /// assert_ne!(range_ce, range_00);
    /// // `\xce` is incomplete, so it is considered smaller than `\x00`.
    /// // Note that `\x00` is a valid ASCII character.
    /// assert_eq!(range_ce.partial_cmp(&range_00), Some(Ordering::Less));
    ///
    /// let queue_ufffd = StrQueue::from("Hello\u{FFFD}");
    /// let range_ufffd = queue_ufffd.chars_range(..);
    /// assert_ne!(range_ce, range_ufffd);
    /// // The incomplete character (which consists of `\xce`) is converted to
    /// // `\u{FFFD}` when displayed, but it is not considered to be the same
    /// // as a valid Unicode character `\u{FFFD}`.
    /// assert_eq!(range_ce.partial_cmp(&range_ufffd), Some(Ordering::Less));
    /// ```
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        Some(self.cmp_self(rhs))
    }
}

impl Ord for CharsRange<'_> {
    ///
    /// This comparson is arawe of the existence of the last incomplete
    /// characters, but does not aware of its value.
    /// If you care about the value of the incomplete characters, you should use
    /// bytes comparison.
    ///
    /// If the range has the incomplete character, it is treated as a character
    /// which is smaller than any other characters.
    /// In other words, the comparison result can be thought as
    /// `(lhs.complete(), !lhs.is_complete()).cmp(&(rhs.complete(), !rhs.is_complete()))`.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    /// let queue_f0 = StrQueue::from(b"Hello\xf0");
    /// let range_f0 = queue_f0.chars_range(..);
    ///
    /// // Bytes for incomplete characters are considered the same.
    /// assert_eq!(range_ce, range_f0);
    /// assert_eq!(range_ce.cmp(&range_f0), Ordering::Equal);
    /// // To distinguish incomplete characters, use bytes range.
    /// assert_ne!(range_ce.to_bytes_range(), range_f0.to_bytes_range());
    /// assert_eq!(
    ///     range_ce.to_bytes_range().cmp(&range_f0.to_bytes_range()),
    ///     Ordering::Less
    /// );
    /// ```
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    ///
    /// let queue_none = StrQueue::from(b"Hello");
    /// let range_none = queue_none.chars_range(..);
    /// assert_ne!(range_ce, range_none);
    /// assert_eq!(range_ce.partial_cmp(&range_none), Some(Ordering::Greater));
    ///
    /// let queue_00 = StrQueue::from(b"Hello\x00");
    /// let range_00 = queue_00.chars_range(..);
    /// assert_ne!(range_ce, range_00);
    /// // `\xce` is incomplete, so it is considered smaller than `\x00`.
    /// // Note that `\x00` is a valid ASCII character.
    /// assert_eq!(range_ce.partial_cmp(&range_00), Some(Ordering::Less));
    ///
    /// let queue_ufffd = StrQueue::from("Hello\u{FFFD}");
    /// let range_ufffd = queue_ufffd.chars_range(..);
    /// assert_ne!(range_ce, range_ufffd);
    /// // The incomplete character (which consists of `\xce`) is converted to
    /// // `\u{FFFD}` when displayed, but it is not considered to be the same
    /// // as a valid Unicode character `\u{FFFD}`.
    /// assert_eq!(range_ce.partial_cmp(&range_ufffd), Some(Ordering::Less));
    /// ```
    fn cmp(&self, rhs: &Self) -> Ordering {
        self.cmp_self(rhs)
    }
}

impl PartialEq<str> for CharsRange<'_> {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        // Return earlily if lengths are not the same.
        (self.len() == other.len()) && self.cmp_str(other).is_eq()
    }
}

impl PartialOrd<str> for CharsRange<'_> {
    /// Compares the chars range and a string slice.
    ///
    /// If the range has the incomplete character, it is treated as a character
    /// which is smaller than any other characters.
    /// In other words, the comparison result can be thought as
    /// `(range.complete(), !range.is_complete()).cmp(&(rhs, false))`.
    /// The complete part differ from the rhs string slice, that result is
    /// returned regardless of the incomplete character.
    ///
    /// # Examples
    ///
    /// ```
    /// use str_queue::{PartialHandling, StrQueue};
    /// use core::cmp::Ordering;
    ///
    /// let queue_00 = StrQueue::from(b"Hello\x00");
    /// let range_00 = queue_00.chars_range(..);
    /// let queue_ce = StrQueue::from(b"Hello\xce");
    /// let range_ce = queue_ce.chars_range(..);
    ///
    /// assert_eq!(range_00, "Hello\u{0}");
    /// assert_eq!(range_00.partial_cmp("Hello\u{0}"), Some(Ordering::Equal));
    ///
    /// assert_eq!(range_ce.partial_cmp("Hello"), Some(Ordering::Greater));
    /// // `\xce` is incomplete, so it is considered smaller than `\x00`.
    /// // Note that `\x00` is a valid ASCII character.
    /// assert_eq!(range_ce.partial_cmp("Hello\u{0}"), Some(Ordering::Less));
    /// // The incomplete character (which consists of `\xce`) is converted to
    /// // `\u{FFFD}` when displayed, but it is not considered to be the same
    /// // as a valid Unicode character `\u{FFFD}`.
    /// assert_eq!(range_ce.partial_cmp("Hello\u{FFFD}"), Some(Ordering::Less));
    /// ```
    #[inline]
    fn partial_cmp(&self, rhs: &str) -> Option<Ordering> {
        Some(self.cmp_str(rhs))
    }
}

impl PartialEq<CharsRange<'_>> for str {
    #[inline]
    fn eq(&self, other: &CharsRange<'_>) -> bool {
        other.eq(self)
    }
}

impl PartialOrd<CharsRange<'_>> for str {
    #[inline]
    fn partial_cmp(&self, rhs: &CharsRange<'_>) -> Option<Ordering> {
        rhs.partial_cmp(self).map(Ordering::reverse)
    }
}

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

impl PartialOrd<&str> for CharsRange<'_> {
    #[inline]
    fn partial_cmp(&self, rhs: &&str) -> Option<Ordering> {
        self.partial_cmp(*rhs)
    }
}

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

impl PartialOrd<CharsRange<'_>> for &str {
    #[inline]
    fn partial_cmp(&self, rhs: &CharsRange<'_>) -> Option<Ordering> {
        rhs.partial_cmp(*self).map(Ordering::reverse)
    }
}

/// A line popped from [`CharsRange`] using [`pop_line`][`CharsRange::pop_line`] method.
///
/// Note that this may pop a line from `CharsRange`, but `StrQueue` behind the
/// range won't be affected.
///
/// Also note that it is unspecified whether the line will be removed from the
/// queue, if the `CharsRangePoppedLine` value is not dropped while the borrow
/// it holds expires (e.g. due to [`core::mem::forget`]).
#[derive(Debug)]
pub struct CharsRangePoppedLine<'a, 'r> {
    /// Range.
    range: &'r mut CharsRange<'a>,
    /// Line length.
    ///
    /// A complete line cannot be empty since it has a line break.
    line_len: NonZeroUsize,
}

impl<'a, 'r> CharsRangePoppedLine<'a, 'r> {
    /// Returns the chars range for the line.
    #[inline]
    #[must_use]
    pub fn to_chars_range(&self) -> CharsRange<'a> {
        self.range.range(..self.line_len.get())
    }

    /// Returns the bytes range for the line.
    #[inline]
    #[must_use]
    pub fn to_bytes_range(&self) -> BytesRange<'_> {
        self.range.to_bytes_range().range(..self.line_len.get())
    }

    /// Returns the length of the line.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.line_len.get()
    }

    /// Returns whether the line is empty, i.e. **always returns false**.
    ///
    /// A complete line to be removed cannot be empty since it has a line break.
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        false
    }
}

impl fmt::Display for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.to_chars_range().fmt(f)
    }
}

impl core::ops::Drop for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn drop(&mut self) {
        *self.range = self.range.range(self.line_len.get()..);
    }
}

impl PartialEq for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn eq(&self, other: &CharsRangePoppedLine<'_, '_>) -> bool {
        self.to_bytes_range().eq(&other.to_bytes_range())
    }
}

impl Eq for CharsRangePoppedLine<'_, '_> {}

impl PartialOrd for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn partial_cmp(&self, rhs: &CharsRangePoppedLine<'_, '_>) -> Option<Ordering> {
        self.to_bytes_range().partial_cmp(&rhs.to_bytes_range())
    }
}

impl Ord for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn cmp(&self, rhs: &CharsRangePoppedLine<'_, '_>) -> Ordering {
        self.to_bytes_range().cmp(&rhs.to_bytes_range())
    }
}

impl PartialEq<str> for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.to_bytes_range().eq(other.as_bytes())
    }
}

impl PartialOrd<str> for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn partial_cmp(&self, rhs: &str) -> Option<Ordering> {
        self.to_bytes_range().partial_cmp(rhs.as_bytes())
    }
}

impl PartialEq<CharsRangePoppedLine<'_, '_>> for str {
    #[inline]
    fn eq(&self, other: &CharsRangePoppedLine<'_, '_>) -> bool {
        other.to_bytes_range().eq(self.as_bytes())
    }
}

impl PartialOrd<CharsRangePoppedLine<'_, '_>> for str {
    #[inline]
    fn partial_cmp(&self, rhs: &CharsRangePoppedLine<'_, '_>) -> Option<Ordering> {
        rhs.to_bytes_range()
            .partial_cmp(self.as_bytes())
            .map(Ordering::reverse)
    }
}

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

impl PartialOrd<&str> for CharsRangePoppedLine<'_, '_> {
    #[inline]
    fn partial_cmp(&self, rhs: &&str) -> Option<Ordering> {
        self.partial_cmp(*rhs)
    }
}

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

impl PartialOrd<CharsRangePoppedLine<'_, '_>> for &str {
    #[inline]
    fn partial_cmp(&self, rhs: &CharsRangePoppedLine<'_, '_>) -> Option<Ordering> {
        rhs.partial_cmp(*self).map(Ordering::reverse)
    }
}