binary_util/
interfaces.rs

1// todo: remove this in 4.0.0
2#![allow(deprecated)]
3
4use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
5
6use crate::io::{ByteReader, ByteWriter};
7use crate::types::{i24, u24, vari32, vari64, varu32, varu64, BE, LE};
8
9macro_rules! impl_reader {
10    ($(LE<$t:ty>, $method:ident),*) => {
11        $(
12            impl Reader<LE<$t>> for LE<$t> {
13                fn read(buf: &mut ByteReader) -> Result<LE<$t>, std::io::Error> {
14                    buf.$method().map(LE::new)
15                }
16            }
17        )*
18    };
19    ($(BE<$t:ty>, $method:ident),*) => {
20        $(
21            impl Reader<BE<$t>> for BE<$t> {
22                fn read(buf: &mut ByteReader) -> Result<BE<$t>, std::io::Error> {
23                    buf.$method().map(BE::new)
24                }
25            }
26        )*
27    };
28    ($($t:ty, $method: tt),*) => {
29        $(
30            impl Reader<$t> for $t {
31                fn read(buf: &mut ByteReader) -> Result<$t, std::io::Error> {
32                    buf.$method()
33                }
34            }
35        )*
36    };
37}
38
39macro_rules! impl_writer {
40    ($(LE<$t:ty>, $method:ident),*) => {
41        $(
42            impl Writer for LE<$t> {
43                fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
44                    buf.$method(**self)
45                }
46            }
47        )*
48    };
49    ($(BE<$t:ty>, $method:ident),*) => {
50        $(
51            impl Writer for BE<$t> {
52                fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
53                    buf.$method(**self)
54                }
55            }
56        )*
57    };
58    ($($t:ty, $method: tt),*) => {
59        $(
60            impl Writer for $t {
61                fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
62                    buf.$method(*self)
63                }
64            }
65        )*
66    };
67}
68
69macro_rules! impl_streamable {
70    ($($t:ty),*) => {
71        $(
72            impl Streamable<$t> for $t {}
73        )*
74    };
75}
76
77/// Allows you to read from a `ByteReader` without needing to know the type.
78///
79/// ```ignore
80/// use binary_util::io::{ByteReader, Reader};
81///
82/// pub struct MyStruct {
83///    pub a: u8,
84///    pub b: u8
85/// }
86///
87/// impl Reader for MyStruct {
88///     fn read(&self, buf: &mut ByteReader) -> Result<Self, std::io::Error> {
89///        let a = buf.read_u8()?;
90///        let b = buf.read_u8()?;
91///        Ok(Self { a, b })
92///     }
93/// }
94/// ```
95pub trait Reader<Output> {
96    /// Reads `Self` from a `ByteReader`.
97    ///
98    /// For automatic implementations, use the `#[derive(BinaryIo)]` macro.
99    fn read(buf: &mut ByteReader) -> Result<Output, std::io::Error>;
100
101    /// Reads `Self` from a `&[u8]`.
102    ///
103    /// This is a convenience method that creates a `ByteReader` from the slice and calls `read`.
104    fn read_from_slice(buf: &[u8]) -> Result<Output, std::io::Error> {
105        let mut reader = ByteReader::from(buf);
106        Self::read(&mut reader)
107    }
108}
109
110// default implementations on primitive types.
111impl_reader!(
112    u8,
113    read_u8,
114    i8,
115    read_i8,
116    u16,
117    read_u16,
118    i16,
119    read_i16,
120    u32,
121    read_u32,
122    i32,
123    read_i32,
124    u64,
125    read_u64,
126    i64,
127    read_i64,
128    u128,
129    read_u128,
130    i128,
131    read_i128,
132    f32,
133    read_f32,
134    f64,
135    read_f64,
136    bool,
137    read_bool,
138    char,
139    read_char,
140    String,
141    read_string
142);
143
144// little endian implementations on primitive types.
145impl_reader!(
146    LE<u16>,
147    read_u16_le,
148    LE<u32>,
149    read_u32_le,
150    LE<u64>,
151    read_u64_le,
152    LE<u128>,
153    read_u128_le,
154    LE<i16>,
155    read_i16_le,
156    LE<i32>,
157    read_i32_le,
158    LE<i64>,
159    read_i64_le,
160    LE<i128>,
161    read_i128_le,
162    LE<f32>,
163    read_f32_le,
164    LE<f64>,
165    read_f64_le
166);
167
168// big endian explicit implementations on primitive types.
169impl_reader!(
170    BE<u16>,
171    read_u16,
172    BE<u32>,
173    read_u32,
174    BE<u64>,
175    read_u64,
176    BE<u128>,
177    read_u128,
178    BE<i16>,
179    read_i16,
180    BE<i32>,
181    read_i32,
182    BE<i64>,
183    read_i64,
184    BE<i128>,
185    read_i128,
186    BE<f32>,
187    read_f32,
188    BE<f64>,
189    read_f64
190);
191
192impl<T> Reader<Vec<T>> for Vec<T>
193where
194    T: Reader<T> + Sized,
195{
196    fn read(buf: &mut ByteReader) -> Result<Vec<T>, std::io::Error> {
197        let len = buf.read_var_u32()?;
198        let mut vec = Vec::with_capacity(len as usize);
199        for _ in 0..len {
200            vec.push(T::read(buf)?);
201        }
202        Ok(vec)
203    }
204}
205
206impl<T> Reader<Option<T>> for Option<T>
207where
208    T: Reader<T> + Sized,
209{
210    fn read(buf: &mut ByteReader) -> Result<Option<T>, std::io::Error> {
211        let is_some = buf.read_bool()?;
212        if is_some {
213            Ok(Some(T::read(buf)?))
214        } else {
215            Ok(None)
216        }
217    }
218}
219
220impl Reader<SocketAddr> for SocketAddr {
221    fn read(buf: &mut ByteReader) -> Result<SocketAddr, std::io::Error> {
222        match buf.read_u8()? {
223            4 => {
224                let parts = (
225                    buf.read_u8()?,
226                    buf.read_u8()?,
227                    buf.read_u8()?,
228                    buf.read_u8()?,
229                );
230                let port = buf.read_u16()?;
231                Ok(SocketAddr::V4(SocketAddrV4::new(
232                    Ipv4Addr::new(parts.0, parts.1, parts.2, parts.3),
233                    port,
234                )))
235            }
236            6 => {
237                let _family = buf.read_u16()?;
238                let port = buf.read_u16()?;
239                let flow = buf.read_u32()?;
240                let parts = (
241                    buf.read_u16()?,
242                    buf.read_u16()?,
243                    buf.read_u16()?,
244                    buf.read_u16()?,
245                    buf.read_u16()?,
246                    buf.read_u16()?,
247                    buf.read_u16()?,
248                    buf.read_u16()?,
249                );
250                let address = Ipv6Addr::new(
251                    parts.0, parts.1, parts.2, parts.3, parts.4, parts.5, parts.6, parts.7,
252                );
253                let scope = buf.read_u32()?;
254                Ok(SocketAddr::V6(SocketAddrV6::new(
255                    address, port, flow, scope,
256                )))
257            }
258            _ => Err(std::io::Error::new(
259                std::io::ErrorKind::InvalidData,
260                "Invalid IP version",
261            )),
262        }
263    }
264}
265
266impl Reader<varu32> for varu32 {
267    fn read(buf: &mut ByteReader) -> Result<varu32, std::io::Error> {
268        Ok(varu32(buf.read_var_u32()?))
269    }
270}
271
272impl Reader<vari32> for vari32 {
273    fn read(buf: &mut ByteReader) -> Result<vari32, std::io::Error> {
274        Ok(vari32(buf.read_var_i32()?))
275    }
276}
277
278impl Reader<varu64> for varu64 {
279    fn read(buf: &mut ByteReader) -> Result<varu64, std::io::Error> {
280        Ok(varu64(buf.read_var_u64()?))
281    }
282}
283
284impl Reader<vari64> for vari64 {
285    fn read(buf: &mut ByteReader) -> Result<vari64, std::io::Error> {
286        Ok(vari64(buf.read_var_i64()?))
287    }
288}
289
290impl Reader<LE<u24>> for LE<u24> {
291    fn read(buf: &mut ByteReader) -> Result<LE<u24>, std::io::Error> {
292        Ok(LE(buf.read_u24()?.into()))
293    }
294}
295
296impl Reader<BE<u24>> for BE<u24> {
297    fn read(buf: &mut ByteReader) -> Result<BE<u24>, std::io::Error> {
298        Ok(BE(buf.read_u24()?.into()))
299    }
300}
301
302impl Reader<LE<i24>> for LE<i24> {
303    fn read(buf: &mut ByteReader) -> Result<LE<i24>, std::io::Error> {
304        Ok(LE(buf.read_i24()?.into()))
305    }
306}
307
308impl Reader<BE<i24>> for BE<i24> {
309    fn read(buf: &mut ByteReader) -> Result<BE<i24>, std::io::Error> {
310        Ok(BE(buf.read_i24()?.into()))
311    }
312}
313
314impl Reader<u24> for u24 {
315    fn read(buf: &mut ByteReader) -> Result<u24, std::io::Error> {
316        Ok(u24(buf.read_u24()?))
317    }
318}
319
320impl Reader<i24> for i24 {
321    fn read(buf: &mut ByteReader) -> Result<i24, std::io::Error> {
322        Ok(i24(buf.read_i24()?))
323    }
324}
325
326/// Allows you to write to a `ByteWriter` without needing to know the type.
327///
328/// ```ignore
329/// use binary_util::io::{ByteWriter, Writer};
330///
331/// pub struct MyStruct {
332///   pub a: u8,
333///   pub b: u8
334/// }
335///
336/// impl Writer for MyStruct {
337///     fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
338///         buf.write_u8(self.a)?;
339///         buf.write_u8(self.b)?;
340///         Ok(());
341///     }
342/// }
343/// ```
344pub trait Writer {
345    /// Writes `Self` to a `ByteWriter`.
346    ///
347    /// For automatic implementations, use `#[derive(BinaryEncoder]` macro.
348    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error>;
349
350    /// This is a utility function to write `Self` to a `ByteWriter` without
351    /// needing to create a `ByteWriter` first.
352    fn write_to_bytes(&self) -> Result<ByteWriter, std::io::Error> {
353        let mut buf = ByteWriter::new();
354        self.write(&mut buf)?;
355        Ok(buf)
356    }
357}
358
359// default implementations on primitive types.
360impl_writer!(
361    u8,
362    write_u8,
363    i8,
364    write_i8,
365    u16,
366    write_u16,
367    i16,
368    write_i16,
369    u24,
370    write_u24,
371    i24,
372    write_i24,
373    u32,
374    write_u32,
375    i32,
376    write_i32,
377    u64,
378    write_u64,
379    i64,
380    write_i64,
381    u128,
382    write_u128,
383    i128,
384    write_i128,
385    f32,
386    write_f32,
387    f64,
388    write_f64,
389    bool,
390    write_bool,
391    &str,
392    write_string
393);
394
395// little endian implementations on primitive types.
396impl_writer!(
397    LE<u16>,
398    write_u16_le,
399    LE<u32>,
400    write_u32_le,
401    LE<u64>,
402    write_u64_le,
403    LE<u128>,
404    write_u128_le,
405    LE<i16>,
406    write_i16_le,
407    LE<i32>,
408    write_i32_le,
409    LE<i64>,
410    write_i64_le,
411    LE<i128>,
412    write_i128_le,
413    LE<f32>,
414    write_f32_le,
415    LE<f64>,
416    write_f64_le
417);
418
419// big endian explicit implementations on primitive types.
420impl_writer!(
421    BE<u16>,
422    write_u16,
423    BE<u32>,
424    write_u32,
425    BE<u64>,
426    write_u64,
427    BE<u128>,
428    write_u128,
429    BE<i16>,
430    write_i16,
431    BE<i32>,
432    write_i32,
433    BE<i64>,
434    write_i64,
435    BE<i128>,
436    write_i128,
437    BE<f32>,
438    write_f32,
439    BE<f64>,
440    write_f64
441);
442impl Writer for String {
443    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
444        buf.write_string(self)
445    }
446}
447
448impl Writer for char {
449    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
450        buf.write_char(*self)
451    }
452}
453
454impl<T> Writer for Vec<T>
455where
456    T: Writer + Sized,
457{
458    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
459        buf.write_var_u32(self.len() as u32)?;
460        for item in self {
461            item.write(buf)?;
462        }
463        Ok(())
464    }
465}
466
467impl<T> Writer for Option<T>
468where
469    T: Writer + Sized,
470{
471    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
472        match self {
473            Some(item) => {
474                buf.write_bool(true)?;
475                item.write(buf)?;
476            }
477            None => {
478                buf.write_bool(false)?;
479            }
480        }
481        Ok(())
482    }
483}
484
485impl Writer for SocketAddr {
486    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
487        match self {
488            SocketAddr::V4(addr) => {
489                buf.write_u8(4)?;
490                buf.write(&addr.ip().octets())?;
491                buf.write_u16(addr.port())?;
492            }
493            SocketAddr::V6(addr) => {
494                buf.write_u8(6)?;
495                // family (unused by rust)
496                buf.write_u16(0)?;
497                // port
498                buf.write_u16(addr.port())?;
499                // flow
500                buf.write_u32(addr.flowinfo())?;
501                // address eg: 0:0:0:0:0:ffff:7f00:1
502                buf.write(&addr.ip().octets())?;
503                // scope
504                buf.write_u32(addr.scope_id())?;
505            }
506        }
507        Ok(())
508    }
509}
510
511impl Writer for LE<u24> {
512    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
513        buf.write_u24_le(self.0)
514    }
515}
516
517impl Writer for BE<u24> {
518    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
519        buf.write_u24(self.0)
520    }
521}
522
523impl Writer for LE<i24> {
524    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
525        buf.write_i24_le(self.0)
526    }
527}
528
529impl Writer for BE<i24> {
530    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
531        buf.write_i24(self.0)
532    }
533}
534
535impl Writer for varu32 {
536    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
537        buf.write_var_u32(self.0)
538    }
539}
540
541impl Writer for varu64 {
542    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
543        buf.write_var_u64(self.0)
544    }
545}
546
547impl Writer for vari32 {
548    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
549        buf.write_var_i32(self.0)
550    }
551}
552
553impl Writer for vari64 {
554    fn write(&self, buf: &mut ByteWriter) -> Result<(), std::io::Error> {
555        buf.write_var_i64(self.0)
556    }
557}
558
559///
560/// __**This trait exists only for backwards compatibility.**__
561///
562/// If you wish to read and write from a `ByteReader` or `ByteWriter`,
563/// use the `Reader` and `Writer` traits.
564///
565/// ### New Implementation Example
566/// ```ignore
567/// use binary_util::io::{ByteReader, ByteWriter};
568/// use binary_util::interfaces::{Reader, Writer};
569///
570/// pub struct MyStruct;
571///
572/// impl Reader for MyStruct;
573/// impl Writer for MyStruct;
574/// ```
575///
576/// ## `Streamable`
577/// A trait to parse and unparse header structs from a given buffer.
578///
579/// ```ignore
580/// use binary_util::{Streamable, error::BinaryError};
581///
582/// struct Foo {
583///     bar: u8,
584///     foo_bar: u16
585/// }
586/// impl Streamable for Foo {
587///     fn parse(&self) -> Result<Vec<u8>, BinaryError> {
588///         use std::io::Write;
589///         let mut stream = Vec::<u8>::new();
590///         stream.write_all(&self.bar.parse()?[..])?;
591///         stream.write_all(&self.bar.parse()?[..])?;
592///         Ok(stream)
593///     }
594///
595///     fn compose(source: &[u8], position: &mut usize) -> Result<Self, BinaryError> {
596///         // Streamable is implemented for all primitives, so we can
597///         // just use this implementation to read our properties.
598///         Ok(Self {
599///             bar: u8::compose(&source, position)?,
600///             foo_bar: u16::compose(&source, position)?
601///         })
602///     }
603/// }
604/// ```
605/// <p style="background:rgba(255,181,77,0.16);padding:0.75em;border-left: 2px solid orange;">
606///     <strong>Warning:</strong> This module is deprecated and will be removed in <strong>v0.4.0</strong>.
607/// </p>
608#[deprecated(
609    since = "0.3.0",
610    note = "This module is deprecated and will be removed in v0.4.0. Use the `Reader` and `Writer` traits instead."
611)]
612pub trait Streamable<T>: Reader<T> + Writer {
613    /// Writes `self` to the given buffer.
614    fn parse(&self) -> Result<Vec<u8>, crate::error::BinaryError> {
615        if let Ok(v) = self.write_to_bytes() {
616            Ok(v.as_slice().to_vec())
617        } else {
618            Err(crate::error::BinaryError::RecoverableUnknown)
619        }
620    }
621
622    /// Writes and unwraps `self` to the given buffer.
623    ///
624    /// ⚠️ This method is not fail safe, and will panic if result is Err.
625    fn fparse(&self) -> Vec<u8> {
626        self.parse().unwrap()
627    }
628
629    /// Reads `self` from the given buffer.
630    fn compose(source: &[u8], position: &mut usize) -> Result<T, crate::error::BinaryError>
631    where
632        Self: Sized,
633    {
634        let mut reader = ByteReader::from(&source[*position..]);
635        if let Ok(v) = Self::read(&mut reader) {
636            Ok(v)
637        } else {
638            Err(crate::error::BinaryError::RecoverableUnknown)
639        }
640    }
641
642    /// Reads and unwraps `self` from the given buffer.
643    ///
644    /// ⚠️ This method is not fail safe, and will panic if result is Err.
645    fn fcompose(source: &[u8], position: &mut usize) -> T
646    where
647        Self: Sized,
648    {
649        Self::compose(source, position).unwrap()
650    }
651}
652
653impl_streamable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64, bool, char, String);