Skip to main content

Packet

Struct Packet 

Source
pub struct Packet {
    pub header: u32,
    pub length: u32,
    pub payload: Vec<u8>,
}
Expand description

A length-prefixed protocol packet.

Fields§

§header: u32§length: u32§payload: Vec<u8>

Implementations§

Source§

impl Packet

Source

pub fn new(payload: Vec<u8>) -> Self

Examples found in repository?
examples/cli.rs (line 244)
243fn write_tcp(stream: &TcpStream, body: Vec<u8>) -> Result<(), DynErr> {
244    let bytes = frame::Packet::new(body).to_bytes();
245    let mut s: &TcpStream = stream;
246    s.write_all(&bytes)?;
247    Ok(())
248}
More examples
Hide additional examples
examples/sanitize_full_sync.rs (line 48)
17fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let mut args = env::args_os().skip(1);
19    let input = args.next().ok_or("missing input frame path")?;
20    let output = args.next().ok_or("missing output frame path")?;
21    if args.next().is_some() {
22        return Err("expected exactly two paths: input and output".into());
23    }
24
25    let bytes = fs::read(&input)?;
26    let (packet, consumed) =
27        Packet::from_bytes(&bytes).ok_or("input is not a complete TCP frame")?;
28    if consumed != bytes.len() {
29        return Err(format!("input contains {} trailing bytes", bytes.len() - consumed).into());
30    }
31    let ChangeFrame::FullSync { mut root } =
32        decode(&packet.payload).ok_or("invalid change frame")?
33    else {
34        return Err("input frame is not a full sync".into());
35    };
36
37    let layout = Layout::from_full_sync(&root)?;
38    let firmware = find_property(&root, "systemFirmwareVersion")
39        .and_then(|value| match value {
40            Value::String(value) => Some(value.as_str()),
41            _ => None,
42        })
43        .unwrap_or("unknown")
44        .to_string();
45    let (nodes, properties) = tree_size(&root);
46
47    sanitize_node(&mut root);
48    let sanitized = Packet::new(encode_full_sync(&root)).to_bytes();
49    fs::write(&output, &sanitized)?;
50
51    eprintln!("model={}", layout.model());
52    eprintln!("firmware={firmware}");
53    eprintln!("faders={}", layout.fader_count());
54    eprintln!("channels={}", layout.channel_count());
55    eprintln!("sources={}", layout.source_count());
56    eprintln!("mixes_per_source={}", layout.mix_count_per_source());
57    eprintln!("input_sources={}", layout.input_source_count());
58    eprintln!("headphones={}", layout.headphone_count());
59    eprintln!("effects={}", layout.effects_count());
60    eprintln!("pads={}", layout.pad_count());
61    eprintln!("sip_call_slots={}", layout.sip_call_slots_count());
62    eprintln!("sip_registrations={}", layout.sip_registration_count());
63    eprintln!("nodes={nodes}");
64    eprintln!("properties={properties}");
65    eprintln!("frame_bytes={}", sanitized.len());
66    Ok(())
67}
Source

pub fn to_bytes(&self) -> Vec<u8> ⓘ

Examples found in repository?
examples/cli.rs (line 244)
243fn write_tcp(stream: &TcpStream, body: Vec<u8>) -> Result<(), DynErr> {
244    let bytes = frame::Packet::new(body).to_bytes();
245    let mut s: &TcpStream = stream;
246    s.write_all(&bytes)?;
247    Ok(())
248}
More examples
Hide additional examples
examples/sanitize_full_sync.rs (line 48)
17fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let mut args = env::args_os().skip(1);
19    let input = args.next().ok_or("missing input frame path")?;
20    let output = args.next().ok_or("missing output frame path")?;
21    if args.next().is_some() {
22        return Err("expected exactly two paths: input and output".into());
23    }
24
25    let bytes = fs::read(&input)?;
26    let (packet, consumed) =
27        Packet::from_bytes(&bytes).ok_or("input is not a complete TCP frame")?;
28    if consumed != bytes.len() {
29        return Err(format!("input contains {} trailing bytes", bytes.len() - consumed).into());
30    }
31    let ChangeFrame::FullSync { mut root } =
32        decode(&packet.payload).ok_or("invalid change frame")?
33    else {
34        return Err("input frame is not a full sync".into());
35    };
36
37    let layout = Layout::from_full_sync(&root)?;
38    let firmware = find_property(&root, "systemFirmwareVersion")
39        .and_then(|value| match value {
40            Value::String(value) => Some(value.as_str()),
41            _ => None,
42        })
43        .unwrap_or("unknown")
44        .to_string();
45    let (nodes, properties) = tree_size(&root);
46
47    sanitize_node(&mut root);
48    let sanitized = Packet::new(encode_full_sync(&root)).to_bytes();
49    fs::write(&output, &sanitized)?;
50
51    eprintln!("model={}", layout.model());
52    eprintln!("firmware={firmware}");
53    eprintln!("faders={}", layout.fader_count());
54    eprintln!("channels={}", layout.channel_count());
55    eprintln!("sources={}", layout.source_count());
56    eprintln!("mixes_per_source={}", layout.mix_count_per_source());
57    eprintln!("input_sources={}", layout.input_source_count());
58    eprintln!("headphones={}", layout.headphone_count());
59    eprintln!("effects={}", layout.effects_count());
60    eprintln!("pads={}", layout.pad_count());
61    eprintln!("sip_call_slots={}", layout.sip_call_slots_count());
62    eprintln!("sip_registrations={}", layout.sip_registration_count());
63    eprintln!("nodes={nodes}");
64    eprintln!("properties={properties}");
65    eprintln!("frame_bytes={}", sanitized.len());
66    Ok(())
67}
Source

