1
0
Fork 0
forked from wry/wry

autocommit 2022-02-06 16:33:54 CET

This commit is contained in:
Julian Orth 2022-02-06 16:33:54 +01:00
parent c92346324b
commit dc2cb71012
104 changed files with 2563 additions and 4617 deletions

View file

@ -60,6 +60,7 @@ impl<'a> MsgFormatter<'a> {
self.object(obj).uint(event)
}
#[allow(dead_code)]
pub fn array<F: FnOnce(&mut MsgFormatter<'_>)>(&mut self, f: F) -> &mut Self {
let pos = self.buf.out_pos;
self.uint(0);
@ -81,6 +82,14 @@ impl<'a> MsgFormatter<'a> {
self
}
pub fn binary<T: ?Sized>(&mut self, t: &T) -> &mut Self {
self.uint(mem::size_of_val(t) as u32);
self.buf.write(uapi::as_maybe_uninit_bytes(t));
let none = [MaybeUninit::new(0); 4];
self.buf.write(&none[..self.buf.out_pos.wrapping_neg() & 3]);
self
}
pub fn write_len(self) {
assert!(self.buf.out_pos - self.pos >= 8);
assert_eq!(self.pos % 4, 0);

View file

@ -1,3 +1,4 @@
use std::{mem, ptr};
use std::rc::Rc;
use crate::fixed::Fixed;
use crate::globals::GlobalName;
@ -5,12 +6,16 @@ use crate::object::ObjectId;
use crate::utils::buffd::BufFdIn;
use bstr::{BStr, ByteSlice};
use thiserror::Error;
use uapi::OwnedFd;
use uapi::{OwnedFd, Pod};
#[derive(Debug, Error)]
pub enum MsgParserError {
#[error("The message ended unexpectedly")]
UnexpectedEof,
#[error("The binary array contains more than the required number of bytes")]
BinaryArrayTooLarge,
#[error("The size of the binary array is not a multiple of the element size")]
BinaryArraySize,
#[error("The message contained a string of size 0")]
EmptyString,
#[error("Message is missing a required file descriptor")]
@ -56,6 +61,7 @@ impl<'a, 'b> MsgParser<'a, 'b> {
self.int().map(|i| ObjectId::from_raw(i as u32).into())
}
#[allow(dead_code)]
pub fn global(&mut self) -> Result<GlobalName, MsgParserError> {
self.int().map(|i| GlobalName::from_raw(i as u32))
}
@ -105,4 +111,33 @@ impl<'a, 'b> MsgParser<'a, 'b> {
self.pos += cap;
Ok(&self.data[pos..pos + len])
}
pub fn binary<T: Pod>(&mut self) -> Result<T, MsgParserError> {
let array = self.array()?;
if array.len() < mem::size_of::<T>() {
return Err(MsgParserError::UnexpectedEof);
}
if array.len() > mem::size_of::<T>() {
return Err(MsgParserError::BinaryArrayTooLarge);
}
unsafe {
Ok(ptr::read_unaligned(array.as_ptr() as _))
}
}
pub fn binary_array<T: Pod>(&mut self) -> Result<&'b [T], MsgParserError> {
if std::mem::align_of::<T>() > 4 {
panic!("Alignment of binary array element is too large");
};
if std::mem::size_of::<T>() == 0 {
panic!("Size of binary array element is 0");
};
let array = self.array()?;
if array.len() % mem::size_of::<T>() != 0 {
return Err(MsgParserError::BinaryArraySize);
}
unsafe {
Ok(std::slice::from_raw_parts(array.as_ptr() as _, array.len() / mem::size_of::<T>()))
}
}
}