]> git.proxmox.com Git - cargo.git/blob - vendor/syn/src/punctuated.rs
New upstream version 0.47.0
[cargo.git] / vendor / syn / src / punctuated.rs
1 //! A punctuated sequence of syntax tree nodes separated by punctuation.
2 //!
3 //! Lots of things in Rust are punctuated sequences.
4 //!
5 //! - The fields of a struct are `Punctuated<Field, Token![,]>`.
6 //! - The segments of a path are `Punctuated<PathSegment, Token![::]>`.
7 //! - The bounds on a generic parameter are `Punctuated<TypeParamBound,
8 //! Token![+]>`.
9 //! - The arguments to a function call are `Punctuated<Expr, Token![,]>`.
10 //!
11 //! This module provides a common representation for these punctuated sequences
12 //! in the form of the [`Punctuated<T, P>`] type. We store a vector of pairs of
13 //! syntax tree node + punctuation, where every node in the sequence is followed
14 //! by punctuation except for possibly the final one.
15 //!
16 //! [`Punctuated<T, P>`]: struct.Punctuated.html
17 //!
18 //! ```text
19 //! a_function_call(arg1, arg2, arg3);
20 //! ~~~~^ ~~~~^ ~~~~
21 //! ```
22
23 #[cfg(feature = "extra-traits")]
24 use std::fmt::{self, Debug};
25 #[cfg(feature = "extra-traits")]
26 use std::hash::{Hash, Hasher};
27 #[cfg(any(feature = "full", feature = "derive"))]
28 use std::iter;
29 use std::iter::FromIterator;
30 use std::ops::{Index, IndexMut};
31 use std::option;
32 use std::slice;
33 use std::vec;
34
35 #[cfg(feature = "parsing")]
36 use crate::parse::{Parse, ParseStream, Result};
37 #[cfg(feature = "parsing")]
38 use crate::token::Token;
39
40 /// A punctuated sequence of syntax tree nodes of type `T` separated by
41 /// punctuation of type `P`.
42 ///
43 /// Refer to the [module documentation] for details about punctuated sequences.
44 ///
45 /// [module documentation]: self
46 pub struct Punctuated<T, P> {
47 inner: Vec<(T, P)>,
48 last: Option<Box<T>>,
49 }
50
51 impl<T, P> Punctuated<T, P> {
52 /// Creates an empty punctuated sequence.
53 pub fn new() -> Punctuated<T, P> {
54 Punctuated {
55 inner: Vec::new(),
56 last: None,
57 }
58 }
59
60 /// Determines whether this punctuated sequence is empty, meaning it
61 /// contains no syntax tree nodes or punctuation.
62 pub fn is_empty(&self) -> bool {
63 self.inner.len() == 0 && self.last.is_none()
64 }
65
66 /// Returns the number of syntax tree nodes in this punctuated sequence.
67 ///
68 /// This is the number of nodes of type `T`, not counting the punctuation of
69 /// type `P`.
70 pub fn len(&self) -> usize {
71 self.inner.len() + if self.last.is_some() { 1 } else { 0 }
72 }
73
74 /// Borrows the first element in this sequence.
75 pub fn first(&self) -> Option<&T> {
76 self.iter().next()
77 }
78
79 /// Mutably borrows the first element in this sequence.
80 pub fn first_mut(&mut self) -> Option<&mut T> {
81 self.iter_mut().next()
82 }
83
84 /// Borrows the last element in this sequence.
85 pub fn last(&self) -> Option<&T> {
86 self.iter().next_back()
87 }
88
89 /// Mutably borrows the last element in this sequence.
90 pub fn last_mut(&mut self) -> Option<&mut T> {
91 self.iter_mut().next_back()
92 }
93
94 /// Returns an iterator over borrowed syntax tree nodes of type `&T`.
95 pub fn iter(&self) -> Iter<T> {
96 Iter {
97 inner: Box::new(PrivateIter {
98 inner: self.inner.iter(),
99 last: self.last.as_ref().map(Box::as_ref).into_iter(),
100 }),
101 }
102 }
103
104 /// Returns an iterator over mutably borrowed syntax tree nodes of type
105 /// `&mut T`.
106 pub fn iter_mut(&mut self) -> IterMut<T> {
107 IterMut {
108 inner: Box::new(PrivateIterMut {
109 inner: self.inner.iter_mut(),
110 last: self.last.as_mut().map(Box::as_mut).into_iter(),
111 }),
112 }
113 }
114
115 /// Returns an iterator over the contents of this sequence as borrowed
116 /// punctuated pairs.
117 pub fn pairs(&self) -> Pairs<T, P> {
118 Pairs {
119 inner: self.inner.iter(),
120 last: self.last.as_ref().map(Box::as_ref).into_iter(),
121 }
122 }
123
124 /// Returns an iterator over the contents of this sequence as mutably
125 /// borrowed punctuated pairs.
126 pub fn pairs_mut(&mut self) -> PairsMut<T, P> {
127 PairsMut {
128 inner: self.inner.iter_mut(),
129 last: self.last.as_mut().map(Box::as_mut).into_iter(),
130 }
131 }
132
133 /// Returns an iterator over the contents of this sequence as owned
134 /// punctuated pairs.
135 pub fn into_pairs(self) -> IntoPairs<T, P> {
136 IntoPairs {
137 inner: self.inner.into_iter(),
138 last: self.last.map(|t| *t).into_iter(),
139 }
140 }
141
142 /// Appends a syntax tree node onto the end of this punctuated sequence. The
143 /// sequence must previously have a trailing punctuation.
144 ///
145 /// Use [`push`] instead if the punctuated sequence may or may not already
146 /// have trailing punctuation.
147 ///
148 /// [`push`]: Punctuated::push
149 ///
150 /// # Panics
151 ///
152 /// Panics if the sequence does not already have a trailing punctuation when
153 /// this method is called.
154 pub fn push_value(&mut self, value: T) {
155 assert!(self.empty_or_trailing());
156 self.last = Some(Box::new(value));
157 }
158
159 /// Appends a trailing punctuation onto the end of this punctuated sequence.
160 /// The sequence must be non-empty and must not already have trailing
161 /// punctuation.
162 ///
163 /// # Panics
164 ///
165 /// Panics if the sequence is empty or already has a trailing punctuation.
166 pub fn push_punct(&mut self, punctuation: P) {
167 assert!(self.last.is_some());
168 let last = self.last.take().unwrap();
169 self.inner.push((*last, punctuation));
170 }
171
172 /// Removes the last punctuated pair from this sequence, or `None` if the
173 /// sequence is empty.
174 pub fn pop(&mut self) -> Option<Pair<T, P>> {
175 if self.last.is_some() {
176 self.last.take().map(|t| Pair::End(*t))
177 } else {
178 self.inner.pop().map(|(t, d)| Pair::Punctuated(t, d))
179 }
180 }
181
182 /// Determines whether this punctuated sequence ends with a trailing
183 /// punctuation.
184 pub fn trailing_punct(&self) -> bool {
185 self.last.is_none() && !self.is_empty()
186 }
187
188 /// Returns true if either this `Punctuated` is empty, or it has a trailing
189 /// punctuation.
190 ///
191 /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`.
192 pub fn empty_or_trailing(&self) -> bool {
193 self.last.is_none()
194 }
195
196 /// Appends a syntax tree node onto the end of this punctuated sequence.
197 ///
198 /// If there is not a trailing punctuation in this sequence when this method
199 /// is called, the default value of punctuation type `P` is inserted before
200 /// the given value of type `T`.
201 pub fn push(&mut self, value: T)
202 where
203 P: Default,
204 {
205 if !self.empty_or_trailing() {
206 self.push_punct(Default::default());
207 }
208 self.push_value(value);
209 }
210
211 /// Inserts an element at position `index`.
212 ///
213 /// # Panics
214 ///
215 /// Panics if `index` is greater than the number of elements previously in
216 /// this punctuated sequence.
217 pub fn insert(&mut self, index: usize, value: T)
218 where
219 P: Default,
220 {
221 assert!(index <= self.len());
222
223 if index == self.len() {
224 self.push(value);
225 } else {
226 self.inner.insert(index, (value, Default::default()));
227 }
228 }
229
230 /// Clears the sequence of all values and punctuation, making it empty.
231 pub fn clear(&mut self) {
232 self.inner.clear();
233 self.last = None;
234 }
235
236 /// Parses zero or more occurrences of `T` separated by punctuation of type
237 /// `P`, with optional trailing punctuation.
238 ///
239 /// Parsing continues until the end of this parse stream. The entire content
240 /// of this parse stream must consist of `T` and `P`.
241 ///
242 /// *This function is available only if Syn is built with the `"parsing"`
243 /// feature.*
244 #[cfg(feature = "parsing")]
245 pub fn parse_terminated(input: ParseStream) -> Result<Self>
246 where
247 T: Parse,
248 P: Parse,
249 {
250 Self::parse_terminated_with(input, T::parse)
251 }
252
253 /// Parses zero or more occurrences of `T` using the given parse function,
254 /// separated by punctuation of type `P`, with optional trailing
255 /// punctuation.
256 ///
257 /// Like [`parse_terminated`], the entire content of this stream is expected
258 /// to be parsed.
259 ///
260 /// [`parse_terminated`]: Punctuated::parse_terminated
261 ///
262 /// *This function is available only if Syn is built with the `"parsing"`
263 /// feature.*
264 #[cfg(feature = "parsing")]
265 pub fn parse_terminated_with(
266 input: ParseStream,
267 parser: fn(ParseStream) -> Result<T>,
268 ) -> Result<Self>
269 where
270 P: Parse,
271 {
272 let mut punctuated = Punctuated::new();
273
274 loop {
275 if input.is_empty() {
276 break;
277 }
278 let value = parser(input)?;
279 punctuated.push_value(value);
280 if input.is_empty() {
281 break;
282 }
283 let punct = input.parse()?;
284 punctuated.push_punct(punct);
285 }
286
287 Ok(punctuated)
288 }
289
290 /// Parses one or more occurrences of `T` separated by punctuation of type
291 /// `P`, not accepting trailing punctuation.
292 ///
293 /// Parsing continues as long as punctuation `P` is present at the head of
294 /// the stream. This method returns upon parsing a `T` and observing that it
295 /// is not followed by a `P`, even if there are remaining tokens in the
296 /// stream.
297 ///
298 /// *This function is available only if Syn is built with the `"parsing"`
299 /// feature.*
300 #[cfg(feature = "parsing")]
301 pub fn parse_separated_nonempty(input: ParseStream) -> Result<Self>
302 where
303 T: Parse,
304 P: Token + Parse,
305 {
306 Self::parse_separated_nonempty_with(input, T::parse)
307 }
308
309 /// Parses one or more occurrences of `T` using the given parse function,
310 /// separated by punctuation of type `P`, not accepting trailing
311 /// punctuation.
312 ///
313 /// Like [`parse_separated_nonempty`], may complete early without parsing
314 /// the entire content of this stream.
315 ///
316 /// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
317 ///
318 /// *This function is available only if Syn is built with the `"parsing"`
319 /// feature.*
320 #[cfg(feature = "parsing")]
321 pub fn parse_separated_nonempty_with(
322 input: ParseStream,
323 parser: fn(ParseStream) -> Result<T>,
324 ) -> Result<Self>
325 where
326 P: Token + Parse,
327 {
328 let mut punctuated = Punctuated::new();
329
330 loop {
331 let value = parser(input)?;
332 punctuated.push_value(value);
333 if !P::peek(input.cursor()) {
334 break;
335 }
336 let punct = input.parse()?;
337 punctuated.push_punct(punct);
338 }
339
340 Ok(punctuated)
341 }
342 }
343
344 #[cfg(feature = "clone-impls")]
345 impl<T, P> Clone for Punctuated<T, P>
346 where
347 T: Clone,
348 P: Clone,
349 {
350 fn clone(&self) -> Self {
351 Punctuated {
352 inner: self.inner.clone(),
353 last: self.last.clone(),
354 }
355 }
356 }
357
358 #[cfg(feature = "extra-traits")]
359 impl<T, P> Eq for Punctuated<T, P>
360 where
361 T: Eq,
362 P: Eq,
363 {
364 }
365
366 #[cfg(feature = "extra-traits")]
367 impl<T, P> PartialEq for Punctuated<T, P>
368 where
369 T: PartialEq,
370 P: PartialEq,
371 {
372 fn eq(&self, other: &Self) -> bool {
373 let Punctuated { inner, last } = self;
374 *inner == other.inner && *last == other.last
375 }
376 }
377
378 #[cfg(feature = "extra-traits")]
379 impl<T, P> Hash for Punctuated<T, P>
380 where
381 T: Hash,
382 P: Hash,
383 {
384 fn hash<H: Hasher>(&self, state: &mut H) {
385 let Punctuated { inner, last } = self;
386 inner.hash(state);
387 last.hash(state);
388 }
389 }
390
391 #[cfg(feature = "extra-traits")]
392 impl<T: Debug, P: Debug> Debug for Punctuated<T, P> {
393 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
394 let mut list = f.debug_list();
395 for (t, p) in &self.inner {
396 list.entry(t);
397 list.entry(p);
398 }
399 if let Some(last) = &self.last {
400 list.entry(last);
401 }
402 list.finish()
403 }
404 }
405
406 impl<T, P> FromIterator<T> for Punctuated<T, P>
407 where
408 P: Default,
409 {
410 fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self {
411 let mut ret = Punctuated::new();
412 ret.extend(i);
413 ret
414 }
415 }
416
417 impl<T, P> Extend<T> for Punctuated<T, P>
418 where
419 P: Default,
420 {
421 fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) {
422 for value in i {
423 self.push(value);
424 }
425 }
426 }
427
428 impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> {
429 fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self {
430 let mut ret = Punctuated::new();
431 ret.extend(i);
432 ret
433 }
434 }
435
436 impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> {
437 fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) {
438 assert!(self.empty_or_trailing());
439 let mut nomore = false;
440 for pair in i {
441 if nomore {
442 panic!("Punctuated extended with items after a Pair::End");
443 }
444 match pair {
445 Pair::Punctuated(a, b) => self.inner.push((a, b)),
446 Pair::End(a) => {
447 self.last = Some(Box::new(a));
448 nomore = true;
449 }
450 }
451 }
452 }
453 }
454
455 impl<T, P> IntoIterator for Punctuated<T, P> {
456 type Item = T;
457 type IntoIter = IntoIter<T>;
458
459 fn into_iter(self) -> Self::IntoIter {
460 let mut elements = Vec::with_capacity(self.len());
461 elements.extend(self.inner.into_iter().map(|pair| pair.0));
462 elements.extend(self.last.map(|t| *t));
463
464 IntoIter {
465 inner: elements.into_iter(),
466 }
467 }
468 }
469
470 impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> {
471 type Item = &'a T;
472 type IntoIter = Iter<'a, T>;
473
474 fn into_iter(self) -> Self::IntoIter {
475 Punctuated::iter(self)
476 }
477 }
478
479 impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> {
480 type Item = &'a mut T;
481 type IntoIter = IterMut<'a, T>;
482
483 fn into_iter(self) -> Self::IntoIter {
484 Punctuated::iter_mut(self)
485 }
486 }
487
488 impl<T, P> Default for Punctuated<T, P> {
489 fn default() -> Self {
490 Punctuated::new()
491 }
492 }
493
494 /// An iterator over borrowed pairs of type `Pair<&T, &P>`.
495 ///
496 /// Refer to the [module documentation] for details about punctuated sequences.
497 ///
498 /// [module documentation]: self
499 pub struct Pairs<'a, T: 'a, P: 'a> {
500 inner: slice::Iter<'a, (T, P)>,
501 last: option::IntoIter<&'a T>,
502 }
503
504 impl<'a, T, P> Iterator for Pairs<'a, T, P> {
505 type Item = Pair<&'a T, &'a P>;
506
507 fn next(&mut self) -> Option<Self::Item> {
508 self.inner
509 .next()
510 .map(|(t, p)| Pair::Punctuated(t, p))
511 .or_else(|| self.last.next().map(Pair::End))
512 }
513
514 fn size_hint(&self) -> (usize, Option<usize>) {
515 (self.len(), Some(self.len()))
516 }
517 }
518
519 impl<'a, T, P> DoubleEndedIterator for Pairs<'a, T, P> {
520 fn next_back(&mut self) -> Option<Self::Item> {
521 self.last
522 .next()
523 .map(Pair::End)
524 .or_else(|| self.inner.next_back().map(|(t, p)| Pair::Punctuated(t, p)))
525 }
526 }
527
528 impl<'a, T, P> ExactSizeIterator for Pairs<'a, T, P> {
529 fn len(&self) -> usize {
530 self.inner.len() + self.last.len()
531 }
532 }
533
534 // No Clone bound on T or P.
535 impl<'a, T, P> Clone for Pairs<'a, T, P> {
536 fn clone(&self) -> Self {
537 Pairs {
538 inner: self.inner.clone(),
539 last: self.last.clone(),
540 }
541 }
542 }
543
544 /// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`.
545 ///
546 /// Refer to the [module documentation] for details about punctuated sequences.
547 ///
548 /// [module documentation]: self
549 pub struct PairsMut<'a, T: 'a, P: 'a> {
550 inner: slice::IterMut<'a, (T, P)>,
551 last: option::IntoIter<&'a mut T>,
552 }
553
554 impl<'a, T, P> Iterator for PairsMut<'a, T, P> {
555 type Item = Pair<&'a mut T, &'a mut P>;
556
557 fn next(&mut self) -> Option<Self::Item> {
558 self.inner
559 .next()
560 .map(|(t, p)| Pair::Punctuated(t, p))
561 .or_else(|| self.last.next().map(Pair::End))
562 }
563
564 fn size_hint(&self) -> (usize, Option<usize>) {
565 (self.len(), Some(self.len()))
566 }
567 }
568
569 impl<'a, T, P> DoubleEndedIterator for PairsMut<'a, T, P> {
570 fn next_back(&mut self) -> Option<Self::Item> {
571 self.last
572 .next()
573 .map(Pair::End)
574 .or_else(|| self.inner.next_back().map(|(t, p)| Pair::Punctuated(t, p)))
575 }
576 }
577
578 impl<'a, T, P> ExactSizeIterator for PairsMut<'a, T, P> {
579 fn len(&self) -> usize {
580 self.inner.len() + self.last.len()
581 }
582 }
583
584 /// An iterator over owned pairs of type `Pair<T, P>`.
585 ///
586 /// Refer to the [module documentation] for details about punctuated sequences.
587 ///
588 /// [module documentation]: self
589 pub struct IntoPairs<T, P> {
590 inner: vec::IntoIter<(T, P)>,
591 last: option::IntoIter<T>,
592 }
593
594 impl<T, P> Iterator for IntoPairs<T, P> {
595 type Item = Pair<T, P>;
596
597 fn next(&mut self) -> Option<Self::Item> {
598 self.inner
599 .next()
600 .map(|(t, p)| Pair::Punctuated(t, p))
601 .or_else(|| self.last.next().map(Pair::End))
602 }
603
604 fn size_hint(&self) -> (usize, Option<usize>) {
605 (self.len(), Some(self.len()))
606 }
607 }
608
609 impl<T, P> DoubleEndedIterator for IntoPairs<T, P> {
610 fn next_back(&mut self) -> Option<Self::Item> {
611 self.last
612 .next()
613 .map(Pair::End)
614 .or_else(|| self.inner.next_back().map(|(t, p)| Pair::Punctuated(t, p)))
615 }
616 }
617
618 impl<T, P> ExactSizeIterator for IntoPairs<T, P> {
619 fn len(&self) -> usize {
620 self.inner.len() + self.last.len()
621 }
622 }
623
624 impl<T, P> Clone for IntoPairs<T, P>
625 where
626 T: Clone,
627 P: Clone,
628 {
629 fn clone(&self) -> Self {
630 IntoPairs {
631 inner: self.inner.clone(),
632 last: self.last.clone(),
633 }
634 }
635 }
636
637 /// An iterator over owned values of type `T`.
638 ///
639 /// Refer to the [module documentation] for details about punctuated sequences.
640 ///
641 /// [module documentation]: self
642 pub struct IntoIter<T> {
643 inner: vec::IntoIter<T>,
644 }
645
646 impl<T> Iterator for IntoIter<T> {
647 type Item = T;
648
649 fn next(&mut self) -> Option<Self::Item> {
650 self.inner.next()
651 }
652
653 fn size_hint(&self) -> (usize, Option<usize>) {
654 (self.len(), Some(self.len()))
655 }
656 }
657
658 impl<T> DoubleEndedIterator for IntoIter<T> {
659 fn next_back(&mut self) -> Option<Self::Item> {
660 self.inner.next_back()
661 }
662 }
663
664 impl<T> ExactSizeIterator for IntoIter<T> {
665 fn len(&self) -> usize {
666 self.inner.len()
667 }
668 }
669
670 impl<T> Clone for IntoIter<T>
671 where
672 T: Clone,
673 {
674 fn clone(&self) -> Self {
675 IntoIter {
676 inner: self.inner.clone(),
677 }
678 }
679 }
680
681 /// An iterator over borrowed values of type `&T`.
682 ///
683 /// Refer to the [module documentation] for details about punctuated sequences.
684 ///
685 /// [module documentation]: self
686 pub struct Iter<'a, T: 'a> {
687 // The `Item = &'a T` needs to be specified to support rustc 1.31 and older.
688 // On modern compilers we would be able to write just IterTrait<'a, T> where
689 // Item can be inferred unambiguously from the supertrait.
690 inner: Box<dyn IterTrait<'a, T, Item = &'a T> + 'a>,
691 }
692
693 trait IterTrait<'a, T: 'a>:
694 DoubleEndedIterator<Item = &'a T> + ExactSizeIterator<Item = &'a T>
695 {
696 fn clone_box(&self) -> Box<dyn IterTrait<'a, T, Item = &'a T> + 'a>;
697 }
698
699 struct PrivateIter<'a, T: 'a, P: 'a> {
700 inner: slice::Iter<'a, (T, P)>,
701 last: option::IntoIter<&'a T>,
702 }
703
704 #[cfg(any(feature = "full", feature = "derive"))]
705 pub(crate) fn empty_punctuated_iter<'a, T>() -> Iter<'a, T> {
706 Iter {
707 inner: Box::new(iter::empty()),
708 }
709 }
710
711 // No Clone bound on T.
712 impl<'a, T> Clone for Iter<'a, T> {
713 fn clone(&self) -> Self {
714 Iter {
715 inner: self.inner.clone_box(),
716 }
717 }
718 }
719
720 impl<'a, T> Iterator for Iter<'a, T> {
721 type Item = &'a T;
722
723 fn next(&mut self) -> Option<Self::Item> {
724 self.inner.next()
725 }
726
727 fn size_hint(&self) -> (usize, Option<usize>) {
728 (self.len(), Some(self.len()))
729 }
730 }
731
732 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
733 fn next_back(&mut self) -> Option<Self::Item> {
734 self.inner.next_back()
735 }
736 }
737
738 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
739 fn len(&self) -> usize {
740 self.inner.len()
741 }
742 }
743
744 impl<'a, T, P> Iterator for PrivateIter<'a, T, P> {
745 type Item = &'a T;
746
747 fn next(&mut self) -> Option<Self::Item> {
748 self.inner
749 .next()
750 .map(|pair| &pair.0)
751 .or_else(|| self.last.next())
752 }
753 }
754
755 impl<'a, T, P> DoubleEndedIterator for PrivateIter<'a, T, P> {
756 fn next_back(&mut self) -> Option<Self::Item> {
757 self.last
758 .next()
759 .or_else(|| self.inner.next_back().map(|pair| &pair.0))
760 }
761 }
762
763 impl<'a, T, P> ExactSizeIterator for PrivateIter<'a, T, P> {
764 fn len(&self) -> usize {
765 self.inner.len() + self.last.len()
766 }
767 }
768
769 // No Clone bound on T or P.
770 impl<'a, T, P> Clone for PrivateIter<'a, T, P> {
771 fn clone(&self) -> Self {
772 PrivateIter {
773 inner: self.inner.clone(),
774 last: self.last.clone(),
775 }
776 }
777 }
778
779 impl<'a, T: 'a, I: 'a> IterTrait<'a, T> for I
780 where
781 I: DoubleEndedIterator<Item = &'a T> + ExactSizeIterator<Item = &'a T> + Clone,
782 {
783 fn clone_box(&self) -> Box<dyn IterTrait<'a, T, Item = &'a T> + 'a> {
784 Box::new(self.clone())
785 }
786 }
787
788 /// An iterator over mutably borrowed values of type `&mut T`.
789 ///
790 /// Refer to the [module documentation] for details about punctuated sequences.
791 ///
792 /// [module documentation]: self
793 pub struct IterMut<'a, T: 'a> {
794 inner: Box<dyn IterMutTrait<'a, T, Item = &'a mut T> + 'a>,
795 }
796
797 trait IterMutTrait<'a, T: 'a>:
798 DoubleEndedIterator<Item = &'a mut T> + ExactSizeIterator<Item = &'a mut T>
799 {
800 }
801
802 struct PrivateIterMut<'a, T: 'a, P: 'a> {
803 inner: slice::IterMut<'a, (T, P)>,
804 last: option::IntoIter<&'a mut T>,
805 }
806
807 #[cfg(any(feature = "full", feature = "derive"))]
808 pub(crate) fn empty_punctuated_iter_mut<'a, T>() -> IterMut<'a, T> {
809 IterMut {
810 inner: Box::new(iter::empty()),
811 }
812 }
813
814 impl<'a, T> Iterator for IterMut<'a, T> {
815 type Item = &'a mut T;
816
817 fn next(&mut self) -> Option<Self::Item> {
818 self.inner.next()
819 }
820
821 fn size_hint(&self) -> (usize, Option<usize>) {
822 (self.len(), Some(self.len()))
823 }
824 }
825
826 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
827 fn next_back(&mut self) -> Option<Self::Item> {
828 self.inner.next_back()
829 }
830 }
831
832 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
833 fn len(&self) -> usize {
834 self.inner.len()
835 }
836 }
837
838 impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> {
839 type Item = &'a mut T;
840
841 fn next(&mut self) -> Option<Self::Item> {
842 self.inner
843 .next()
844 .map(|pair| &mut pair.0)
845 .or_else(|| self.last.next())
846 }
847 }
848
849 impl<'a, T, P> DoubleEndedIterator for PrivateIterMut<'a, T, P> {
850 fn next_back(&mut self) -> Option<Self::Item> {
851 self.last
852 .next()
853 .or_else(|| self.inner.next_back().map(|pair| &mut pair.0))
854 }
855 }
856
857 impl<'a, T, P> ExactSizeIterator for PrivateIterMut<'a, T, P> {
858 fn len(&self) -> usize {
859 self.inner.len() + self.last.len()
860 }
861 }
862
863 impl<'a, T: 'a, I: 'a> IterMutTrait<'a, T> for I where
864 I: DoubleEndedIterator<Item = &'a mut T> + ExactSizeIterator<Item = &'a mut T>
865 {
866 }
867
868 /// A single syntax tree node of type `T` followed by its trailing punctuation
869 /// of type `P` if any.
870 ///
871 /// Refer to the [module documentation] for details about punctuated sequences.
872 ///
873 /// [module documentation]: self
874 pub enum Pair<T, P> {
875 Punctuated(T, P),
876 End(T),
877 }
878
879 impl<T, P> Pair<T, P> {
880 /// Extracts the syntax tree node from this punctuated pair, discarding the
881 /// following punctuation.
882 pub fn into_value(self) -> T {
883 match self {
884 Pair::Punctuated(t, _) | Pair::End(t) => t,
885 }
886 }
887
888 /// Borrows the syntax tree node from this punctuated pair.
889 pub fn value(&self) -> &T {
890 match self {
891 Pair::Punctuated(t, _) | Pair::End(t) => t,
892 }
893 }
894
895 /// Mutably borrows the syntax tree node from this punctuated pair.
896 pub fn value_mut(&mut self) -> &mut T {
897 match self {
898 Pair::Punctuated(t, _) | Pair::End(t) => t,
899 }
900 }
901
902 /// Borrows the punctuation from this punctuated pair, unless this pair is
903 /// the final one and there is no trailing punctuation.
904 pub fn punct(&self) -> Option<&P> {
905 match self {
906 Pair::Punctuated(_, d) => Some(d),
907 Pair::End(_) => None,
908 }
909 }
910
911 /// Creates a punctuated pair out of a syntax tree node and an optional
912 /// following punctuation.
913 pub fn new(t: T, d: Option<P>) -> Self {
914 match d {
915 Some(d) => Pair::Punctuated(t, d),
916 None => Pair::End(t),
917 }
918 }
919
920 /// Produces this punctuated pair as a tuple of syntax tree node and
921 /// optional following punctuation.
922 pub fn into_tuple(self) -> (T, Option<P>) {
923 match self {
924 Pair::Punctuated(t, d) => (t, Some(d)),
925 Pair::End(t) => (t, None),
926 }
927 }
928 }
929
930 #[cfg(feature = "clone-impls")]
931 impl<T, P> Clone for Pair<T, P>
932 where
933 T: Clone,
934 P: Clone,
935 {
936 fn clone(&self) -> Self {
937 match self {
938 Pair::Punctuated(t, p) => Pair::Punctuated(t.clone(), p.clone()),
939 Pair::End(t) => Pair::End(t.clone()),
940 }
941 }
942 }
943
944 impl<T, P> Index<usize> for Punctuated<T, P> {
945 type Output = T;
946
947 fn index(&self, index: usize) -> &Self::Output {
948 if index == self.len() - 1 {
949 match &self.last {
950 Some(t) => t,
951 None => &self.inner[index].0,
952 }
953 } else {
954 &self.inner[index].0
955 }
956 }
957 }
958
959 impl<T, P> IndexMut<usize> for Punctuated<T, P> {
960 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
961 if index == self.len() - 1 {
962 match &mut self.last {
963 Some(t) => t,
964 None => &mut self.inner[index].0,
965 }
966 } else {
967 &mut self.inner[index].0
968 }
969 }
970 }
971
972 #[cfg(feature = "printing")]
973 mod printing {
974 use super::*;
975 use proc_macro2::TokenStream;
976 use quote::{ToTokens, TokenStreamExt};
977
978 impl<T, P> ToTokens for Punctuated<T, P>
979 where
980 T: ToTokens,
981 P: ToTokens,
982 {
983 fn to_tokens(&self, tokens: &mut TokenStream) {
984 tokens.append_all(self.pairs())
985 }
986 }
987
988 impl<T, P> ToTokens for Pair<T, P>
989 where
990 T: ToTokens,
991 P: ToTokens,
992 {
993 fn to_tokens(&self, tokens: &mut TokenStream) {
994 match self {
995 Pair::Punctuated(a, b) => {
996 a.to_tokens(tokens);
997 b.to_tokens(tokens);
998 }
999 Pair::End(a) => a.to_tokens(tokens),
1000 }
1001 }
1002 }
1003 }