wgtk/util/
io.rs

1//! This module provides extension traits for [`Read`] and [`Write`] for
2//! supporting common formats used within the BigWorld engine.
3
4use std::io::{self, Read, Write, Cursor};
5use std::net::{SocketAddrV4, Ipv4Addr};
6
7use byteorder::{ReadBytesExt, WriteBytesExt, LE, BE};
8use glam::Vec3A;
9
10
11/// An extension to the [`Read`] trait specifically used to decode WG formats
12/// and used for network protocol.
13pub trait WgReadExt: Read {
14
15    /// Reads an unsigned 8 bit integer from the underlying reader.
16    #[inline]
17    fn read_u8(&mut self) -> io::Result<u8> {
18        ReadBytesExt::read_u8(self)
19    }
20
21    /// Reads a signed 8 bit integer from the underlying reader.
22    #[inline]
23    fn read_i8(&mut self) -> io::Result<i8> {
24        ReadBytesExt::read_i8(self)
25    }
26
27    /// Skip the given number of u8 integers.
28    #[inline]
29    fn skip<const N: usize>(&mut self) -> io::Result<()> {
30        let mut buf = [0; N];
31        self.read_exact(&mut buf)?;
32        Ok(())
33    }
34
35    /// Reads an unsigned 16 bit integer from the underlying reader.
36    #[inline]
37    fn read_u16(&mut self) -> io::Result<u16> {
38        ReadBytesExt::read_u16::<LE>(self)
39    }
40
41    /// Reads a signed 16 bit integer from the underlying reader.
42    #[inline]
43    fn read_i16(&mut self) -> io::Result<i16> {
44        ReadBytesExt::read_i16::<LE>(self)
45    }
46
47    /// Reads an unsigned 24 bit integer from the underlying reader.
48    #[inline]
49    fn read_u24(&mut self) -> io::Result<u32> {
50        ReadBytesExt::read_u24::<LE>(self)
51    }
52
53    /// Reads a signed 24 bit integer from the underlying reader.
54    #[inline]
55    fn read_i24(&mut self) -> io::Result<i32> {
56        ReadBytesExt::read_i24::<LE>(self)
57    }
58
59    /// Reads an unsigned 32 bit integer from the underlying reader.
60    #[inline]
61    fn read_u32(&mut self) -> io::Result<u32> {
62        ReadBytesExt::read_u32::<LE>(self)
63    }
64
65    /// Reads a signed 32 bit integer from the underlying reader.
66    #[inline]
67    fn read_i32(&mut self) -> io::Result<i32> {
68        ReadBytesExt::read_i32::<LE>(self)
69    }
70
71    /// Read a packed unsigned 32 bit integer from the underlying reader.
72    #[inline]
73    fn read_packed_u32(&mut self) -> io::Result<u32> {
74        match self.read_u8()? {
75            255 => self.read_u24(),
76            n => Ok(n as u32)
77        }
78    }
79
80    /// Reads an unsigned 64 bit integer from the underlying reader.
81    #[inline]
82    fn read_u64(&mut self) -> io::Result<u64> {
83        ReadBytesExt::read_u64::<LE>(self)
84    }
85
86    /// Reads a signed 64 bit integer from the underlying reader.
87    #[inline]
88    fn read_i64(&mut self) -> io::Result<i64> {
89        ReadBytesExt::read_i64::<LE>(self)
90    }
91
92    /// Reads a IEEE754 single-precision (4 bytes) floating point number 
93    /// from the underlying reader.
94    #[inline]
95    fn read_f32(&mut self) -> io::Result<f32> {
96        ReadBytesExt::read_f32::<LE>(self)
97    }
98
99    /// Read a single boolean from the underlying reader.
100    #[inline]
101    fn read_bool(&mut self) -> io::Result<bool> {
102        Ok(self.read_u8()? != 0)
103    }
104
105    /// Check that the next `N` bytes are the exact same as the given array.
106    #[inline]
107    fn check_exact<const N: usize>(&mut self, bytes: &[u8; N]) -> io::Result<bool> {
108        let mut buf = [0; N];
109        self.read_exact(&mut buf[..])?;
110        Ok(&buf == bytes)
111    }
112
113    /// Read a blob of the given length.
114    fn read_blob(&mut self, len: usize) -> io::Result<Vec<u8>> {
115        // TODO: Maybe use a better uninit approach in the future.
116        let mut buf = vec![0; len];
117        self.read_exact(&mut buf[..])?;
118        Ok(buf)
119    }
120
121    // /// Read a blob into the given destination (this exists to be analog to 
122    // /// [`Self::read_string_into()`] but it's literally a forward call to `read_exact`).
123    // #[inline]
124    // fn read_blob_into(&mut self, dst: &mut [u8]) -> io::Result<()> {
125    //     self.read_exact(dst)
126    // }
127
128    /// Read a blob of a length that is specified with a packed u32 before the 
129    /// actual vector.
130    fn read_blob_variable(&mut self) -> io::Result<Vec<u8>> {
131        let len = self.read_packed_u32()? as usize;
132        let mut buf = vec![0; len];
133        self.read_exact(&mut buf[..])?;
134        Ok(buf)
135    }
136
137    /// Read an UTF-8 string of the given length.
138    fn read_string(&mut self, len: usize) -> io::Result<String> {
139        String::from_utf8(self.read_blob(len)?)
140            .map_err(|_| io::ErrorKind::InvalidData.into())
141    }
142
143    // /// Read an UTF-8 string into the given buffer, returning an error if the data is not
144    // /// valid UTF-8, and the given buffer is zero-ed out.
145    // fn read_string_into(&mut self, dst: &mut str) -> io::Result<()> {
146        
147    //     let bytes = unsafe { dst.as_bytes_mut() };
148    //     self.read_blob_into(bytes)?;
149
150    //     // Here we just run UTF-8 validation, and zero out if it fails.
151    //     std::str::from_utf8(bytes).map(|_| ()).map_err(|_| {
152    //         bytes.fill(0);
153    //         io::ErrorKind::InvalidData.into()
154    //     })
155
156    // }
157
158    /// Read an UTF-8 string of a length that is specified with a packed u32
159    /// before the actual vector.
160    fn read_string_variable(&mut self) -> io::Result<String> {
161        let blob = self.read_blob_variable()?;
162        match String::from_utf8(blob) {
163            Ok(s) => Ok(s),
164            Err(_) => Err(io::Error::new(io::ErrorKind::InvalidData, "invalid utf8 string"))
165        }
166    }
167
168    /// Read a null-terminated string of a fixed length, trailing zeros
169    /// are ignored and if no zero is encountered, an invalid data error
170    /// is returned.
171    fn read_cstring(&mut self, len: usize) -> io::Result<String> {
172        let mut buf = self.read_blob(len)?;
173        let pos = buf.iter().position(|&o| o == 0)
174            .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
175        buf.truncate(pos); // Truncate trailing zeros.
176        String::from_utf8(buf).map_err(|_| io::ErrorKind::InvalidData.into())
177    }
178
179    /// Read a null-terminated string of unknown length.
180    fn read_cstring_variable(&mut self) -> io::Result<String> {
181        // The implementation is intentionally naive because it could be
182        // speed up if the underlying read is buffered.
183        let mut buf = Vec::new();
184        loop {
185            let b = self.read_u8()?;
186            if b == 0 {
187                break
188            }
189            buf.push(b);
190        }
191        String::from_utf8(buf).map_err(|_| io::ErrorKind::InvalidData.into())
192    }
193
194    fn read_sock_addr_v4(&mut self) -> io::Result<SocketAddrV4> {
195        let mut ip_raw = [0; 4];
196        self.read_exact(&mut ip_raw[..])?;
197        let port = ReadBytesExt::read_u16::<BE>(self)?;
198        let _salt = ReadBytesExt::read_u16::<LE>(self)?;
199        Ok(SocketAddrV4::new(Ipv4Addr::from(ip_raw), port))
200    }
201
202    #[inline]
203    fn read_vec3(&mut self) -> io::Result<Vec3A> {
204        Ok(Vec3A::new(
205            self.read_f32()?,
206            self.read_f32()?,
207            self.read_f32()?,
208        ))
209    }
210
211    /// Read a Python Pickle of the given `serde::Deserialize` type, this also
212    /// reads the length of the pickle's data in the packed header.
213    fn read_pickle<'de, T: serde::Deserialize<'de>>(&mut self) -> io::Result<T> {
214        use serde_pickle::DeOptions;
215        let length = self.read_packed_u32()?;
216        Ok(serde_pickle::from_reader(self.take(length as _), DeOptions::new().decode_strings()).unwrap())
217    }
218
219    /// Read the size header for a single structure. To read the header of
220    /// a vector, see `read_vector_head`.
221    fn read_single_head(&mut self) -> io::Result<usize> {
222        Ok(self.read_u32()? as usize)
223    }
224
225    /// Read header for vector of structure, returns `(size, count)` with the
226    /// number of structure of the given size, total size is `size * count`.
227    fn read_vector_head(&mut self) -> io::Result<(usize, usize)> {
228        let sec_size = self.read_u32()? as usize;
229        let sec_count = self.read_u32()? as usize;
230        Ok((sec_size, sec_count))
231    }
232
233    /// Read a full vector of structure, use a function to convert each structures'
234    /// bytes to an object, returns a vector with all vector's objects.
235    fn read_vector<F, T>(&mut self, mut func: F) -> io::Result<Vec<T>>
236    where
237        F: FnMut(&mut Cursor<&Vec<u8>>) -> io::Result<T>
238    {
239
240        let (sec_size, sec_count) = self.read_vector_head()?;
241
242        let mut buf = Vec::with_capacity(sec_size);
243        buf.resize(sec_size, 0);
244
245        let mut data = Vec::with_capacity(sec_count);
246        for _ in 0..sec_count {
247            self.read_exact(&mut buf[..])?;
248            data.push((func)(&mut Cursor::new(&buf))?);
249        }
250
251        Ok(data)
252
253    }
254
255}
256
257
258/// An extension to the [`Write`] trait specifically used to decode WG formats
259/// and used for network protocol.
260pub trait WgWriteExt: Write {
261
262    /// Writes an unsigned 8 bit integer to the underlying writer.
263    #[inline]
264    fn write_u8(&mut self, n: u8) -> io::Result<()> {
265        WriteBytesExt::write_u8(self, n)
266    }
267
268    /// Writes a signed 8 bit integer to the underlying writer.
269    #[inline]
270    fn write_i8(&mut self, n: i8) -> io::Result<()> {
271        WriteBytesExt::write_i8(self, n)
272    }
273
274    /// Writes an unsigned 16 bit integer to the underlying writer.
275    #[inline]
276    fn write_u16(&mut self, n: u16) -> io::Result<()> {
277        WriteBytesExt::write_u16::<LE>(self, n)
278    }
279
280    /// Writes a signed 16 bit integer to the underlying writer.
281    #[inline]
282    fn write_i16(&mut self, n: i16) -> io::Result<()> {
283        WriteBytesExt::write_i16::<LE>(self, n)
284    }
285
286    /// Writes an unsigned 24 bit integer to the underlying writer.
287    #[inline]
288    fn write_u24(&mut self, n: u32) -> io::Result<()> {
289        WriteBytesExt::write_u24::<LE>(self, n)
290    }
291
292    /// Writes a signed 24 bit integer to the underlying writer.
293    #[inline]
294    fn write_i24(&mut self, n: i32) -> io::Result<()> {
295        WriteBytesExt::write_i24::<LE>(self, n)
296    }
297
298    /// Writes an unsigned 32 bit integer to the underlying writer.
299    #[inline]
300    fn write_u32(&mut self, n: u32) -> io::Result<()> {
301        WriteBytesExt::write_u32::<LE>(self, n)
302    }
303
304    /// Writes a signed 32 bit integer to the underlying writer.
305    #[inline]
306    fn write_i32(&mut self, n: i32) -> io::Result<()> {
307        WriteBytesExt::write_i32::<LE>(self, n)
308    }
309
310    /// Writes a packed unsigned 32 bit integer to the underlying writer.
311    fn write_packed_u32(&mut self, n: u32) -> io::Result<()> {
312        if n >= 255 {
313            self.write_u8(255)?;
314            self.write_u24(n)
315        } else {
316            self.write_u8(n as u8)
317        }
318    }
319
320    /// Writes an unsigned 64 bit integer to the underlying writer.
321    #[inline]
322    fn write_u64(&mut self, n: u64) -> io::Result<()> {
323        WriteBytesExt::write_u64::<LE>(self, n)
324    }
325
326    /// Writes a signed 64 bit integer to the underlying writer.
327    #[inline]
328    fn write_i64(&mut self, n: i64) -> io::Result<()> {
329        WriteBytesExt::write_i64::<LE>(self, n)
330    }
331
332    /// Writes a IEEE754 single-precision (4 bytes) floating point number 
333    /// to the underlying writer.
334    #[inline]
335    fn write_f32(&mut self, n: f32) -> io::Result<()> {
336        WriteBytesExt::write_f32::<LE>(self, n)
337    }
338
339    /// Write a single boolean to the underlying writer.
340    #[inline]
341    fn write_bool(&mut self, b: bool) -> io::Result<()> {
342        self.write_u8(b as _)
343    }
344
345    #[inline]
346    fn write_blob(&mut self, data: &[u8]) -> io::Result<()> {
347        self.write_all(data)
348    }
349
350    /// Write a blob with its packed length before the actual data.
351    fn write_blob_variable(&mut self, data: &[u8]) -> io::Result<()> {
352        self.write_packed_u32(data.len() as u32)?;
353        self.write_blob(data)
354    }
355
356    /// Writes a string to the underlying writer. Note that the length of
357    /// the string is not written.
358    #[inline]
359    fn write_string<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
360        self.write_blob(s.as_ref().as_bytes())
361    }
362
363    /// Write a string with its packed length before.
364    #[inline]
365    fn write_string_variable(&mut self, s: &str) -> io::Result<()> {
366        self.write_blob_variable(s.as_bytes())
367    }
368
369    /// Writes a null-terminated string to the underlying writer.
370    #[inline]
371    fn write_cstring<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
372        self.write_string(s)?;
373        self.write_u8(0)
374    }
375
376    /// Write the size header for a single structure. To write the header of
377    /// a vector, see `write_vector_head`.
378    fn write_single_head(&mut self, n: usize) -> io::Result<()> {
379        self.write_u32(n as u32)
380    }
381
382    fn write_sock_addr_v4(&mut self, addr: SocketAddrV4) -> io::Result<()> {
383        self.write_all(&addr.ip().octets()[..])?;
384        WriteBytesExt::write_u16::<BE>(self, addr.port())?;
385        WriteBytesExt::write_u16::<LE>(self, 0)?; // Salt
386        Ok(())
387    }
388
389    fn write_vec3(&mut self, vec: Vec3A) -> io::Result<()> {
390        self.write_f32(vec.x)?;
391        self.write_f32(vec.y)?;
392        self.write_f32(vec.z)?;
393        Ok(())
394    }
395
396    /// Write a Python Pickle from the given `serde::Serialize` value, the pickle's
397    /// data is prefixed with the variable length of the data (like a variable blob
398    /// or string).
399    fn write_pickle<T: serde::Serialize>(&mut self, value: &T) -> io::Result<()> {
400        use serde_pickle::SerOptions;
401        self.write_blob_variable(&serde_pickle::to_vec(value, SerOptions::new().proto_v2()).unwrap())
402    }
403
404    /// Write header for vector of structure.
405    fn write_vector_head(&mut self, size: usize, count: usize) -> io::Result<()> {
406        self.write_u32(size as u32)?;
407        self.write_u32(count as u32)
408    }
409
410    /// Write a vector of structure. Items give in the iterator are converted 
411    /// through the given function. This function take the 
412    fn write_vector<T, I, F>(&mut self, vec: &[T], size: usize, mut func: F) -> io::Result<()>
413    where
414        F: FnMut(&T, &mut Self),
415    {
416        self.write_vector_head(size, vec.len())?;
417        for elt in vec {
418            (func)(elt, self);
419        }
420        Ok(())
421    }
422
423}
424
425impl<R: Read> WgReadExt for R {}
426impl<W: Write> WgWriteExt for W {}
427
428
429/// A wrapper for a [`Read`] or [`Write`] implementor that will increment
430/// an internal counter when a byte is either read or written.
431pub struct IoCounter<I> {
432    inner: I,
433    count: usize,
434}
435
436impl<I> IoCounter<I> {
437
438    #[inline]
439    pub fn new(inner: I) -> Self {
440        Self {
441            inner,
442            count: 0,
443        }
444    }
445
446    #[inline]
447    pub fn count(&self) -> usize {
448        self.count
449    }
450
451    #[inline]
452    pub fn into_inner(self) -> I {
453        self.inner
454    }
455
456}
457
458impl<R: Read> Read for IoCounter<R> {
459
460    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
461        let len = self.inner.read(buf)?;
462        self.count += len;
463        Ok(len)
464    }
465
466    // TODO: Support vectored read later...
467
468}
469
470impl<W: Write> Write for IoCounter<W> {
471
472    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
473        let len = self.inner.write(buf)?;
474        self.count += len;
475        Ok(len)
476    }
477
478    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
479        self.inner.write_all(buf)?;
480        self.count += buf.len();
481        Ok(())
482    }
483
484    #[inline]
485    fn flush(&mut self) -> io::Result<()> {
486        self.inner.flush()
487    }
488
489}