disco_rs/
tag.rs

1/*
2    Copyright David Huseby, All Rights Reserved.
3    SPDX-License-Identifier: Apache-2.0
4*/
5/// Disco streams consist of "tagged data" where a tag is sent before the data and the tag
6/// describes the data that follows. The tag specifies the type of data and the length of data.
7/// Disco is written in terms of a Tag trait and byte array.
8
9/// Tag trait used throughout Disco to describe all of the data that Disco works with. Tags really
10/// just need to be able to encode an arbitrary data type and data length while being able to
11/// deserialize from a &[u8] while also supporing AsRef<[u8]> so that the tag's bytes can be copied
12/// to a message output buffer. This crate copies one by at a time into the byte array
13/// returned by AsMut<[u8]> and calls try_parse() to initiatlize the tag from the bytes. This
14/// allows for a tag to be decrypted, one byte at a time, until we have a valid tag so make sure
15/// that your tagging impl works this way.
16pub trait Tag: AsRef<[u8]> + AsMut<[u8]> + Clone + Default {
17    /// Sets the length of the associated data
18    fn set_data_length(&mut self, size: usize);
19    /// Gets the length of the associated data
20    fn get_data_length(&self) -> usize;
21    /// Tries to parse the tag from the bytes written to it, len specifies how many bytes
22    fn try_parse(&mut self, len: usize) -> bool;
23}
24
25/// Disco operates on pieces of tagged data, this type owns the Tag but contains only a read-only
26/// reference to the data buffer. This is designed so the crate can work on tagged data items
27/// whether or not the caller gives us a raw buffer or not.
28pub trait TaggedData<T: Tag>: AsRef<[u8]> + AsMut<[u8]> + Clone + Default {
29    /// Get the tag
30    fn get_tag(&self) -> &T;
31    /// Get a mutable reference to the tag
32    fn get_tag_mut(&mut self) -> &mut T;
33}