1#![allow(dead_code)]
2
3use flatty::utils::alloc::AlignedBytes;
4use std::ops::{Deref, DerefMut, Range};
5
6pub(crate) struct Buffer {
7 data: AlignedBytes,
8 window: Range<usize>,
9}
10
11impl Buffer {
12 pub(crate) fn new(capacity: usize, align: usize) -> Self {
13 Self {
14 data: AlignedBytes::new(capacity, align),
15 window: 0..0,
16 }
17 }
18
19 pub fn capacity(&self) -> usize {
20 self.data.len()
21 }
22
23 pub(crate) fn preceding_len(&self) -> usize {
24 self.window.start
25 }
26 pub(crate) fn occupied_len(&self) -> usize {
27 self.window.end - self.window.start
28 }
29 pub(crate) fn vacant_len(&self) -> usize {
30 self.capacity() - self.window.end
31 }
32 pub(crate) fn free_len(&self) -> usize {
33 self.preceding_len() + self.vacant_len()
34 }
35
36 pub(crate) fn occupied(&self) -> &[u8] {
37 &self.data[self.window.clone()]
38 }
39 pub(crate) fn occupied_mut(&mut self) -> &mut [u8] {
40 &mut self.data[self.window.clone()]
41 }
42 pub(crate) fn vacant_mut(&mut self) -> &mut [u8] {
43 &mut self.data[self.window.end..]
44 }
45
46 pub(crate) fn clear(&mut self) {
47 self.window = 0..0;
48 }
49 pub(crate) fn skip(&mut self, count: usize) {
51 self.window.start += count;
52 assert!(self.window.start <= self.window.end);
53 if self.window.is_empty() {
54 self.window = 0..0;
55 }
56 }
57 pub(crate) fn advance(&mut self, count: usize) {
59 self.window.end += count;
60 assert!(self.window.end <= self.capacity());
61 }
62 pub(crate) fn make_contiguous(&mut self) {
64 self.data.copy_within(self.window.clone(), 0);
65 self.window = 0..(self.window.end - self.window.start);
66 }
67}
68
69pub struct IoBuffer<P> {
70 pub(crate) pipe: P,
71 pub(crate) buffer: Buffer,
72 pub(crate) poisoned: bool,
73}
74
75impl<P> IoBuffer<P> {
76 pub fn new(pipe: P, capacity: usize, align: usize) -> Self {
77 Self {
78 pipe,
79 buffer: Buffer::new(capacity, align),
80 poisoned: false,
81 }
82 }
83 pub(crate) fn split_mut(&mut self) -> (&mut P, &mut Buffer) {
84 (&mut self.pipe, &mut self.buffer)
85 }
86}
87
88impl<P> Deref for IoBuffer<P> {
89 type Target = [u8];
90 fn deref(&self) -> &Self::Target {
91 self.buffer.occupied()
92 }
93}
94impl<P> DerefMut for IoBuffer<P> {
95 fn deref_mut(&mut self) -> &mut Self::Target {
96 self.buffer.occupied_mut()
97 }
98}