async_proto/impls/
git2.rs

1use {
2    std::{
3        future::Future,
4        io::prelude::*,
5        pin::Pin,
6    },
7    tokio::io::{
8        AsyncRead,
9        AsyncReadExt as _,
10        AsyncWrite,
11        AsyncWriteExt as _,
12    },
13    crate::{
14        ErrorContext,
15        Protocol,
16        ReadError,
17        ReadErrorKind,
18        WriteError,
19    },
20};
21
22/// A git object ID uses its native binary representation, a sequence of 20 bytes.
23#[cfg_attr(docsrs, doc(cfg(feature = "git2")))]
24impl Protocol for git2::Oid {
25    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(stream: &'a mut R) -> Pin<Box<dyn Future<Output = Result<Self, ReadError>> + Send + 'a>> {
26        Box::pin(async move {
27            let mut buf = [0; 20];
28            stream.read_exact(&mut buf).await.map_err(|e| ReadError {
29                context: ErrorContext::BuiltIn { for_type: "git2::Oid" },
30                kind: e.into(),
31            })?;
32            Self::from_bytes(&buf).map_err(|e| ReadError {
33                context: ErrorContext::BuiltIn { for_type: "git2::Oid" },
34                kind: ReadErrorKind::Custom(e.to_string()),
35            })
36        })
37    }
38
39    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, sink: &'a mut W) -> Pin<Box<dyn Future<Output = Result<(), WriteError>> + Send + 'a>> {
40        Box::pin(async move {
41            sink.write_all(self.as_bytes()).await.map_err(|e| WriteError {
42                context: ErrorContext::BuiltIn { for_type: "git2::Oid" },
43                kind: e.into(),
44            })?;
45            Ok(())
46        })
47    }
48
49    fn read_sync(stream: &mut impl Read) -> Result<Self, ReadError> {
50        let mut buf = [0; 20];
51        stream.read_exact(&mut buf).map_err(|e| ReadError {
52            context: ErrorContext::BuiltIn { for_type: "git2::Oid" },
53            kind: e.into(),
54        })?;
55        Self::from_bytes(&buf).map_err(|e| ReadError {
56            context: ErrorContext::BuiltIn { for_type: "git2::Oid" },
57            kind: ReadErrorKind::Custom(e.to_string()),
58        })
59    }
60
61    fn write_sync(&self, sink: &mut impl Write) -> Result<(), WriteError> {
62        sink.write_all(self.as_bytes()).map_err(|e| WriteError {
63            context: ErrorContext::BuiltIn { for_type: "git2::Oid" },
64            kind: e.into(),
65        })?;
66        Ok(())
67    }
68}