aboutsummaryrefslogtreecommitdiff
path: root/src/server/parser.rs
blob: da999ea2de019a993aacd319ddd984d80bbba8d0 (plain) (blame)
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
use bytes::BytesMut;

/// Read all commands from the given buffer.
///
/// # Process
/// 1. Get a command from `buffer` based on first byte.
/// 2. Push command to `commands`.
/// 3. Remove command from `buffer`.
/// 4. Iterate and do this for all commands within `buffer`.
pub fn get_commands_from_buffer(mut buffer: BytesMut) -> Vec<BytesMut> {
	let mut commands: Vec<BytesMut> = Vec::new();
	// debug!("initial buffer: {:?}, length: {}", buffer, buffer.len());

	let data_length = buffer.get(0).unwrap().to_owned() as usize;
	if buffer.is_empty() {
		loop {
			// debug!("loop: {:?}, length: {}", buffer, buffer.len());
			let command_length = buffer.get(0).unwrap().to_owned() as usize;
			commands.push(
				BytesMut::from(buffer.get(0..command_length).unwrap())
			);

			// Remove command from buffer
			buffer = buffer.split_off(command_length);

			// Check if any more commands are present
			if buffer.len() == 0 { break; }
		}
	} else {
		// There will always be at least one command, push it.
		commands.push(
			BytesMut::from(buffer.get(0..data_length).unwrap())
		);
	}

	commands // Return command (s)
}