Guest User

Untitled

a guest
Jun 21st, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. use std::iter;
  2.  
  3. #[derive(Debug)]
  4. struct Book {
  5. pub title: String,
  6. }
  7.  
  8. #[derive(Debug)]
  9. struct Library {
  10. pub books: Vec<Book>,
  11. }
  12.  
  13. #[derive(Debug)]
  14. struct LibraryIterator<'b> {
  15. /// Keeps track which index we're currently at.
  16. pub cursor: usize,
  17. /// Borrow of the Bookshelf we're going to iterate over.
  18. pub inner: &'b Library,
  19. }
  20.  
  21. #[derive(Debug)]
  22. struct LibraryIter {
  23. /// Borrow of the Bookshelf we're going to iterate over.
  24. pub inner: Library,
  25. }
  26.  
  27. impl Library {
  28. /// Create an iterator that iterates over all books in the library.
  29. pub fn iter(&self) -> LibraryIterator {
  30. LibraryIterator {
  31. inner: self,
  32. cursor: 0,
  33. }
  34. }
  35. }
  36.  
  37. impl<'b> iter::Iterator for LibraryIterator<'b> {
  38. type Item = &'b Book;
  39.  
  40. fn next(&mut self) -> Option<Self::Item> {
  41. let cursor = self.cursor;
  42. self.cursor += 1;
  43.  
  44. if cursor >= self.inner.books.len() {
  45. None
  46. } else {
  47. Some(&self.inner.books[cursor])
  48. }
  49. }
  50. }
  51.  
  52. impl iter::Iterator for LibraryIter {
  53. type Item = Book;
  54.  
  55. fn next(&mut self) -> Option<Self::Item> {
  56. if self.inner.books.len() > 0 {
  57. Some(self.inner.books.remove(0))
  58. } else {
  59. None
  60. }
  61. }
  62. }
  63.  
  64. impl<'b> iter::IntoIterator for &'b Library {
  65. type Item = &'b Book;
  66. type IntoIter = LibraryIterator<'b>;
  67.  
  68. fn into_iter(self) -> Self::IntoIter {
  69. Self::IntoIter {
  70. cursor: 0,
  71. inner: self,
  72. }
  73. }
  74. }
  75.  
  76. impl<'b> iter::IntoIterator for Library {
  77. type Item = Book;
  78. type IntoIter = LibraryIter;
  79.  
  80. fn into_iter(self) -> Self::IntoIter {
  81. Self::IntoIter {
  82. inner: self,
  83. }
  84. }
  85. }
  86.  
  87. fn main() {
  88. let library = Library {
  89. books: vec![
  90. Book { title: "Das Kapital I".into() },
  91. Book { title: "Das Kapital II".into() },
  92. Book { title: "Das Kapital III".into() },
  93. ],
  94. };
  95.  
  96. // Borrow library and iterate.
  97. for book in library.iter() {
  98. println!("book {}", book.title);
  99. }
  100.  
  101. // Consume library and iterate. `library` can no longer be used after this
  102. // point.
  103. for book in &library {
  104. println!("book {}", book.title);
  105. }
  106.  
  107. for book in library {
  108. println!("book {}", book.title);
  109. }
  110. }
Add Comment
Please, Sign In to add comment