packet/buffer/mod.rs
1// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2// Version 2, December 2004
3//
4// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
5//
6// Everyone is permitted to copy and distribute verbatim or modified
7// copies of this license document, and changing it is allowed as long
8// as the name is changed.
9//
10// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
12//
13// 0. You just DO WHAT THE FUCK YOU WANT TO.
14
15use crate::error::*;
16
17/// A buffer to build packets in.
18///
19/// A `Buffer` is composed of multiple layers, internally an `offset` and
20/// `length` is used to keep track of the current layer, `data()` and
21/// `data_mut()` will always return a slice to the current layer.
22///
23/// # Example
24///
25/// ```
26/// use packet::buffer::{self, Buffer};
27///
28/// // Create a new dynamic buffer, `buffer::Dynamic` is backed by a `Vec<u8>`.
29/// let mut buffer = buffer::Dynamic::new();
30///
31/// // Create a new layer for 20 bytes, calling `next()` increases the offset
32/// // and zeroes the underlying memory.
33/// buffer.next(20);
34///
35/// // Get more memory in the buffer.
36/// buffer.more(4);
37///
38/// // Get the backing data for the buffer.
39/// let data = buffer.into_inner();
40/// assert_eq!(data.len(), 24);
41/// ```
42pub trait Buffer {
43 /// Inner type used by the buffer.
44 type Inner: AsMut<[u8]>;
45
46 /// Convert the buffer into the inner type.
47 fn into_inner(self) -> Self::Inner;
48
49 /// Go to the next layer requesting the given size, zeroeing the layer.
50 fn next(&mut self, size: usize) -> Result<()>;
51
52 /// Request more memory for the same layer, zeroeing the new buffer area.
53 fn more(&mut self, size: usize) -> Result<()>;
54
55 /// Clear the buffer.
56 fn clear(&mut self);
57
58 /// Number of bytes used by the whole buffer.
59 fn used(&self) -> usize;
60
61 /// Offset from the beginning of the whole buffer.
62 fn offset(&self) -> usize;
63
64 /// Length of the current layer.
65 fn length(&self) -> usize;
66
67 /// Get a slice over the current layer.
68 fn data(&self) -> &[u8];
69
70 /// Get a mutable slice over the current layer.
71 fn data_mut(&mut self) -> &mut [u8];
72}
73
74mod dynamic;
75pub use self::dynamic::Buffer as Dynamic;
76
77mod slice;
78pub use self::slice::Buffer as Slice;