Debian Codegraph @

src/base/write/io/offset.rs

raw symbols SCIP
1 // Copyright (c) 2022 Harry [Majored] [[email protected]]
2 // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE)
3
4 use std::io::{Error, IoSlice};
5 use std::pin::Pin;
6 use std::task::{Context, Poll};
7
8 use futures_lite::io::AsyncWrite;
9 use pin_project::pin_project;
10
11 /// A wrapper around an [`AsyncWrite`] implementation which tracks the current byte offset.
12 #[pin_project(project = OffsetWriterProj)]
13 pub struct AsyncOffsetWriter<W> {
14 #[pin]
15 inner: W,
16 offset: u64,
17 }
18
19 impl<W> AsyncOffsetWriter<W>
20 where
21 W: AsyncWrite + Unpin,
22 {
23 /// Constructs a new wrapper from an inner [`AsyncWrite`] writer.
24 pub fn new(inner: W) -> Self {
25 Self { inner, offset: 0 }
26 }
27
28 /// Returns the current byte offset.
29 pub fn offset(&self) -> u64 {
30 self.offset
31 }
32
33 /// Consumes this wrapper and returns the inner [`AsyncWrite`] writer.
34 pub fn into_inner(self) -> W {
35 self.inner
36 }
37
38 pub fn inner_mut(&mut self) -> &mut W {
39 &mut self.inner
40 }
41 }
42
43 impl<W> AsyncWrite for AsyncOffsetWriter<W>
44 where
45 W: AsyncWrite + Unpin,
46 {
47 fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<Result<usize, Error>> {
48 let this = self.project();
49 let poll = this.inner.poll_write(cx, buf);
50
51 if let Poll::Ready(Ok(inner)) = &poll {
52 *this.offset += *inner as u64;
53 }
54
55 poll
56 }
57
58 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
59 self.project().inner.poll_flush(cx)
60 }
61
62 fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
63 self.project().inner.poll_close(cx)
64 }
65
66 fn poll_write_vectored(
67 self: Pin<&mut Self>,
68 cx: &mut Context<'_>,
69 bufs: &[IoSlice<'_>],
70 ) -> Poll<Result<usize, Error>> {
71 self.project().inner.poll_write_vectored(cx, bufs)
72 }
73 }