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
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//                    Version 2, December 2004
//
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
//  0. You just DO WHAT THE FUCK YOU WANT TO.

use std::io::{self, Read};
use stream::{self, Entry};
use mail::{Mail, Headers, Body};

pub struct Iter<R: Read> {
	input: stream::Iter<R>,
	body:  bool,
}

impl<R: Read> Iter<R> {
	#[inline]
	pub fn new(input: R) -> Self {
		Iter {
			input: stream::entries(input),
			body:  true,
		}
	}

	#[inline]
	pub fn body(&mut self, value: bool) -> &mut Self {
		self.body = value;
		self
	}
}

impl<R: Read> Iterator for Iter<R> {
	type Item = io::Result<Mail>;

	fn next(&mut self) -> Option<Self::Item> {
		macro_rules! eof {
			($body:expr) => (
				if let Some(value) = $body {
					value
				}
				else {
					return None;
				}
			);
		}

		macro_rules! try {
			($body:expr) => (
				match $body {
					Ok(value) =>
						value,

					Err(err) =>
						return Some(Err(err.into()))
				}
			);
		}

		// The first entry must be an `Entry::Begin`.
		let (offset, origin) = if let Entry::Begin(offset, origin) = try!(eof!(self.input.next())) {
			(offset, origin)
		}
		else {
			return Some(Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid state")));
		};

		let mut headers = Headers::default();
		let mut body    = Body::default();
		let mut ended   = false;

		// Read headers.
		loop {
			match try!(eof!(self.input.next())) {
				// This shouldn't happen.
				Entry::Begin(..) => {
					return Some(Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid state")));
				}

				// Insert the header.
				Entry::Header(header) => {
					headers.insert(header);
				}

				// The body started.
				Entry::Body(value) => {
					if self.body {
						body.append(value);
					}

					break;
				}

				// There was no body.
				Entry::End => {
					ended = true;
					break;
				}
			}
		}

		// Read body if there is one.
		if !ended {
			while let Entry::Body(value) = try!(eof!(self.input.next())) {
				if self.body {
					body.append(value);
				}
			}
		}

		Some(Ok(Mail::new(offset, origin, headers, body)))
	}
}