pub fn from_bytes(data: &[u8]) -> Option<(Self, usize)>

Parse a packet from bytes, returning it and the total bytes consumed.

Examples found in repository?
examples/cli.rs (line 314)
288fn tcp_reader_loop(
289    stream: Arc<TcpStream>,
290    layout: Shared<Option<Layout>>,
291    root: Shared<Option<Node>>,
292    watch: Arc<AtomicBool>,
293) {
294    let mut buf = Vec::<u8>::with_capacity(8192);
295    let mut chunk = [0u8; 4096];
296    loop {
297        let mut s: &TcpStream = &stream;
298        let n = match s.read(&mut chunk) {
299            Ok(0) => return,
300            Ok(n) => n,
301            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
302            Err(_) => return,
303        };
304        buf.extend_from_slice(&chunk[..n]);
305        loop {
306            match frame::scan_frame(&buf) {
307                FrameScan::Incomplete => break,
308                FrameScan::Desync => {
309                    // TCP frames are byte-aligned (no report stride);
310                    // slide one byte and rescan to resync on a fresh magic.
311                    buf.drain(..1);
312                }
313                FrameScan::Complete { len } => {
314                    let Some((packet, consumed)) = frame::Packet::from_bytes(&buf[..len]) else {
315                        buf.drain(..len);
316                        continue;
317                    };
318                    buf.drain(..consumed);
319                    handle_body(packet.payload, &layout, &root, &watch);
320                }
321            }
322        }
323    }
324}
More examples
Hide additional examples
examples/sanitize_full_sync.rs (line 27)
17fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let mut args = env::args_os().skip(1);
19    let input = args.next().ok_or("missing input frame path")?;
20    let output = args.next().ok_or("missing output frame path")?;
21    if args.next().is_some() {
22        return Err("expected exactly two paths: input and output".into());
23    }
24
25    let bytes = fs::read(&input)?;
26    let (packet, consumed) =
27        Packet::from_bytes(&bytes).ok_or("input is not a complete TCP frame")?;
28    if consumed != bytes.len() {
29        return Err(format!("input contains {} trailing bytes", bytes.len() - consumed).into());
30    }
31    let ChangeFrame::FullSync { mut root } =
32        decode(&packet.payload).ok_or("invalid change frame")?
33    else {
34        return Err("input frame is not a full sync".into());
35    };
36
37    let layout = Layout::from_full_sync(&root)?;
38    let firmware = find_property(&root, "systemFirmwareVersion")
39        .and_then(|value| match value {
40            Value::String(value) => Some(value.as_str()),
41            _ => None,
42        })
43        .unwrap_or("unknown")
44        .to_string();
45    let (nodes, properties) = tree_size(&root);
46
47    sanitize_node(&mut root);
48    let sanitized = Packet::new(encode_full_sync(&root)).to_bytes();
49    fs::write(&output, &sanitized)?;
50
51    eprintln!("model={}", layout.model());
52    eprintln!("firmware={firmware}");
53    eprintln!("faders={}", layout.fader_count());
54    eprintln!("channels={}", layout.channel_count());
55    eprintln!("sources={}", layout.source_count());
56    eprintln!("mixes_per_source={}", layout.mix_count_per_source());
57    eprintln!("input_sources={}", layout.input_source_count());
58    eprintln!("headphones={}", layout.headphone_count());
59    eprintln!("effects={}", layout.effects_count());
60    eprintln!("pads={}", layout.pad_count());
61    eprintln!("sip_call_slots={}", layout.sip_call_slots_count());
62    eprintln!("sip_registrations={}", layout.sip_registration_count());
63    eprintln!("nodes={nodes}");
64    eprintln!("properties={properties}");
65    eprintln!("frame_bytes={}", sanitized.len());
66    Ok(())
67}

Trait Implementations§

Source§

impl Clone for Packet

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Packet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.