gix_utils/buffers.rs
1use crate::Buffers;
2
3/// Lifecycle
4impl Buffers {
5 /// Use this if there is an input buffer `src` which isn't owned by you, but which should be used as source when
6 /// asking for [`src_and_dest()`](WithForeignSource::src_and_dest()).
7 pub fn use_foreign_src<'a, 'src>(&'a mut self, src: &'src [u8]) -> WithForeignSource<'src, 'a> {
8 self.clear();
9 WithForeignSource {
10 ro_src: Some(src),
11 src: &mut self.src,
12 dest: &mut self.dest,
13 }
14 }
15}
16
17impl Buffers {
18 /// Clear all buffers, which should be called once processing is done.
19 pub fn clear(&mut self) {
20 self.src.clear();
21 self.dest.clear();
22 }
23
24 /// Must be called after every change (i.e. when it's known that `dest` was written.
25 pub fn swap(&mut self) {
26 std::mem::swap(&mut self.src, &mut self.dest);
27 }
28}
29
30/// A utility to do buffer-swapping with, similar to [`Buffers`], but with support for a
31/// read-only one-time buffer as source.
32pub struct WithForeignSource<'src, 'bufs> {
33 /// The original source buffer, or `None` if already altered.
34 pub ro_src: Option<&'src [u8]>,
35 /// The source buffer that will be used after the first call to `swap`.
36 pub src: &'bufs mut Vec<u8>,
37 dest: &'bufs mut Vec<u8>,
38}
39
40impl WithForeignSource<'_, '_> {
41 /// Must be called after every change (i.e. when it's known that `dest` was written.
42 pub fn swap(&mut self) {
43 self.ro_src.take();
44 std::mem::swap(&mut self.src, &mut self.dest);
45 self.dest.clear();
46 }
47 /// Obtain `(source, destination)`, which reads from the read-only source exactly once.
48 pub fn src_and_dest(&mut self) -> (&[u8], &mut Vec<u8>) {
49 match self.ro_src {
50 Some(src) => (src, &mut self.dest),
51 None => (self.src, &mut self.dest),
52 }
53 }
54}