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
//! Provides a trait for receiving data frames and messages.
//!
//! Also provides iterators over data frames and messages.
//! See the `ws` module documentation for more information.

use result::WebSocketResult;
use std::io::Read;
use ws::dataframe::DataFrame;
use ws::Message;

/// A trait for receiving data frames and messages.
pub trait Receiver: Sized {
	/// The type of dataframe that incoming messages will be serialized to.
	type F: DataFrame;

	/// The type of message that incoming messages will be serialized to.
	type M: Message;

	/// Reads a single data frame from this receiver.
	fn recv_dataframe<R>(&mut self, reader: &mut R) -> WebSocketResult<Self::F>
	where
		R: Read;

	/// Returns the data frames that constitute one message.
	fn recv_message_dataframes<R>(&mut self, reader: &mut R) -> WebSocketResult<Vec<Self::F>>
	where
		R: Read;

	/// Returns an iterator over incoming data frames.
	fn incoming_dataframes<'a, R>(&'a mut self, reader: &'a mut R) -> DataFrameIterator<'a, Self, R>
	where
		R: Read,
	{
		DataFrameIterator {
			reader,
			inner: self,
		}
	}

	/// Reads a single message from this receiver.
	fn recv_message<R>(&mut self, reader: &mut R) -> WebSocketResult<Self::M>
	where
		R: Read,
	{
		let dataframes = self.recv_message_dataframes(reader)?;
		Self::M::from_dataframes(dataframes)
	}

	/// Returns an iterator over incoming messages.
	fn incoming_messages<'a, R>(&'a mut self, reader: &'a mut R) -> MessageIterator<'a, Self, R>
	where
		R: Read,
	{
		MessageIterator {
			reader,
			inner: self,
		}
	}
}

/// An iterator over data frames from a Receiver.
pub struct DataFrameIterator<'a, Recv, R>
where
	Recv: 'a + Receiver,
	R: 'a + Read,
{
	reader: &'a mut R,
	inner: &'a mut Recv,
}

impl<'a, Recv, R> Iterator for DataFrameIterator<'a, Recv, R>
where
	Recv: 'a + Receiver,
	R: Read,
{
	type Item = WebSocketResult<Recv::F>;

	/// Get the next data frame from the receiver. Always returns `Some`.
	fn next(&mut self) -> Option<WebSocketResult<Recv::F>> {
		Some(self.inner.recv_dataframe(self.reader))
	}
}

/// An iterator over messages from a Receiver.
pub struct MessageIterator<'a, Recv, R>
where
	Recv: 'a + Receiver,
	R: 'a + Read,
{
	reader: &'a mut R,
	inner: &'a mut Recv,
}

impl<'a, Recv, R> Iterator for MessageIterator<'a, Recv, R>
where
	Recv: 'a + Receiver,
	R: Read,
{
	type Item = WebSocketResult<Recv::M>;

	/// Get the next message from the receiver. Always returns `Some`.
	fn next(&mut self) -> Option<WebSocketResult<Recv::M>> {
		Some(self.inner.recv_message(self.reader))
	}
}