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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
//! Collects X11 data into "packets" to be parsed by a display.
use core::convert::TryInto;
use core::fmt;
use core::mem::replace;
use alloc::{vec, vec::Vec};
/// Minimal length of an X11 packet.
const MINIMAL_PACKET_LENGTH: usize = 32;
/// A wrapper around a buffer used to read X11 packets.
pub struct PacketReader {
/// A partially-read packet.
pending_packet: Vec<u8>,
/// The point at which the packet is already read.
already_read: usize,
}
impl fmt::Debug for PacketReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PacketReader")
.field(&format_args!(
"{}/{}",
self.already_read,
self.pending_packet.len()
))
.finish()
}
}
impl Default for PacketReader {
fn default() -> Self {
Self::new()
}
}
impl PacketReader {
/// Create a new, empty `PacketReader`.
///
/// # Example
///
/// ```rust
/// # use x11rb_protocol::packet_reader::PacketReader;
/// let reader = PacketReader::new();
/// ```
pub fn new() -> Self {
Self {
pending_packet: vec![0; MINIMAL_PACKET_LENGTH],
already_read: 0,
}
}
/// Get the buffer that the reader should fill with data.
///
/// # Example
///
/// ```rust
/// # use x11rb_protocol::packet_reader::PacketReader;
/// # use x11rb_protocol::protocol::xproto::{GetInputFocusReply, InputFocus, Window};
/// let mut reader = PacketReader::new();
/// let buffer: [u8; 32] = read_in_buffer();
///
/// reader.buffer().copy_from_slice(&buffer);
///
/// # fn read_in_buffer() -> [u8; 32] { [0; 32] }
/// ```
pub fn buffer(&mut self) -> &mut [u8] {
&mut self.pending_packet[self.already_read..]
}
/// The remaining capacity that needs to be filled.
pub fn remaining_capacity(&self) -> usize {
self.pending_packet.len() - self.already_read
}
/// Advance this buffer by the given amount.
///
/// This will return the packet that was read, if enough bytes were read in order
/// to form a complete packet.
pub fn advance(&mut self, amount: usize) -> Option<Vec<u8>> {
self.already_read += amount;
debug_assert!(self.already_read <= self.pending_packet.len());
if self.already_read == MINIMAL_PACKET_LENGTH {
// we've read in the minimal packet, compute the amount of data we need to read
// to form a complete packet
let extra_length = extra_length(&self.pending_packet);
// tell if we need to read more
if extra_length > 0 {
let total_length = MINIMAL_PACKET_LENGTH + extra_length;
self.pending_packet.resize(total_length, 0);
return None;
}
} else if self.already_read != self.pending_packet.len() {
// we haven't read the full packet yet, return
return None;
}
// we've read in the full packet, return it
self.already_read = 0;
Some(replace(
&mut self.pending_packet,
vec![0; MINIMAL_PACKET_LENGTH],
))
}
}
/// Compute the length of the data we need to read, beyond the `MINIMAL_PACKET_LENGTH`.
fn extra_length(buffer: &[u8]) -> usize {
use crate::protocol::xproto::GE_GENERIC_EVENT;
const REPLY: u8 = 1;
let response_type = buffer[0];
if response_type == REPLY || response_type & 0x7f == GE_GENERIC_EVENT {
let length_field = buffer[4..8].try_into().unwrap();
let length_field = u32::from_ne_bytes(length_field) as usize;
4 * length_field
} else {
// Fixed size packet: error or event that is not GE_GENERIC_EVENT
0
}
}
#[cfg(test)]
mod tests {
use super::PacketReader;
use alloc::{vec, vec::Vec};
fn test_packets(packets: Vec<Vec<u8>>) {
// Combine all packet data into one big chunk and test that the packet reader splits things
let mut all_data = packets.iter().flatten().copied().collect::<Vec<u8>>();
let mut reader = PacketReader::default();
for (i, packet) in packets.into_iter().enumerate() {
std::println!("Checking packet {i}");
loop {
let buffer = reader.buffer();
let amount = std::cmp::min(buffer.len(), all_data.len());
buffer.copy_from_slice(&all_data[..amount]);
let _ = all_data.drain(..amount);
if let Some(read_packet) = reader.advance(amount) {
assert_eq!(read_packet, packet);
break;
}
}
}
}
fn make_reply_with_length(len: usize) -> Vec<u8> {
let mut packet = vec![0; len];
let len = (len - 32) / 4;
// write "len" to bytes 4..8 in the packet
let len_bytes = (len as u32).to_ne_bytes();
packet[4..8].copy_from_slice(&len_bytes);
packet[0] = 1;
packet
}
#[test]
fn fixed_size_packet() {
// packet with a fixed size
let packet = vec![0; 32];
test_packets(vec![packet]);
}
#[test]
fn variable_size_packet() {
// packet with a variable size
let packet = make_reply_with_length(1200);
test_packets(vec![packet]);
}
#[test]
fn test_many_fixed_size_packets() {
let mut packets = vec![];
for _ in 0..100 {
packets.push(vec![0; 32]);
}
test_packets(packets);
}
#[test]
fn test_many_variable_size_packets() {
let mut packets = vec![];
for i in 0..100 {
// for maximum variation, increase packet size in a curved parabola
// defined by -1/25 (x - 50)^2 + 100
let variation = ((i - 50) * (i - 50)) as f32;
let variation = -1.0 / 25.0 * variation + 100.0;
let variation = variation as usize;
// round to a multiple of 4
let variation = variation / 4 * 4;
let mut len = 1200 + variation;
let mut packet = vec![0; len];
assert_eq!(0, len % 4);
len = (len - 32) / 4;
// write "len" to bytes 4..8 in the packet
let len_bytes = (len as u32).to_ne_bytes();
packet[4..8].copy_from_slice(&len_bytes);
packet[0] = 1;
packets.push(packet);
}
test_packets(packets);
}
#[test]
fn test_many_size_packets_mixed() {
let mut packets = vec![];
for i in 0..100 {
// on odds, do a varsize packet
let mut len = if i & 1 == 1 {
// for maximum variation, increase packet size in a curved parabola
// defined by -1/25 (x - 50)^2 + 100
let variation = ((i - 50) * (i - 50)) as f32;
let variation = -1.0 / 25.0 * variation + 100.0;
let variation = variation as usize;
// round to a multiple of 4
let variation = variation / 4 * 4;
1200 + variation
} else {
32
};
assert_eq!(0, len % 4);
let mut packet = vec![0; len];
len = (len - 32) / 4;
// write "len" to bytes 4..8 in the packet
let len_bytes = (len as u32).to_ne_bytes();
packet[4..8].copy_from_slice(&len_bytes);
packet[0] = 1;
packets.push(packet);
}
test_packets(packets);
}
#[test]
fn test_debug_fixed_size_packet() {
// The debug output includes the length of the packet of the packet and how much was
// already read
let mut reader = PacketReader::new();
assert_eq!(std::format!("{:?}", reader), "PacketReader(0/32)");
let _ = reader.advance(15);
assert_eq!(std::format!("{:?}", reader), "PacketReader(15/32)");
let _ = reader.advance(15);
assert_eq!(std::format!("{:?}", reader), "PacketReader(30/32)");
let _ = reader.advance(2);
assert_eq!(std::format!("{:?}", reader), "PacketReader(0/32)");
}
#[test]
fn test_debug_variable_size_packet() {
let packet = make_reply_with_length(1200);
let mut reader = PacketReader::new();
let first_len = 32;
let second_len = 3;
reader.buffer()[..first_len].copy_from_slice(&packet[..first_len]);
let _ = reader.advance(first_len);
reader.buffer()[..second_len].copy_from_slice(&packet[..second_len]);
let _ = reader.advance(second_len);
assert_eq!(std::format!("{:?}", reader), "PacketReader(35/1200)");
}
}